1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
21 #include "zypp/base/InputStream.h"
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Gettext.h"
24 #include "zypp/base/Function.h"
25 #include "zypp/base/Regex.h"
26 #include "zypp/PathInfo.h"
27 #include "zypp/TmpPath.h"
29 #include "zypp/ServiceInfo.h"
30 #include "zypp/repo/RepoException.h"
31 #include "zypp/RepoManager.h"
33 #include "zypp/media/MediaManager.h"
34 #include "zypp/media/CredentialManager.h"
35 #include "zypp/MediaSetAccess.h"
36 #include "zypp/ExternalProgram.h"
37 #include "zypp/ManagedFile.h"
39 #include "zypp/parser/RepoFileReader.h"
40 #include "zypp/parser/ServiceFileReader.h"
41 #include "zypp/repo/ServiceRepos.h"
42 #include "zypp/repo/yum/Downloader.h"
43 #include "zypp/repo/susetags/Downloader.h"
44 #include "zypp/repo/PluginServices.h"
46 #include "zypp/Target.h" // for Target::targetDistribution() for repo index services
47 #include "zypp/ZYppFactory.h" // to get the Target from ZYpp instance
48 #include "zypp/HistoryLog.h" // to write history :O)
50 #include "zypp/ZYppCallbacks.h"
56 using namespace zypp::repo;
58 #define OPT_PROGRESS const ProgressData::ReceiverFnc & = ProgressData::ReceiverFnc()
60 ///////////////////////////////////////////////////////////////////
63 ///////////////////////////////////////////////////////////////////
66 /** Simple media mounter to access non-downloading URLs e.g. for non-local plaindir repos.
72 /** Ctor provides media access. */
73 MediaMounter( const Url & url_r )
75 media::MediaManager mediamanager;
76 _mid = mediamanager.open( url_r );
77 mediamanager.attach( _mid );
80 /** Ctor releases the media. */
83 media::MediaManager mediamanager;
84 mediamanager.release( _mid );
85 mediamanager.close( _mid );
88 /** Convert a path relative to the media into an absolute path.
90 * Called without argument it returns the path to the medias root directory.
92 Pathname getPathName( const Pathname & path_r = Pathname() ) const
94 media::MediaManager mediamanager;
95 return mediamanager.localPath( _mid, path_r );
99 media::MediaAccessId _mid;
101 ///////////////////////////////////////////////////////////////////
103 /** Check if alias_r is present in repo/service container. */
104 template <class Iterator>
105 inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
107 for_( it, begin_r, end_r )
108 if ( it->alias() == alias_r )
113 template <class Container>
114 inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
115 { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
117 /** Find alias_r in repo/service container. */
118 template <class Iterator>
119 inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
121 for_( it, begin_r, end_r )
122 if ( it->alias() == alias_r )
127 template <class Container>
128 inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
129 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
131 template <class Container>
132 inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
133 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
136 /** \short Generate a related filename from a repo/service infos alias */
137 inline std::string filenameFromAlias( const std::string & alias_r, const std::string & stem_r )
139 std::string filename( alias_r );
140 // replace slashes with underscores
141 str::replaceAll( filename, "/", "_" );
143 filename = Pathname(filename).extend("."+stem_r).asString();
144 MIL << "generating filename for " << stem_r << " [" << alias_r << "] : '" << filename << "'" << endl;
149 * \short Simple callback to collect the results
151 * Classes like RepoFileParser call the callback
152 * once per each repo in a file.
154 * Passing this functor as callback, you can collect
155 * all results at the end, without dealing with async
158 * If targetDistro is set, all repos with non-empty RepoInfo::targetDistribution()
161 * \todo do this through a separate filter
163 struct RepoCollector : private base::NonCopyable
168 RepoCollector(const std::string & targetDistro_)
169 : targetDistro(targetDistro_)
172 bool collect( const RepoInfo &repo )
174 // skip repositories meant for other distros than specified
175 if (!targetDistro.empty()
176 && !repo.targetDistribution().empty()
177 && repo.targetDistribution() != targetDistro)
180 << "Skipping repository meant for '" << repo.targetDistribution()
181 << "' distribution (current distro is '"
182 << targetDistro << "')." << endl;
187 repos.push_back(repo);
192 std::string targetDistro;
194 ////////////////////////////////////////////////////////////////////////////
197 * Reads RepoInfo's from a repo file.
199 * \param file pathname of the file to read.
201 std::list<RepoInfo> repositories_in_file( const Pathname & file )
203 MIL << "repo file: " << file << endl;
204 RepoCollector collector;
205 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
206 return collector.repos;
209 ////////////////////////////////////////////////////////////////////////////
212 * \short List of RepoInfo's from a directory
214 * Goes trough every file ending with ".repo" in a directory and adds all
215 * RepoInfo's contained in that file.
217 * \param dir pathname of the directory to read.
219 std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
221 MIL << "directory " << dir << endl;
222 std::list<RepoInfo> repos;
223 std::list<Pathname> entries;
224 if ( filesystem::readdir( entries, dir, false ) != 0 )
226 // TranslatorExplanation '%s' is a pathname
227 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
230 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
231 for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
233 if (str::regex_match(it->extension(), allowedRepoExt))
235 std::list<RepoInfo> tmp = repositories_in_file( *it );
236 repos.insert( repos.end(), tmp.begin(), tmp.end() );
238 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
239 //MIL << "ok" << endl;
245 ////////////////////////////////////////////////////////////////////////////
247 inline void assert_alias( const RepoInfo & info )
249 if ( info.alias().empty() )
250 ZYPP_THROW( RepoNoAliasException() );
251 // bnc #473834. Maybe we can match the alias against a regex to define
252 // and check for valid aliases
253 if ( info.alias()[0] == '.')
254 ZYPP_THROW(RepoInvalidAliasException(
255 info, _("Repository alias cannot start with dot.")));
258 inline void assert_alias( const ServiceInfo & info )
260 if ( info.alias().empty() )
261 ZYPP_THROW( ServiceNoAliasException() );
262 // bnc #473834. Maybe we can match the alias against a regex to define
263 // and check for valid aliases
264 if ( info.alias()[0] == '.')
265 ZYPP_THROW(ServiceInvalidAliasException(
266 info, _("Service alias cannot start with dot.")));
269 ////////////////////////////////////////////////////////////////////////////
271 inline void assert_urls( const RepoInfo & info )
273 if ( info.baseUrlsEmpty() )
274 ZYPP_THROW( RepoNoUrlException( info ) );
277 inline void assert_url( const ServiceInfo & info )
279 if ( ! info.url().isValid() )
280 ZYPP_THROW( ServiceNoUrlException( info ) );
283 ////////////////////////////////////////////////////////////////////////////
286 * \short Calculates the raw cache path for a repository, this is usually
287 * /var/cache/zypp/alias
289 inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
292 return opt.repoRawCachePath / info.escaped_alias();
296 * \short Calculates the raw product metadata path for a repository, this is
297 * inside the raw cache dir, plus an optional path where the metadata is.
299 * It should be different only for repositories that are not in the root of
301 * for example /var/cache/zypp/alias/addondir
303 inline Pathname rawproductdata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
306 return opt.repoRawCachePath / info.escaped_alias() / info.path();
310 * \short Calculates the packages cache path for a repository
312 inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
315 return opt.repoPackagesCachePath / info.escaped_alias();
319 * \short Calculates the solv cache path for a repository
321 inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
324 return opt.repoSolvCachePath / info.escaped_alias();
327 ////////////////////////////////////////////////////////////////////////////
329 /** Functor collecting ServiceInfos into a ServiceSet. */
330 class ServiceCollector
333 typedef std::set<ServiceInfo> ServiceSet;
335 ServiceCollector( ServiceSet & services_r )
336 : _services( services_r )
339 bool operator()( const ServiceInfo & service_r ) const
341 _services.insert( service_r );
346 ServiceSet & _services;
348 ////////////////////////////////////////////////////////////////////////////
351 ///////////////////////////////////////////////////////////////////
353 std::list<RepoInfo> readRepoFile( const Url & repo_file )
355 // no interface to download a specific file, using workaround:
356 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
358 Pathname path(url.getPathName());
359 url.setPathName ("/");
360 MediaSetAccess access(url);
361 Pathname local = access.provideFile(path);
363 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
365 return repositories_in_file(local);
368 ///////////////////////////////////////////////////////////////////
370 // class RepoManagerOptions
372 ////////////////////////////////////////////////////////////////////
374 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
376 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
377 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
378 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
379 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
380 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
381 knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
382 pluginsPath = Pathname::assertprefix( root_r, ZConfig::instance().pluginsPath() );
383 probe = ZConfig::instance().repo_add_probe();
388 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
390 RepoManagerOptions ret;
391 ret.repoCachePath = root_r;
392 ret.repoRawCachePath = root_r/"raw";
393 ret.repoSolvCachePath = root_r/"solv";
394 ret.repoPackagesCachePath = root_r/"packages";
395 ret.knownReposPath = root_r/"repos.d";
396 ret.knownServicesPath = root_r/"services.d";
397 ret.pluginsPath = root_r/"plugins";
398 ret.rootDir = root_r;
402 ///////////////////////////////////////////////////////////////////
403 /// \class RepoManager::Impl
404 /// \brief RepoManager implementation.
406 ///////////////////////////////////////////////////////////////////
407 struct RepoManager::Impl
410 Impl( const RepoManagerOptions &opt )
413 init_knownServices();
414 init_knownRepositories();
418 bool repoEmpty() const { return _repos.empty(); }
419 RepoSizeType repoSize() const { return _repos.size(); }
420 RepoConstIterator repoBegin() const { return _repos.begin(); }
421 RepoConstIterator repoEnd() const { return _repos.end(); }
423 bool hasRepo( const std::string & alias ) const
424 { return foundAliasIn( alias, _repos ); }
426 RepoInfo getRepo( const std::string & alias ) const
428 RepoConstIterator it( findAlias( alias, _repos ) );
429 return it == _repos.end() ? RepoInfo::noRepo : *it;
433 Pathname metadataPath( const RepoInfo & info ) const
434 { return rawcache_path_for_repoinfo( _options, info ); }
436 Pathname packagesPath( const RepoInfo & info ) const
437 { return packagescache_path_for_repoinfo( _options, info ); }
439 RepoStatus metadataStatus( const RepoInfo & info ) const;
441 RefreshCheckStatus checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy );
443 void refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, OPT_PROGRESS );
445 void cleanMetadata( const RepoInfo & info, OPT_PROGRESS );
447 void cleanPackages( const RepoInfo & info, OPT_PROGRESS );
449 void buildCache( const RepoInfo & info, CacheBuildPolicy policy, OPT_PROGRESS );
451 repo::RepoType probe( const Url & url, const Pathname & path = Pathname() ) const;
453 void cleanCacheDirGarbage( OPT_PROGRESS );
455 void cleanCache( const RepoInfo & info, OPT_PROGRESS );
457 bool isCached( const RepoInfo & info ) const
458 { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
460 RepoStatus cacheStatus( const RepoInfo & info ) const
461 { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
463 void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
465 void addRepository( const RepoInfo & info, OPT_PROGRESS );
467 void addRepositories( const Url & url, OPT_PROGRESS );
469 void removeRepository( const RepoInfo & info, OPT_PROGRESS );
471 void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
473 RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
474 RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
477 bool serviceEmpty() const { return _services.empty(); }
478 ServiceSizeType serviceSize() const { return _services.size(); }
479 ServiceConstIterator serviceBegin() const { return _services.begin(); }
480 ServiceConstIterator serviceEnd() const { return _services.end(); }
482 bool hasService( const std::string & alias ) const
483 { return foundAliasIn( alias, _services ); }
485 ServiceInfo getService( const std::string & alias ) const
487 ServiceConstIterator it( findAlias( alias, _services ) );
488 return it == _services.end() ? ServiceInfo::noService : *it;
492 void addService( const ServiceInfo & service );
493 void addService( const std::string & alias, const Url & url )
494 { addService( ServiceInfo( alias, url ) ); }
496 void removeService( const std::string & alias );
497 void removeService( const ServiceInfo & service )
498 { removeService( service.alias() ); }
500 void refreshServices();
502 void refreshService( const std::string & alias );
503 void refreshService( const ServiceInfo & service )
504 { refreshService( service.alias() ); }
506 void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
508 repo::ServiceType probeService( const Url & url ) const;
511 void saveService( ServiceInfo & service ) const;
513 Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
515 std::string generateFilename( const RepoInfo & info ) const
516 { return filenameFromAlias( info.alias(), "repo" ); }
518 std::string generateFilename( const ServiceInfo & info ) const
519 { return filenameFromAlias( info.alias(), "service" ); }
521 void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
523 Pathname base = solv_path_for_repoinfo( _options, info );
524 filesystem::assert_dir(base);
525 status.saveToCookieFile( base / "cookie" );
528 void touchIndexFile( const RepoInfo & info );
530 template<typename OutputIterator>
531 void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
533 MatchServiceAlias filter( alias );
534 std::copy( boost::make_filter_iterator( filter, _repos.begin(), _repos.end() ),
535 boost::make_filter_iterator( filter, _repos.end(), _repos.end() ),
540 void init_knownServices();
541 void init_knownRepositories();
544 RepoManagerOptions _options;
546 ServiceSet _services;
549 friend Impl * rwcowClone<Impl>( const Impl * rhs );
550 /** clone for RWCOW_pointer */
552 { return new Impl( *this ); }
554 ///////////////////////////////////////////////////////////////////
556 /** \relates RepoManager::Impl Stream output */
557 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
558 { return str << "RepoManager::Impl"; }
560 ///////////////////////////////////////////////////////////////////
562 void RepoManager::Impl::saveService( ServiceInfo & service ) const
564 filesystem::assert_dir( _options.knownServicesPath );
565 Pathname servfile = generateNonExistingName( _options.knownServicesPath,
566 generateFilename( service ) );
567 service.setFilepath( servfile );
569 MIL << "saving service in " << servfile << endl;
571 std::ofstream file( servfile.c_str() );
574 // TranslatorExplanation '%s' is a filename
575 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
577 service.dumpAsIniOn( file );
578 MIL << "done" << endl;
582 * Generate a non existing filename in a directory, using a base
583 * name. For example if a directory contains 3 files
589 * If you try to generate a unique filename for this directory,
590 * based on "ruu" you will get "ruu", but if you use the base
591 * "foo" you will get "foo_1"
593 * \param dir Directory where the file needs to be unique
594 * \param basefilename string to base the filename on.
596 Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
597 const std::string & basefilename ) const
599 std::string final_filename = basefilename;
601 while ( PathInfo(dir + final_filename).isExist() )
603 final_filename = basefilename + "_" + str::numstring(counter);
606 return dir + Pathname(final_filename);
609 ////////////////////////////////////////////////////////////////////////////
611 void RepoManager::Impl::init_knownServices()
613 Pathname dir = _options.knownServicesPath;
614 std::list<Pathname> entries;
615 if (PathInfo(dir).isExist())
617 if ( filesystem::readdir( entries, dir, false ) != 0 )
619 // TranslatorExplanation '%s' is a pathname
620 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
623 //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
624 for_(it, entries.begin(), entries.end() )
626 parser::ServiceFileReader(*it, ServiceCollector(_services));
630 repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
633 void RepoManager::Impl::init_knownRepositories()
635 MIL << "start construct known repos" << endl;
637 if ( PathInfo(_options.knownReposPath).isExist() )
639 std::list<std::string> repoEscAliases;
640 for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
642 // set the metadata path for the repo
643 repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
644 // set the downloaded packages path for the repo
645 repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
647 _repos.insert( repoInfo );
648 repoEscAliases.push_back(repoInfo.escaped_alias());
650 repoEscAliases.sort();
652 // delete metadata folders without corresponding repo (e.g. old tmp directories)
653 for ( const Pathname & cachePath : { _options.repoRawCachePath
654 , _options.repoSolvCachePath } )
656 std::list<std::string> entries;
657 if ( filesystem::readdir( entries, cachePath, false ) == 0 )
660 std::set<std::string> oldfiles;
661 set_difference( entries.begin(), entries.end(), repoEscAliases.begin(), repoEscAliases.end(),
662 std::inserter( oldfiles, oldfiles.end() ) );
663 for ( const std::string & old : oldfiles )
665 if ( old == Repository::systemRepoAlias() ) // don't remove the @System solv file
667 filesystem::recursive_rmdir( cachePath / old );
672 MIL << "end construct known repos" << endl;
675 ///////////////////////////////////////////////////////////////////
677 RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
679 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
680 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
682 RepoType repokind = info.type();
683 // If unknown, probe the local metadata
684 if ( repokind == RepoType::NONE )
685 repokind = probe( productdatapath.asUrl() );
688 switch ( repokind.toEnum() )
690 case RepoType::RPMMD_e :
691 status = RepoStatus( productdatapath/"repodata/repomd.xml");
694 case RepoType::YAST2_e :
695 status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
698 case RepoType::RPMPLAINDIR_e :
699 status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
702 case RepoType::NONE_e :
703 // Return default RepoStatus in case of RepoType::NONE
704 // indicating it should be created?
705 // ZYPP_THROW(RepoUnknownTypeException());
712 void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
714 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
716 RepoType repokind = info.type();
717 if ( repokind.toEnum() == RepoType::NONE_e )
718 // unknown, probe the local metadata
719 repokind = probe( productdatapath.asUrl() );
720 // if still unknown, just return
721 if (repokind == RepoType::NONE_e)
725 switch ( repokind.toEnum() )
727 case RepoType::RPMMD_e :
728 p = Pathname(productdatapath + "/repodata/repomd.xml");
731 case RepoType::YAST2_e :
732 p = Pathname(productdatapath + "/content");
735 case RepoType::RPMPLAINDIR_e :
736 p = Pathname(productdatapath + "/cookie");
739 case RepoType::NONE_e :
744 // touch the file, ignore error (they are logged anyway)
745 filesystem::touch(p);
749 RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
754 MIL << "Going to try to check whether refresh is needed for " << url << endl;
756 // first check old (cached) metadata
757 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
758 filesystem::assert_dir( mediarootpath );
759 RepoStatus oldstatus = metadataStatus( info );
761 if ( oldstatus.empty() )
763 MIL << "No cached metadata, going to refresh" << endl;
764 return REFRESH_NEEDED;
768 if ( url.schemeIsVolatile() )
770 MIL << "never refresh CD/DVD" << endl;
771 return REPO_UP_TO_DATE;
773 if ( url.schemeIsLocal() )
775 policy = RefreshIfNeededIgnoreDelay;
779 // now we've got the old (cached) status, we can decide repo.refresh.delay
780 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
782 // difference in seconds
783 double diff = difftime(
784 (Date::ValueType)Date::now(),
785 (Date::ValueType)oldstatus.timestamp()) / 60;
787 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
788 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
789 DBG << "last refresh = " << diff << " minutes ago" << endl;
791 if ( diff < ZConfig::instance().repo_refresh_delay() )
795 WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
799 MIL << "Repository '" << info.alias()
800 << "' has been refreshed less than repo.refresh.delay ("
801 << ZConfig::instance().repo_refresh_delay()
802 << ") minutes ago. Advising to skip refresh" << endl;
803 return REPO_CHECK_DELAYED;
808 // To test the new matadta create temp dir as sibling of mediarootpath
809 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
811 repo::RepoType repokind = info.type();
812 // if unknown: probe it
813 if ( repokind == RepoType::NONE )
814 repokind = probe( url, info.path() );
816 // retrieve newstatus
817 RepoStatus newstatus;
818 switch ( repokind.toEnum() )
820 case RepoType::RPMMD_e:
822 MediaSetAccess media( url );
823 newstatus = yum::Downloader( info, mediarootpath ).status( media );
827 case RepoType::YAST2_e:
829 MediaSetAccess media( url );
830 newstatus = susetags::Downloader( info, mediarootpath ).status( media );
834 case RepoType::RPMPLAINDIR_e:
835 newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
839 case RepoType::NONE_e:
840 ZYPP_THROW( RepoUnknownTypeException( info ) );
845 bool refresh = false;
846 if ( oldstatus == newstatus )
848 MIL << "repo has not changed" << endl;
849 if ( policy == RefreshForced )
851 MIL << "refresh set to forced" << endl;
857 MIL << "repo has changed, going to refresh" << endl;
862 touchIndexFile(info);
864 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
867 catch ( const Exception &e )
870 ERR << "refresh check failed for " << url << endl;
874 return REFRESH_NEEDED; // default
878 void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
883 // we will throw this later if no URL checks out fine
884 RepoException rexception(_PL("Valid metadata not found at specified URL",
885 "Valid metadata not found at specified URLs",
886 info.baseUrlsSize() ) );
888 // try urls one by one
889 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
895 // check whether to refresh metadata
896 // if the check fails for this url, it throws, so another url will be checked
897 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
900 MIL << "Going to refresh metadata from " << url << endl;
902 repo::RepoType repokind = info.type();
904 // if the type is unknown, try probing.
905 if ( repokind == RepoType::NONE )
908 repokind = probe( *it, info.path() );
910 if (repokind.toEnum() != RepoType::NONE_e)
912 // Adjust the probed type in RepoInfo
913 info.setProbedType( repokind ); // lazy init!
914 //save probed type only for repos in system
915 for_( it, repoBegin(), repoEnd() )
917 if ( info.alias() == (*it).alias() )
919 RepoInfo modifiedrepo = info;
920 modifiedrepo.setType( repokind );
921 modifyRepository( info.alias(), modifiedrepo );
928 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
929 if( filesystem::assert_dir(mediarootpath) )
931 Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
935 // create temp dir as sibling of mediarootpath
936 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
937 if( tmpdir.path().empty() )
939 Exception ex(_("Can't create metadata cache directory."));
943 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
944 ( repokind.toEnum() == RepoType::YAST2_e ) )
946 MediaSetAccess media(url);
947 shared_ptr<repo::Downloader> downloader_ptr;
949 MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
951 if ( repokind.toEnum() == RepoType::RPMMD_e )
952 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
954 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
957 * Given a downloader, sets the other repos raw metadata
958 * path as cache paths for the fetcher, so if another
959 * repo has the same file, it will not download it
960 * but copy it from the other repository
962 for_( it, repoBegin(), repoEnd() )
964 Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
965 if ( PathInfo(cachepath).isExist() )
966 downloader_ptr->addCachePath(cachepath);
969 downloader_ptr->download( media, tmpdir.path() );
971 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
973 MediaMounter media( url );
974 RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) ); // dir status
976 Pathname productpath( tmpdir.path() / info.path() );
977 filesystem::assert_dir( productpath );
978 newstatus.saveToCookieFile( productpath/"cookie" );
982 ZYPP_THROW(RepoUnknownTypeException());
985 // ok we have the metadata, now exchange
987 filesystem::exchange( tmpdir.path(), mediarootpath );
992 catch ( const Exception &e )
995 ERR << "Trying another url..." << endl;
997 // remember the exception caught for the *first URL*
998 // if all other URLs fail, the rexception will be thrown with the
999 // cause of the problem of the first URL remembered
1000 if (it == info.baseUrlsBegin())
1001 rexception.remember(e);
1004 ERR << "No more urls..." << endl;
1005 ZYPP_THROW(rexception);
1008 ////////////////////////////////////////////////////////////////////////////
1010 void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1012 ProgressData progress(100);
1013 progress.sendTo(progressfnc);
1015 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1020 void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1022 ProgressData progress(100);
1023 progress.sendTo(progressfnc);
1025 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1030 void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1033 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1034 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1036 if( filesystem::assert_dir(_options.repoCachePath) )
1038 Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1041 RepoStatus raw_metadata_status = metadataStatus(info);
1042 if ( raw_metadata_status.empty() )
1044 /* if there is no cache at this point, we refresh the raw
1045 in case this is the first time - if it's !autorefresh,
1046 we may still refresh */
1047 refreshMetadata(info, RefreshIfNeeded, progressrcv );
1048 raw_metadata_status = metadataStatus(info);
1051 bool needs_cleaning = false;
1052 if ( isCached( info ) )
1054 MIL << info.alias() << " is already cached." << endl;
1055 RepoStatus cache_status = cacheStatus(info);
1057 if ( cache_status == raw_metadata_status )
1059 MIL << info.alias() << " cache is up to date with metadata." << endl;
1060 if ( policy == BuildIfNeeded ) {
1064 MIL << info.alias() << " cache rebuild is forced" << endl;
1068 needs_cleaning = true;
1071 ProgressData progress(100);
1072 callback::SendReport<ProgressReport> report;
1073 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1074 progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1082 MIL << info.alias() << " building cache..." << info.type() << endl;
1084 Pathname base = solv_path_for_repoinfo( _options, info);
1086 if( filesystem::assert_dir(base) )
1088 Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1092 if( ! PathInfo(base).userMayW() )
1094 Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1097 Pathname solvfile = base / "solv";
1100 repo::RepoType repokind = info.type();
1102 // if the type is unknown, try probing.
1103 switch ( repokind.toEnum() )
1105 case RepoType::NONE_e:
1106 // unknown, probe the local metadata
1107 repokind = probe( productdatapath.asUrl() );
1113 MIL << "repo type is " << repokind << endl;
1115 switch ( repokind.toEnum() )
1117 case RepoType::RPMMD_e :
1118 case RepoType::YAST2_e :
1119 case RepoType::RPMPLAINDIR_e :
1121 // Take care we unlink the solvfile on exception
1122 ManagedFile guard( solvfile, filesystem::unlink );
1123 scoped_ptr<MediaMounter> forPlainDirs;
1125 ExternalProgram::Arguments cmd;
1126 cmd.push_back( "repo2solv.sh" );
1127 // repo2solv expects -o as 1st arg!
1128 cmd.push_back( "-o" );
1129 cmd.push_back( solvfile.asString() );
1130 cmd.push_back( "-X" ); // autogenerate pattern from pattern-package
1132 if ( repokind == RepoType::RPMPLAINDIR )
1134 forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1135 // recusive for plaindir as 2nd arg!
1136 cmd.push_back( "-R" );
1137 // FIXME this does only work form dir: URLs
1138 cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1141 cmd.push_back( productdatapath.asString() );
1143 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1144 std::string errdetail;
1146 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1147 WAR << " " << output;
1148 if ( errdetail.empty() ) {
1149 errdetail = prog.command();
1152 errdetail += output;
1155 int ret = prog.close();
1158 RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1159 ex.remember( errdetail );
1164 guard.resetDispose();
1168 ZYPP_THROW(RepoUnknownTypeException( _("Unhandled repository type") ));
1171 // update timestamp and checksum
1172 setCacheStatus(info, raw_metadata_status);
1173 MIL << "Commit cache.." << endl;
1177 ////////////////////////////////////////////////////////////////////////////
1179 repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1181 MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1183 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1185 // Handle non existing local directory in advance, as
1186 // MediaSetAccess does not support it.
1187 MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1188 return repo::RepoType::NONE;
1191 // prepare exception to be thrown if the type could not be determined
1192 // due to a media exception. We can't throw right away, because of some
1193 // problems with proxy servers returning an incorrect error
1194 // on ftp file-not-found(bnc #335906). Instead we'll check another types
1197 // TranslatorExplanation '%s' is an URL
1198 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1199 bool gotMediaException = false;
1202 MediaSetAccess access(url);
1205 if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1207 MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1208 return repo::RepoType::RPMMD;
1211 catch ( const media::MediaException &e )
1214 DBG << "problem checking for repodata/repomd.xml file" << endl;
1216 gotMediaException = true;
1221 if ( access.doesFileExist(path/"/content") )
1223 MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1224 return repo::RepoType::YAST2;
1227 catch ( const media::MediaException &e )
1230 DBG << "problem checking for content file" << endl;
1232 gotMediaException = true;
1235 // if it is a non-downloading URL denoting a directory
1236 if ( ! url.schemeIsDownloading() )
1238 MediaMounter media( url );
1239 if ( PathInfo(media.getPathName()/path).isDir() )
1241 // allow empty dirs for now
1242 MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1243 return repo::RepoType::RPMPLAINDIR;
1247 catch ( const Exception &e )
1250 // TranslatorExplanation '%s' is an URL
1251 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1256 if (gotMediaException)
1259 MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1260 return repo::RepoType::NONE;
1263 ////////////////////////////////////////////////////////////////////////////
1265 void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1267 MIL << "Going to clean up garbage in cache dirs" << endl;
1269 ProgressData progress(300);
1270 progress.sendTo(progressrcv);
1273 std::list<Pathname> cachedirs;
1274 cachedirs.push_back(_options.repoRawCachePath);
1275 cachedirs.push_back(_options.repoPackagesCachePath);
1276 cachedirs.push_back(_options.repoSolvCachePath);
1278 for_( dir, cachedirs.begin(), cachedirs.end() )
1280 if ( PathInfo(*dir).isExist() )
1282 std::list<Pathname> entries;
1283 if ( filesystem::readdir( entries, *dir, false ) != 0 )
1284 // TranslatorExplanation '%s' is a pathname
1285 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1287 unsigned sdircount = entries.size();
1288 unsigned sdircurrent = 1;
1289 for_( subdir, entries.begin(), entries.end() )
1291 // if it does not belong known repo, make it disappear
1293 for_( r, repoBegin(), repoEnd() )
1294 if ( subdir->basename() == r->escaped_alias() )
1295 { found = true; break; }
1297 if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1298 filesystem::recursive_rmdir( *subdir );
1300 progress.set( progress.val() + sdircurrent * 100 / sdircount );
1305 progress.set( progress.val() + 100 );
1310 ////////////////////////////////////////////////////////////////////////////
1312 void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1314 ProgressData progress(100);
1315 progress.sendTo(progressrcv);
1318 MIL << "Removing raw metadata cache for " << info.alias() << endl;
1319 filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1324 ////////////////////////////////////////////////////////////////////////////
1326 void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1329 Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1331 if ( ! PathInfo(solvfile).isExist() )
1332 ZYPP_THROW(RepoNotCachedException(info));
1334 sat::Pool::instance().reposErase( info.alias() );
1337 Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1338 // test toolversion in order to rebuild solv file in case
1339 // it was written by an old libsolv-tool parser.
1341 // Known version strings used:
1345 sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1346 if ( toolversion.begin().asString().empty() )
1348 repo.eraseFromPool();
1349 ZYPP_THROW(Exception("Solv-file was created by old parser."));
1351 // else: up-to-date (or even newer).
1353 catch ( const Exception & exp )
1356 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1357 cleanCache( info, progressrcv );
1358 buildCache( info, BuildIfNeeded, progressrcv );
1360 sat::Pool::instance().addRepoSolv( solvfile, info );
1364 ////////////////////////////////////////////////////////////////////////////
1366 void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1370 ProgressData progress(100);
1371 callback::SendReport<ProgressReport> report;
1372 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1373 progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1376 MIL << "Try adding repo " << info << endl;
1378 RepoInfo tosave = info;
1379 if ( _repos.find(tosave) != _repos.end() )
1380 ZYPP_THROW(RepoAlreadyExistsException(info));
1382 // check the first url for now
1383 if ( _options.probe )
1385 DBG << "unknown repository type, probing" << endl;
1387 RepoType probedtype;
1388 probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1389 if ( tosave.baseUrlsSize() > 0 )
1391 if ( probedtype == RepoType::NONE )
1392 ZYPP_THROW(RepoUnknownTypeException());
1394 tosave.setType(probedtype);
1400 // assert the directory exists
1401 filesystem::assert_dir(_options.knownReposPath);
1403 Pathname repofile = generateNonExistingName(
1404 _options.knownReposPath, generateFilename(tosave));
1405 // now we have a filename that does not exists
1406 MIL << "Saving repo in " << repofile << endl;
1408 std::ofstream file(repofile.c_str());
1411 // TranslatorExplanation '%s' is a filename
1412 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1415 tosave.dumpAsIniOn(file);
1416 tosave.setFilepath(repofile);
1417 tosave.setMetadataPath( metadataPath( tosave ) );
1418 tosave.setPackagesPath( packagesPath( tosave ) );
1420 // We chould fix the API as we must injet those paths
1421 // into the repoinfo in order to keep it usable.
1422 RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1423 oinfo.setMetadataPath( metadataPath( tosave ) );
1424 oinfo.setPackagesPath( packagesPath( tosave ) );
1426 _repos.insert(tosave);
1430 // check for credentials in Urls
1431 bool havePasswords = false;
1432 for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1433 if ( urlit->hasCredentialsInAuthority() )
1435 havePasswords = true;
1438 // save the credentials
1439 if ( havePasswords )
1441 media::CredentialManager cm(
1442 media::CredManagerOptions(_options.rootDir) );
1444 for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1445 if (urlit->hasCredentialsInAuthority())
1446 //! \todo use a method calling UI callbacks to ask where to save creds?
1447 cm.saveInUser(media::AuthData(*urlit));
1450 HistoryLog().addRepository(tosave);
1453 MIL << "done" << endl;
1457 void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1459 std::list<RepoInfo> repos = readRepoFile(url);
1460 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1464 // look if the alias is in the known repos.
1465 for_ ( kit, repoBegin(), repoEnd() )
1467 if ( (*it).alias() == (*kit).alias() )
1469 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1470 ZYPP_THROW(RepoAlreadyExistsException(*it));
1475 std::string filename = Pathname(url.getPathName()).basename();
1477 if ( filename == Pathname() )
1479 // TranslatorExplanation '%s' is an URL
1480 ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1483 // assert the directory exists
1484 filesystem::assert_dir(_options.knownReposPath);
1486 Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1487 // now we have a filename that does not exists
1488 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1490 std::ofstream file(repofile.c_str());
1493 // TranslatorExplanation '%s' is a filename
1494 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1497 for ( std::list<RepoInfo>::iterator it = repos.begin();
1501 MIL << "Saving " << (*it).alias() << endl;
1502 it->setFilepath(repofile.asString());
1503 it->dumpAsIniOn(file);
1506 HistoryLog(_options.rootDir).addRepository(*it);
1509 MIL << "done" << endl;
1512 ////////////////////////////////////////////////////////////////////////////
1514 void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1516 ProgressData progress;
1517 callback::SendReport<ProgressReport> report;
1518 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1519 progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1521 MIL << "Going to delete repo " << info.alias() << endl;
1523 for_( it, repoBegin(), repoEnd() )
1525 // they can be the same only if the provided is empty, that means
1526 // the provided repo has no alias
1528 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1531 // TODO match by url
1533 // we have a matcing repository, now we need to know
1534 // where it does come from.
1535 RepoInfo todelete = *it;
1536 if (todelete.filepath().empty())
1538 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1542 // figure how many repos are there in the file:
1543 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1544 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1546 // easy, only this one, just delete the file
1547 if ( filesystem::unlink(todelete.filepath()) != 0 )
1549 // TranslatorExplanation '%s' is a filename
1550 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1552 MIL << todelete.alias() << " sucessfully deleted." << endl;
1556 // there are more repos in the same file
1557 // write them back except the deleted one.
1559 //std::ofstream file(tmp.path().c_str());
1561 // assert the directory exists
1562 filesystem::assert_dir(todelete.filepath().dirname());
1564 std::ofstream file(todelete.filepath().c_str());
1567 // TranslatorExplanation '%s' is a filename
1568 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1570 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1571 fit != filerepos.end();
1574 if ( (*fit).alias() != todelete.alias() )
1575 (*fit).dumpAsIniOn(file);
1579 CombinedProgressData cSubprogrcv(progress, 20);
1580 CombinedProgressData mSubprogrcv(progress, 40);
1581 CombinedProgressData pSubprogrcv(progress, 40);
1582 // now delete it from cache
1583 if ( isCached(todelete) )
1584 cleanCache( todelete, cSubprogrcv);
1585 // now delete metadata (#301037)
1586 cleanMetadata( todelete, mSubprogrcv );
1587 cleanPackages( todelete, pSubprogrcv );
1588 _repos.erase(todelete);
1589 MIL << todelete.alias() << " sucessfully deleted." << endl;
1590 HistoryLog(_options.rootDir).removeRepository(todelete);
1592 } // else filepath is empty
1595 // should not be reached on a sucess workflow
1596 ZYPP_THROW(RepoNotFoundException(info));
1599 ////////////////////////////////////////////////////////////////////////////
1601 void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1603 RepoInfo toedit = getRepositoryInfo(alias);
1604 RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1606 // check if the new alias already exists when renaming the repo
1607 if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1609 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1612 if (toedit.filepath().empty())
1614 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1618 // figure how many repos are there in the file:
1619 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1621 // there are more repos in the same file
1622 // write them back except the deleted one.
1624 //std::ofstream file(tmp.path().c_str());
1626 // assert the directory exists
1627 filesystem::assert_dir(toedit.filepath().dirname());
1629 std::ofstream file(toedit.filepath().c_str());
1632 // TranslatorExplanation '%s' is a filename
1633 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1635 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1636 fit != filerepos.end();
1639 // if the alias is different, dump the original
1640 // if it is the same, dump the provided one
1641 if ( (*fit).alias() != toedit.alias() )
1642 (*fit).dumpAsIniOn(file);
1644 newinfo.dumpAsIniOn(file);
1647 newinfo.setFilepath(toedit.filepath());
1648 _repos.erase(toedit);
1649 _repos.insert(newinfo);
1650 HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1651 MIL << "repo " << alias << " modified" << endl;
1655 ////////////////////////////////////////////////////////////////////////////
1657 RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1659 RepoConstIterator it( findAlias( alias, _repos ) );
1660 if ( it != _repos.end() )
1663 info.setAlias( alias );
1664 ZYPP_THROW( RepoNotFoundException(info) );
1668 RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1670 for_( it, repoBegin(), repoEnd() )
1672 for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1674 if ( (*urlit).asString(urlview) == url.asString(urlview) )
1679 info.setBaseUrl( url );
1680 ZYPP_THROW( RepoNotFoundException(info) );
1683 ////////////////////////////////////////////////////////////////////////////
1687 ////////////////////////////////////////////////////////////////////////////
1689 void RepoManager::Impl::addService( const ServiceInfo & service )
1691 assert_alias( service );
1693 // check if service already exists
1694 if ( hasService( service.alias() ) )
1695 ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1697 // Writable ServiceInfo is needed to save the location
1698 // of the .service file. Finaly insert into the service list.
1699 ServiceInfo toSave( service );
1700 saveService( toSave );
1701 _services.insert( toSave );
1703 // check for credentials in Url (username:password, not ?credentials param)
1704 if ( toSave.url().hasCredentialsInAuthority() )
1706 media::CredentialManager cm(
1707 media::CredManagerOptions(_options.rootDir) );
1709 //! \todo use a method calling UI callbacks to ask where to save creds?
1710 cm.saveInUser(media::AuthData(toSave.url()));
1713 MIL << "added service " << toSave.alias() << endl;
1716 ////////////////////////////////////////////////////////////////////////////
1718 void RepoManager::Impl::removeService( const std::string & alias )
1720 MIL << "Going to delete repo " << alias << endl;
1722 const ServiceInfo & service = getService( alias );
1724 Pathname location = service.filepath();
1725 if( location.empty() )
1727 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
1731 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1733 // only one service definition in the file
1734 if ( tmpSet.size() == 1 )
1736 if ( filesystem::unlink(location) != 0 )
1738 // TranslatorExplanation '%s' is a filename
1739 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), location.c_str() )));
1741 MIL << alias << " sucessfully deleted." << endl;
1745 filesystem::assert_dir(location.dirname());
1747 std::ofstream file(location.c_str());
1750 // TranslatorExplanation '%s' is a filename
1751 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1754 for_(it, tmpSet.begin(), tmpSet.end())
1756 if( it->alias() != alias )
1757 it->dumpAsIniOn(file);
1760 MIL << alias << " sucessfully deleted from file " << location << endl;
1763 // now remove all repositories added by this service
1764 RepoCollector rcollector;
1765 getRepositoriesInService( alias,
1766 boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1767 // cannot do this directly in getRepositoriesInService - would invalidate iterators
1768 for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1769 removeRepository(*rit);
1772 ////////////////////////////////////////////////////////////////////////////
1774 void RepoManager::Impl::refreshServices()
1776 // copy the set of services since refreshService
1777 // can eventually invalidate the iterator
1778 ServiceSet services( serviceBegin(), serviceEnd() );
1779 for_( it, services.begin(), services.end() )
1781 if ( !it->enabled() )
1785 refreshService(*it);
1787 catch ( const repo::ServicePluginInformalException & e )
1788 { ;/* ignore ServicePluginInformalException */ }
1792 void RepoManager::Impl::refreshService( const std::string & alias )
1794 ServiceInfo service( getService( alias ) );
1795 assert_alias( service );
1796 assert_url( service );
1797 // NOTE: It might be necessary to modify and rewrite the service info.
1798 // Either when probing the type, or when adjusting the repositories
1799 // enable/disable state.:
1800 bool serviceModified = false;
1801 MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << endl;
1803 //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
1805 // if the type is unknown, try probing.
1806 if ( service.type() == repo::ServiceType::NONE )
1808 repo::ServiceType type = probeService( service.url() );
1809 if ( type != ServiceType::NONE )
1811 service.setProbedType( type ); // lazy init!
1812 serviceModified = true;
1816 // get target distro identifier
1817 std::string servicesTargetDistro = _options.servicesTargetDistro;
1818 if ( servicesTargetDistro.empty() )
1820 servicesTargetDistro = Target::targetDistribution( Pathname() );
1822 DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
1825 RepoCollector collector(servicesTargetDistro);
1826 // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
1827 // which is actually a notification. Using an exception for this
1828 // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
1830 std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
1832 ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
1834 catch ( const repo::ServicePluginInformalException & e )
1836 /* ignore ServicePluginInformalException and throw later */
1837 uglyHack.first = true;
1838 uglyHack.second = e;
1841 // set service alias and base url for all collected repositories
1842 for_( it, collector.repos.begin(), collector.repos.end() )
1844 // if the repo url was not set by the repoindex parser, set service's url
1847 if ( it->baseUrlsEmpty() )
1848 url = service.url();
1851 // service repo can contain only one URL now, so no need to iterate.
1852 url = *it->baseUrlsBegin();
1855 // libzypp currently has problem with separate url + path handling
1856 // so just append the path to the baseurl
1857 if ( !it->path().empty() )
1859 Pathname path(url.getPathName());
1861 url.setPathName( path.asString() );
1865 // Prepend service alias:
1866 it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
1869 it->setBaseUrl( url );
1870 // set refrence to the parent service
1871 it->setService( service.alias() );
1874 ////////////////////////////////////////////////////////////////////////////
1875 // Now compare collected repos with the ones in the system...
1877 RepoInfoList oldRepos;
1878 getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
1880 // find old repositories to remove...
1881 for_( it, oldRepos.begin(), oldRepos.end() )
1883 if ( ! foundAliasIn( it->alias(), collector.repos ) )
1885 if ( it->enabled() && ! service.repoToDisableFind( it->alias() ) )
1887 DBG << "Service removes enabled repo " << it->alias() << endl;
1888 service.addRepoToEnable( it->alias() );
1889 serviceModified = true;
1893 DBG << "Service removes disabled repo " << it->alias() << endl;
1895 removeRepository( *it );
1899 ////////////////////////////////////////////////////////////////////////////
1900 // create missing repositories and modify exising ones if needed...
1901 for_( it, collector.repos.begin(), collector.repos.end() )
1903 // Service explicitly requests the repo being enabled?
1904 // Service explicitly requests the repo being disabled?
1905 // And hopefully not both ;) If so, enable wins.
1906 bool beEnabled = service.repoToEnableFind( it->alias() );
1907 bool beDisabled = service.repoToDisableFind( it->alias() );
1909 // Make sure the service repo is created with the
1910 // appropriate enable
1911 if ( beEnabled ) it->setEnabled(true);
1912 if ( beDisabled ) it->setEnabled(false);
1916 // Remove from enable request list.
1917 // NOTE: repoToDisable is handled differently.
1918 // It gets cleared on each refresh.
1919 service.delRepoToEnable( it->alias() );
1920 serviceModified = true;
1923 RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
1924 if ( oldRepo == oldRepos.end() )
1926 // Not found in oldRepos ==> a new repo to add
1928 // At that point check whether a repo with the same alias
1929 // exists outside this service. Maybe forcefully re-alias
1930 // the existing repo?
1931 DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
1932 addRepository( *it );
1934 // save repo credentials
1935 // ma@: task for modifyRepository?
1939 // ==> an exising repo to check
1940 bool oldRepoModified = false;
1945 if ( ! oldRepo->enabled() )
1947 DBG << "Service repo " << it->alias() << " gets enabled" << endl;
1948 oldRepo->setEnabled( true );
1949 oldRepoModified = true;
1953 DBG << "Service repo " << it->alias() << " stays enabled" << endl;
1956 else if ( beDisabled )
1958 if ( oldRepo->enabled() )
1960 DBG << "Service repo " << it->alias() << " gets disabled" << endl;
1961 oldRepo->setEnabled( false );
1962 oldRepoModified = true;
1966 DBG << "Service repo " << it->alias() << " stays disabled" << endl;
1971 DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
1975 // service repo can contain only one URL now, so no need to iterate.
1976 if ( oldRepo->url() != it->url() )
1978 DBG << "Service repo " << it->alias() << " gets new URL " << it->url() << endl;
1979 oldRepo->setBaseUrl( it->url() );
1980 oldRepoModified = true;
1983 // save if modified:
1984 if ( oldRepoModified )
1986 modifyRepository( oldRepo->alias(), *oldRepo );
1991 // Unlike reposToEnable, reposToDisable is always cleared after refresh.
1992 if ( ! service.reposToDisableEmpty() )
1994 service.clearReposToDisable();
1995 serviceModified = true;
1998 ////////////////////////////////////////////////////////////////////////////
1999 // save service if modified:
2000 if ( serviceModified )
2002 // write out modified service file.
2003 modifyService( service.alias(), service );
2006 if ( uglyHack.first )
2008 throw( uglyHack.second ); // intentionally not ZYPP_THROW
2012 ////////////////////////////////////////////////////////////////////////////
2014 void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2016 MIL << "Going to modify service " << oldAlias << endl;
2018 // we need a writable copy to link it to the file where
2019 // it is saved if we modify it
2020 ServiceInfo service(newService);
2022 if ( service.type() == ServiceType::PLUGIN )
2024 MIL << "Not modifying plugin service '" << oldAlias << "'" << endl;
2028 const ServiceInfo & oldService = getService(oldAlias);
2030 Pathname location = oldService.filepath();
2031 if( location.empty() )
2033 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
2036 // remember: there may multiple services being defined in one file:
2038 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2040 filesystem::assert_dir(location.dirname());
2041 std::ofstream file(location.c_str());
2042 for_(it, tmpSet.begin(), tmpSet.end())
2044 if( *it != oldAlias )
2045 it->dumpAsIniOn(file);
2047 service.dumpAsIniOn(file);
2049 service.setFilepath(location);
2051 _services.erase(oldAlias);
2052 _services.insert(service);
2054 // changed properties affecting also repositories
2055 if( oldAlias != service.alias() // changed alias
2056 || oldService.enabled() != service.enabled() // changed enabled status
2059 std::vector<RepoInfo> toModify;
2060 getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2061 for_( it, toModify.begin(), toModify.end() )
2063 if (oldService.enabled() && !service.enabled())
2064 it->setEnabled(false);
2065 else if (!oldService.enabled() && service.enabled())
2067 //! \todo do nothing? the repos will be enabled on service refresh
2068 //! \todo how to know the service needs a (auto) refresh????
2071 it->setService(service.alias());
2072 modifyRepository(it->alias(), *it);
2076 //! \todo refresh the service automatically if url is changed?
2079 ////////////////////////////////////////////////////////////////////////////
2081 repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2085 MediaSetAccess access(url);
2086 if ( access.doesFileExist("/repo/repoindex.xml") )
2087 return repo::ServiceType::RIS;
2089 catch ( const media::MediaException &e )
2092 // TranslatorExplanation '%s' is an URL
2093 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2097 catch ( const Exception &e )
2100 // TranslatorExplanation '%s' is an URL
2101 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2106 return repo::ServiceType::NONE;
2109 ///////////////////////////////////////////////////////////////////
2111 // CLASS NAME : RepoManager
2113 ///////////////////////////////////////////////////////////////////
2115 RepoManager::RepoManager( const RepoManagerOptions & opt )
2116 : _pimpl( new Impl(opt) )
2119 RepoManager::~RepoManager()
2122 bool RepoManager::repoEmpty() const
2123 { return _pimpl->repoEmpty(); }
2125 RepoManager::RepoSizeType RepoManager::repoSize() const
2126 { return _pimpl->repoSize(); }
2128 RepoManager::RepoConstIterator RepoManager::repoBegin() const
2129 { return _pimpl->repoBegin(); }
2131 RepoManager::RepoConstIterator RepoManager::repoEnd() const
2132 { return _pimpl->repoEnd(); }
2134 RepoInfo RepoManager::getRepo( const std::string & alias ) const
2135 { return _pimpl->getRepo( alias ); }
2137 bool RepoManager::hasRepo( const std::string & alias ) const
2138 { return _pimpl->hasRepo( alias ); }
2140 std::string RepoManager::makeStupidAlias( const Url & url_r )
2142 std::string ret( url_r.getScheme() );
2148 std::string host( url_r.getHost() );
2149 if ( ! host.empty() )
2155 static Date::ValueType serial = Date::now();
2156 ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2160 RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2161 { return _pimpl->metadataStatus( info ); }
2163 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2164 { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2166 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2167 { return _pimpl->metadataPath( info ); }
2169 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2170 { return _pimpl->packagesPath( info ); }
2172 void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2173 { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2175 void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2176 { return _pimpl->cleanMetadata( info, progressrcv ); }
2178 void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2179 { return _pimpl->cleanPackages( info, progressrcv ); }
2181 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2182 { return _pimpl->cacheStatus( info ); }
2184 void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2185 { return _pimpl->buildCache( info, policy, progressrcv ); }
2187 void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2188 { return _pimpl->cleanCache( info, progressrcv ); }
2190 bool RepoManager::isCached( const RepoInfo &info ) const
2191 { return _pimpl->isCached( info ); }
2193 void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2194 { return _pimpl->loadFromCache( info, progressrcv ); }
2196 void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2197 { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2199 repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2200 { return _pimpl->probe( url, path ); }
2202 repo::RepoType RepoManager::probe( const Url & url ) const
2203 { return _pimpl->probe( url ); }
2205 void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2206 { return _pimpl->addRepository( info, progressrcv ); }
2208 void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2209 { return _pimpl->addRepositories( url, progressrcv ); }
2211 void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2212 { return _pimpl->removeRepository( info, progressrcv ); }
2214 void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2215 { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2217 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2218 { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2220 RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2221 { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2223 bool RepoManager::serviceEmpty() const
2224 { return _pimpl->serviceEmpty(); }
2226 RepoManager::ServiceSizeType RepoManager::serviceSize() const
2227 { return _pimpl->serviceSize(); }
2229 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2230 { return _pimpl->serviceBegin(); }
2232 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2233 { return _pimpl->serviceEnd(); }
2235 ServiceInfo RepoManager::getService( const std::string & alias ) const
2236 { return _pimpl->getService( alias ); }
2238 bool RepoManager::hasService( const std::string & alias ) const
2239 { return _pimpl->hasService( alias ); }
2241 repo::ServiceType RepoManager::probeService( const Url &url ) const
2242 { return _pimpl->probeService( url ); }
2244 void RepoManager::addService( const std::string & alias, const Url& url )
2245 { return _pimpl->addService( alias, url ); }
2247 void RepoManager::addService( const ServiceInfo & service )
2248 { return _pimpl->addService( service ); }
2250 void RepoManager::removeService( const std::string & alias )
2251 { return _pimpl->removeService( alias ); }
2253 void RepoManager::removeService( const ServiceInfo & service )
2254 { return _pimpl->removeService( service ); }
2256 void RepoManager::refreshServices()
2257 { return _pimpl->refreshServices(); }
2259 void RepoManager::refreshService( const std::string & alias )
2260 { return _pimpl->refreshService( alias ); }
2262 void RepoManager::refreshService( const ServiceInfo & service )
2263 { return _pimpl->refreshService( service ); }
2265 void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2266 { return _pimpl->modifyService( oldAlias, service ); }
2268 ////////////////////////////////////////////////////////////////////////////
2270 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2271 { return str << *obj._pimpl; }
2273 /////////////////////////////////////////////////////////////////
2275 ///////////////////////////////////////////////////////////////////