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/DefaultIntegral.h"
25 #include "zypp/base/Function.h"
26 #include "zypp/base/Regex.h"
27 #include "zypp/PathInfo.h"
28 #include "zypp/TmpPath.h"
30 #include "zypp/ServiceInfo.h"
31 #include "zypp/repo/RepoException.h"
32 #include "zypp/RepoManager.h"
34 #include "zypp/media/MediaManager.h"
35 #include "zypp/media/CredentialManager.h"
36 #include "zypp/MediaSetAccess.h"
37 #include "zypp/ExternalProgram.h"
38 #include "zypp/ManagedFile.h"
40 #include "zypp/parser/RepoFileReader.h"
41 #include "zypp/parser/ServiceFileReader.h"
42 #include "zypp/repo/ServiceRepos.h"
43 #include "zypp/repo/yum/Downloader.h"
44 #include "zypp/repo/susetags/Downloader.h"
45 #include "zypp/repo/PluginServices.h"
47 #include "zypp/Target.h" // for Target::targetDistribution() for repo index services
48 #include "zypp/ZYppFactory.h" // to get the Target from ZYpp instance
49 #include "zypp/HistoryLog.h" // to write history :O)
51 #include "zypp/ZYppCallbacks.h"
57 using namespace zypp::repo;
59 #define OPT_PROGRESS const ProgressData::ReceiverFnc & = ProgressData::ReceiverFnc()
61 ///////////////////////////////////////////////////////////////////
64 ///////////////////////////////////////////////////////////////////
67 ///////////////////////////////////////////////////////////////////
68 /// \class UrlCredentialExtractor
69 /// \brief Extract credentials in \ref Url authority and store them via \ref CredentialManager.
71 /// Lazy init CredentialManager and save collected credentials when
72 /// going out of scope.
74 /// Methods return whether a password has been collected/extracted.
77 /// UrlCredentialExtractor( "/rootdir" ).collect( oneUrlOrUrlContainer );
81 /// UrlCredentialExtractor extractCredentials;
82 /// extractCredentials.collect( oneUrlOrUrlContainer );
83 /// extractCredentials.extract( oneMoreUrlOrUrlContainer );
88 class UrlCredentialExtractor
91 UrlCredentialExtractor( Pathname & root_r )
95 ~UrlCredentialExtractor()
96 { if ( _cmPtr ) _cmPtr->save(); }
98 /** Remember credentials stored in URL authority leaving the password in \a url_r. */
99 bool collect( const Url & url_r )
101 bool ret = url_r.hasCredentialsInAuthority();
104 if ( !_cmPtr ) _cmPtr.reset( new media::CredentialManager( _root ) );
105 _cmPtr->addUserCred( url_r );
109 /** \overload operating on Url container */
110 template<class TContainer>
111 bool collect( const TContainer & urls_r )
112 { bool ret = false; for ( const Url & url : urls_r ) { if ( collect( url ) && !ret ) ret = true; } return ret; }
114 /** Remember credentials stored in URL authority stripping the passowrd from \a url_r. */
115 bool extract( Url & url_r )
117 bool ret = collect( url_r );
119 url_r.setPassword( std::string() );
122 /** \overload operating on Url container */
123 template<class TContainer>
124 bool extract( TContainer & urls_r )
125 { bool ret = false; for ( Url & url : urls_r ) { if ( extract( url ) && !ret ) ret = true; } return ret; }
128 const Pathname & _root;
129 scoped_ptr<media::CredentialManager> _cmPtr;
132 ///////////////////////////////////////////////////////////////////
134 ///////////////////////////////////////////////////////////////////
137 /** Simple media mounter to access non-downloading URLs e.g. for non-local plaindir repos.
143 /** Ctor provides media access. */
144 MediaMounter( const Url & url_r )
146 media::MediaManager mediamanager;
147 _mid = mediamanager.open( url_r );
148 mediamanager.attach( _mid );
151 /** Ctor releases the media. */
154 media::MediaManager mediamanager;
155 mediamanager.release( _mid );
156 mediamanager.close( _mid );
159 /** Convert a path relative to the media into an absolute path.
161 * Called without argument it returns the path to the medias root directory.
163 Pathname getPathName( const Pathname & path_r = Pathname() ) const
165 media::MediaManager mediamanager;
166 return mediamanager.localPath( _mid, path_r );
170 media::MediaAccessId _mid;
172 ///////////////////////////////////////////////////////////////////
174 /** Check if alias_r is present in repo/service container. */
175 template <class Iterator>
176 inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
178 for_( it, begin_r, end_r )
179 if ( it->alias() == alias_r )
184 template <class Container>
185 inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
186 { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
188 /** Find alias_r in repo/service container. */
189 template <class Iterator>
190 inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
192 for_( it, begin_r, end_r )
193 if ( it->alias() == alias_r )
198 template <class Container>
199 inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
200 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
202 template <class Container>
203 inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
204 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
207 /** \short Generate a related filename from a repo/service infos alias */
208 inline std::string filenameFromAlias( const std::string & alias_r, const std::string & stem_r )
210 std::string filename( alias_r );
211 // replace slashes with underscores
212 str::replaceAll( filename, "/", "_" );
214 filename = Pathname(filename).extend("."+stem_r).asString();
215 MIL << "generating filename for " << stem_r << " [" << alias_r << "] : '" << filename << "'" << endl;
220 * \short Simple callback to collect the results
222 * Classes like RepoFileReader call the callback
223 * once per each repo in a file.
225 * Passing this functor as callback, you can collect
226 * all results at the end, without dealing with async
229 * If targetDistro is set, all repos with non-empty RepoInfo::targetDistribution()
232 * \todo do this through a separate filter
234 struct RepoCollector : private base::NonCopyable
239 RepoCollector(const std::string & targetDistro_)
240 : targetDistro(targetDistro_)
243 bool collect( const RepoInfo &repo )
245 // skip repositories meant for other distros than specified
246 if (!targetDistro.empty()
247 && !repo.targetDistribution().empty()
248 && repo.targetDistribution() != targetDistro)
251 << "Skipping repository meant for '" << repo.targetDistribution()
252 << "' distribution (current distro is '"
253 << targetDistro << "')." << endl;
258 repos.push_back(repo);
263 std::string targetDistro;
265 ////////////////////////////////////////////////////////////////////////////
268 * Reads RepoInfo's from a repo file.
270 * \param file pathname of the file to read.
272 std::list<RepoInfo> repositories_in_file( const Pathname & file )
274 MIL << "repo file: " << file << endl;
275 RepoCollector collector;
276 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
277 return std::move(collector.repos);
280 ////////////////////////////////////////////////////////////////////////////
283 * \short List of RepoInfo's from a directory
285 * Goes trough every file ending with ".repo" in a directory and adds all
286 * RepoInfo's contained in that file.
288 * \param dir pathname of the directory to read.
290 std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
292 MIL << "directory " << dir << endl;
293 std::list<RepoInfo> repos;
294 bool nonroot( geteuid() != 0 );
295 if ( nonroot && ! PathInfo(dir).userMayRX() )
297 JobReport::warning( formatNAC(_("Cannot read repo directory '%1%': Permission denied")) % dir );
301 std::list<Pathname> entries;
302 if ( filesystem::readdir( entries, dir, false ) != 0 )
304 // TranslatorExplanation '%s' is a pathname
305 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
308 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
309 for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
311 if ( str::regex_match(it->extension(), allowedRepoExt) )
313 if ( nonroot && ! PathInfo(*it).userMayR() )
315 JobReport::warning( formatNAC(_("Cannot read repo file '%1%': Permission denied")) % *it );
319 const std::list<RepoInfo> & tmp( repositories_in_file( *it ) );
320 repos.insert( repos.end(), tmp.begin(), tmp.end() );
328 ////////////////////////////////////////////////////////////////////////////
330 inline void assert_alias( const RepoInfo & info )
332 if ( info.alias().empty() )
333 ZYPP_THROW( RepoNoAliasException( info ) );
334 // bnc #473834. Maybe we can match the alias against a regex to define
335 // and check for valid aliases
336 if ( info.alias()[0] == '.')
337 ZYPP_THROW(RepoInvalidAliasException(
338 info, _("Repository alias cannot start with dot.")));
341 inline void assert_alias( const ServiceInfo & info )
343 if ( info.alias().empty() )
344 ZYPP_THROW( ServiceNoAliasException( info ) );
345 // bnc #473834. Maybe we can match the alias against a regex to define
346 // and check for valid aliases
347 if ( info.alias()[0] == '.')
348 ZYPP_THROW(ServiceInvalidAliasException(
349 info, _("Service alias cannot start with dot.")));
352 ////////////////////////////////////////////////////////////////////////////
354 inline void assert_urls( const RepoInfo & info )
356 if ( info.baseUrlsEmpty() )
357 ZYPP_THROW( RepoNoUrlException( info ) );
360 inline void assert_url( const ServiceInfo & info )
362 if ( ! info.url().isValid() )
363 ZYPP_THROW( ServiceNoUrlException( info ) );
366 ////////////////////////////////////////////////////////////////////////////
369 * \short Calculates the raw cache path for a repository, this is usually
370 * /var/cache/zypp/alias
372 inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
375 return opt.repoRawCachePath / info.escaped_alias();
379 * \short Calculates the raw product metadata path for a repository, this is
380 * inside the raw cache dir, plus an optional path where the metadata is.
382 * It should be different only for repositories that are not in the root of
384 * for example /var/cache/zypp/alias/addondir
386 inline Pathname rawproductdata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
389 return opt.repoRawCachePath / info.escaped_alias() / info.path();
393 * \short Calculates the packages cache path for a repository
395 inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
398 return opt.repoPackagesCachePath / info.escaped_alias();
402 * \short Calculates the solv cache path for a repository
404 inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
407 return opt.repoSolvCachePath / info.escaped_alias();
410 ////////////////////////////////////////////////////////////////////////////
412 /** Functor collecting ServiceInfos into a ServiceSet. */
413 class ServiceCollector
416 typedef std::set<ServiceInfo> ServiceSet;
418 ServiceCollector( ServiceSet & services_r )
419 : _services( services_r )
422 bool operator()( const ServiceInfo & service_r ) const
424 _services.insert( service_r );
429 ServiceSet & _services;
431 ////////////////////////////////////////////////////////////////////////////
434 ///////////////////////////////////////////////////////////////////
436 std::list<RepoInfo> readRepoFile( const Url & repo_file )
438 // no interface to download a specific file, using workaround:
439 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
441 Pathname path(url.getPathName());
442 url.setPathName ("/");
443 MediaSetAccess access(url);
444 Pathname local = access.provideFile(path);
446 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
448 return repositories_in_file(local);
451 ///////////////////////////////////////////////////////////////////
453 // class RepoManagerOptions
455 ////////////////////////////////////////////////////////////////////
457 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
459 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
460 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
461 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
462 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
463 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
464 knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
465 pluginsPath = Pathname::assertprefix( root_r, ZConfig::instance().pluginsPath() );
466 probe = ZConfig::instance().repo_add_probe();
471 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
473 RepoManagerOptions ret;
474 ret.repoCachePath = root_r;
475 ret.repoRawCachePath = root_r/"raw";
476 ret.repoSolvCachePath = root_r/"solv";
477 ret.repoPackagesCachePath = root_r/"packages";
478 ret.knownReposPath = root_r/"repos.d";
479 ret.knownServicesPath = root_r/"services.d";
480 ret.pluginsPath = root_r/"plugins";
481 ret.rootDir = root_r;
485 std:: ostream & operator<<( std::ostream & str, const RepoManagerOptions & obj )
487 #define OUTS(X) str << " " #X "\t" << obj.X << endl
488 str << "RepoManagerOptions (" << obj.rootDir << ") {" << endl;
489 OUTS( repoRawCachePath );
490 OUTS( repoSolvCachePath );
491 OUTS( repoPackagesCachePath );
492 OUTS( knownReposPath );
493 OUTS( knownServicesPath );
500 ///////////////////////////////////////////////////////////////////
501 /// \class RepoManager::Impl
502 /// \brief RepoManager implementation.
504 ///////////////////////////////////////////////////////////////////
505 struct RepoManager::Impl
508 Impl( const RepoManagerOptions &opt )
511 init_knownServices();
512 init_knownRepositories();
517 // trigger appdata refresh if some repos change
518 if ( _reposDirty && geteuid() == 0 && ( _options.rootDir.empty() || _options.rootDir == "/" ) )
521 std::list<Pathname> entries;
522 filesystem::readdir( entries, _options.pluginsPath/"appdata", false );
523 if ( ! entries.empty() )
525 ExternalProgram::Arguments cmd;
526 cmd.push_back( "<" ); // discard stdin
527 cmd.push_back( ">" ); // discard stdout
528 cmd.push_back( "PROGRAM" ); // [2] - fix index below if changing!
529 for ( const auto & rinfo : repos() )
531 if ( ! rinfo.enabled() )
533 cmd.push_back( "-R" );
534 cmd.push_back( rinfo.alias() );
535 cmd.push_back( "-t" );
536 cmd.push_back( rinfo.type().asString() );
537 cmd.push_back( "-p" );
538 cmd.push_back( rinfo.metadataPath().asString() );
541 for_( it, entries.begin(), entries.end() )
544 //DBG << "/tmp/xx ->" << pi << endl;
545 if ( pi.isFile() && pi.userMayRX() )
548 cmd[2] = pi.asString(); // [2] - PROGRAM
549 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
554 catch (...) {} // no throw in dtor
559 bool repoEmpty() const { return repos().empty(); }
560 RepoSizeType repoSize() const { return repos().size(); }
561 RepoConstIterator repoBegin() const { return repos().begin(); }
562 RepoConstIterator repoEnd() const { return repos().end(); }
564 bool hasRepo( const std::string & alias ) const
565 { return foundAliasIn( alias, repos() ); }
567 RepoInfo getRepo( const std::string & alias ) const
569 RepoConstIterator it( findAlias( alias, repos() ) );
570 return it == repos().end() ? RepoInfo::noRepo : *it;
574 Pathname metadataPath( const RepoInfo & info ) const
575 { return rawcache_path_for_repoinfo( _options, info ); }
577 Pathname packagesPath( const RepoInfo & info ) const
578 { return packagescache_path_for_repoinfo( _options, info ); }
580 RepoStatus metadataStatus( const RepoInfo & info ) const;
582 RefreshCheckStatus checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy );
584 void refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, OPT_PROGRESS );
586 void cleanMetadata( const RepoInfo & info, OPT_PROGRESS );
588 void cleanPackages( const RepoInfo & info, OPT_PROGRESS );
590 void buildCache( const RepoInfo & info, CacheBuildPolicy policy, OPT_PROGRESS );
592 repo::RepoType probe( const Url & url, const Pathname & path = Pathname() ) const;
593 repo::RepoType probeCache( const Pathname & path_r ) const;
595 void cleanCacheDirGarbage( OPT_PROGRESS );
597 void cleanCache( const RepoInfo & info, OPT_PROGRESS );
599 bool isCached( const RepoInfo & info ) const
600 { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
602 RepoStatus cacheStatus( const RepoInfo & info ) const
603 { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
605 void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
607 void addRepository( const RepoInfo & info, OPT_PROGRESS );
609 void addRepositories( const Url & url, OPT_PROGRESS );
611 void removeRepository( const RepoInfo & info, OPT_PROGRESS );
613 void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
615 RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
616 RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
619 bool serviceEmpty() const { return _services.empty(); }
620 ServiceSizeType serviceSize() const { return _services.size(); }
621 ServiceConstIterator serviceBegin() const { return _services.begin(); }
622 ServiceConstIterator serviceEnd() const { return _services.end(); }
624 bool hasService( const std::string & alias ) const
625 { return foundAliasIn( alias, _services ); }
627 ServiceInfo getService( const std::string & alias ) const
629 ServiceConstIterator it( findAlias( alias, _services ) );
630 return it == _services.end() ? ServiceInfo::noService : *it;
634 void addService( const ServiceInfo & service );
635 void addService( const std::string & alias, const Url & url )
636 { addService( ServiceInfo( alias, url ) ); }
638 void removeService( const std::string & alias );
639 void removeService( const ServiceInfo & service )
640 { removeService( service.alias() ); }
642 void refreshServices( const RefreshServiceOptions & options_r );
644 void refreshService( const std::string & alias, const RefreshServiceOptions & options_r );
645 void refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
646 { refreshService( service.alias(), options_r ); }
648 void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
650 repo::ServiceType probeService( const Url & url ) const;
653 void saveService( ServiceInfo & service ) const;
655 Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
657 std::string generateFilename( const RepoInfo & info ) const
658 { return filenameFromAlias( info.alias(), "repo" ); }
660 std::string generateFilename( const ServiceInfo & info ) const
661 { return filenameFromAlias( info.alias(), "service" ); }
663 void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
665 Pathname base = solv_path_for_repoinfo( _options, info );
666 filesystem::assert_dir(base);
667 status.saveToCookieFile( base / "cookie" );
670 void touchIndexFile( const RepoInfo & info );
672 template<typename OutputIterator>
673 void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
675 MatchServiceAlias filter( alias );
676 std::copy( boost::make_filter_iterator( filter, repos().begin(), repos().end() ),
677 boost::make_filter_iterator( filter, repos().end(), repos().end() ),
682 void init_knownServices();
683 void init_knownRepositories();
685 const RepoSet & repos() const { return _reposX; }
686 RepoSet & reposManip() { if ( ! _reposDirty ) _reposDirty = true; return _reposX; }
689 RepoManagerOptions _options;
691 ServiceSet _services;
693 DefaultIntegral<bool,false> _reposDirty;
696 friend Impl * rwcowClone<Impl>( const Impl * rhs );
697 /** clone for RWCOW_pointer */
699 { return new Impl( *this ); }
701 ///////////////////////////////////////////////////////////////////
703 /** \relates RepoManager::Impl Stream output */
704 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
705 { return str << "RepoManager::Impl"; }
707 ///////////////////////////////////////////////////////////////////
709 void RepoManager::Impl::saveService( ServiceInfo & service ) const
711 filesystem::assert_dir( _options.knownServicesPath );
712 Pathname servfile = generateNonExistingName( _options.knownServicesPath,
713 generateFilename( service ) );
714 service.setFilepath( servfile );
716 MIL << "saving service in " << servfile << endl;
718 std::ofstream file( servfile.c_str() );
721 // TranslatorExplanation '%s' is a filename
722 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
724 service.dumpAsIniOn( file );
725 MIL << "done" << endl;
729 * Generate a non existing filename in a directory, using a base
730 * name. For example if a directory contains 3 files
736 * If you try to generate a unique filename for this directory,
737 * based on "ruu" you will get "ruu", but if you use the base
738 * "foo" you will get "foo_1"
740 * \param dir Directory where the file needs to be unique
741 * \param basefilename string to base the filename on.
743 Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
744 const std::string & basefilename ) const
746 std::string final_filename = basefilename;
748 while ( PathInfo(dir + final_filename).isExist() )
750 final_filename = basefilename + "_" + str::numstring(counter);
753 return dir + Pathname(final_filename);
756 ////////////////////////////////////////////////////////////////////////////
758 void RepoManager::Impl::init_knownServices()
760 Pathname dir = _options.knownServicesPath;
761 std::list<Pathname> entries;
762 if (PathInfo(dir).isExist())
764 if ( filesystem::readdir( entries, dir, false ) != 0 )
766 // TranslatorExplanation '%s' is a pathname
767 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
770 //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
771 for_(it, entries.begin(), entries.end() )
773 parser::ServiceFileReader(*it, ServiceCollector(_services));
777 repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
780 ///////////////////////////////////////////////////////////////////
782 /** Delete \a cachePath_r subdirs not matching known aliases in \a repoEscAliases_r (must be sorted!)
783 * \note bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
784 * we'd need some magic file to identify zypp cache directories. Without this
785 * we may easily remove user data (zypper --pkg-cache-dir . download ...)
787 inline void cleanupNonRepoMetadtaFolders( const Pathname & cachePath_r,
788 const Pathname & defaultCachePath_r,
789 const std::list<std::string> & repoEscAliases_r )
791 if ( cachePath_r != defaultCachePath_r )
794 std::list<std::string> entries;
795 if ( filesystem::readdir( entries, cachePath_r, false ) == 0 )
798 std::set<std::string> oldfiles;
799 set_difference( entries.begin(), entries.end(), repoEscAliases_r.begin(), repoEscAliases_r.end(),
800 std::inserter( oldfiles, oldfiles.end() ) );
801 for ( const std::string & old : oldfiles )
803 if ( old == Repository::systemRepoAlias() ) // don't remove the @System solv file
805 filesystem::recursive_rmdir( cachePath_r / old );
810 ///////////////////////////////////////////////////////////////////
811 void RepoManager::Impl::init_knownRepositories()
813 MIL << "start construct known repos" << endl;
815 if ( PathInfo(_options.knownReposPath).isExist() )
817 std::list<std::string> repoEscAliases;
818 std::list<RepoInfo> orphanedRepos;
819 for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
821 // set the metadata path for the repo
822 repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
823 // set the downloaded packages path for the repo
824 repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
826 _reposX.insert( repoInfo ); // direct access via _reposX in ctor! no reposManip.
828 // detect orphaned repos belonging to a deleted service
829 const std::string & serviceAlias( repoInfo.service() );
830 if ( ! ( serviceAlias.empty() || hasService( serviceAlias ) ) )
832 WAR << "Schedule orphaned service repo for deletion: " << repoInfo << endl;
833 orphanedRepos.push_back( repoInfo );
834 continue; // don't remember it in repoEscAliases
837 repoEscAliases.push_back(repoInfo.escaped_alias());
840 // Cleanup orphanded service repos:
841 if ( ! orphanedRepos.empty() )
843 for ( auto & repoInfo : orphanedRepos )
845 MIL << "Delete orphaned service repo " << repoInfo.alias() << endl;
846 // translators: Cleanup a repository previously owned by a meanwhile unknown (deleted) service.
847 // %1% = service name
848 // %2% = repository name
849 JobReport::warning( formatNAC(_("Unknown service '%1%': Removing orphaned service repository '%2%'" ))
851 % repoInfo.alias() );
853 removeRepository( repoInfo );
855 catch ( const Exception & caugth )
857 JobReport::error( caugth.asUserHistory() );
862 // delete metadata folders without corresponding repo (e.g. old tmp directories)
864 // bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
865 // we'd need somemagic file to identify zypp cache directories. Without this
866 // we may easily remove user data (zypper --pkg-cache-dir . download ...)
867 repoEscAliases.sort();
868 RepoManagerOptions defaultCache( _options.rootDir );
869 cleanupNonRepoMetadtaFolders( _options.repoRawCachePath, defaultCache.repoRawCachePath, repoEscAliases );
870 cleanupNonRepoMetadtaFolders( _options.repoSolvCachePath, defaultCache.repoSolvCachePath, repoEscAliases );
871 cleanupNonRepoMetadtaFolders( _options.repoPackagesCachePath, defaultCache.repoPackagesCachePath, repoEscAliases );
873 MIL << "end construct known repos" << endl;
876 ///////////////////////////////////////////////////////////////////
878 RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
880 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
881 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
883 RepoType repokind = info.type();
884 // If unknown, probe the local metadata
885 if ( repokind == RepoType::NONE )
886 repokind = probeCache( productdatapath );
889 switch ( repokind.toEnum() )
891 case RepoType::RPMMD_e :
892 status = RepoStatus( productdatapath/"repodata/repomd.xml");
895 case RepoType::YAST2_e :
896 status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
899 case RepoType::RPMPLAINDIR_e :
900 status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
903 case RepoType::NONE_e :
904 // Return default RepoStatus in case of RepoType::NONE
905 // indicating it should be created?
906 // ZYPP_THROW(RepoUnknownTypeException());
913 void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
915 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
917 RepoType repokind = info.type();
918 if ( repokind.toEnum() == RepoType::NONE_e )
919 // unknown, probe the local metadata
920 repokind = probeCache( productdatapath );
921 // if still unknown, just return
922 if (repokind == RepoType::NONE_e)
926 switch ( repokind.toEnum() )
928 case RepoType::RPMMD_e :
929 p = Pathname(productdatapath + "/repodata/repomd.xml");
932 case RepoType::YAST2_e :
933 p = Pathname(productdatapath + "/content");
936 case RepoType::RPMPLAINDIR_e :
937 p = Pathname(productdatapath + "/cookie");
940 case RepoType::NONE_e :
945 // touch the file, ignore error (they are logged anyway)
946 filesystem::touch(p);
950 RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
955 MIL << "Going to try to check whether refresh is needed for " << url << endl;
957 // first check old (cached) metadata
958 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
959 filesystem::assert_dir( mediarootpath );
960 RepoStatus oldstatus = metadataStatus( info );
962 if ( oldstatus.empty() )
964 MIL << "No cached metadata, going to refresh" << endl;
965 return REFRESH_NEEDED;
969 if ( url.schemeIsVolatile() )
971 MIL << "never refresh CD/DVD" << endl;
972 return REPO_UP_TO_DATE;
974 if ( url.schemeIsLocal() )
976 policy = RefreshIfNeededIgnoreDelay;
980 // now we've got the old (cached) status, we can decide repo.refresh.delay
981 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
983 // difference in seconds
984 double diff = difftime(
985 (Date::ValueType)Date::now(),
986 (Date::ValueType)oldstatus.timestamp()) / 60;
988 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
989 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
990 DBG << "last refresh = " << diff << " minutes ago" << endl;
992 if ( diff < ZConfig::instance().repo_refresh_delay() )
996 WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
1000 MIL << "Repository '" << info.alias()
1001 << "' has been refreshed less than repo.refresh.delay ("
1002 << ZConfig::instance().repo_refresh_delay()
1003 << ") minutes ago. Advising to skip refresh" << endl;
1004 return REPO_CHECK_DELAYED;
1009 repo::RepoType repokind = info.type();
1010 // if unknown: probe it
1011 if ( repokind == RepoType::NONE )
1012 repokind = probe( url, info.path() );
1014 // retrieve newstatus
1015 RepoStatus newstatus;
1016 switch ( repokind.toEnum() )
1018 case RepoType::RPMMD_e:
1020 MediaSetAccess media( url );
1021 newstatus = yum::Downloader( info, mediarootpath ).status( media );
1025 case RepoType::YAST2_e:
1027 MediaSetAccess media( url );
1028 newstatus = susetags::Downloader( info, mediarootpath ).status( media );
1032 case RepoType::RPMPLAINDIR_e:
1033 newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
1037 case RepoType::NONE_e:
1038 ZYPP_THROW( RepoUnknownTypeException( info ) );
1043 bool refresh = false;
1044 if ( oldstatus == newstatus )
1046 MIL << "repo has not changed" << endl;
1047 if ( policy == RefreshForced )
1049 MIL << "refresh set to forced" << endl;
1055 MIL << "repo has changed, going to refresh" << endl;
1060 touchIndexFile(info);
1062 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
1065 catch ( const Exception &e )
1068 ERR << "refresh check failed for " << url << endl;
1072 return REFRESH_NEEDED; // default
1076 void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
1081 // we will throw this later if no URL checks out fine
1082 RepoException rexception( info, _PL("Valid metadata not found at specified URL",
1083 "Valid metadata not found at specified URLs",
1084 info.baseUrlsSize() ) );
1086 // Suppress (interactive) media::MediaChangeReport if we in have multiple basurls (>1)
1087 media::ScopedDisableMediaChangeReport guard( info.baseUrlsSize() > 1 );
1089 // try urls one by one
1090 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
1096 // check whether to refresh metadata
1097 // if the check fails for this url, it throws, so another url will be checked
1098 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
1101 MIL << "Going to refresh metadata from " << url << endl;
1103 repo::RepoType repokind = info.type();
1105 // if the type is unknown, try probing.
1106 if ( repokind == RepoType::NONE )
1108 // unknown, probe it
1109 repokind = probe( *it, info.path() );
1111 if (repokind.toEnum() != RepoType::NONE_e)
1113 // Adjust the probed type in RepoInfo
1114 info.setProbedType( repokind ); // lazy init!
1115 //save probed type only for repos in system
1116 for_( it, repoBegin(), repoEnd() )
1118 if ( info.alias() == (*it).alias() )
1120 RepoInfo modifiedrepo = info;
1121 modifiedrepo.setType( repokind );
1122 modifyRepository( info.alias(), modifiedrepo );
1129 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1130 if( filesystem::assert_dir(mediarootpath) )
1132 Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
1136 // create temp dir as sibling of mediarootpath
1137 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
1138 if( tmpdir.path().empty() )
1140 Exception ex(_("Can't create metadata cache directory."));
1144 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
1145 ( repokind.toEnum() == RepoType::YAST2_e ) )
1147 MediaSetAccess media(url);
1148 shared_ptr<repo::Downloader> downloader_ptr;
1150 MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
1152 if ( repokind.toEnum() == RepoType::RPMMD_e )
1153 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
1155 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
1158 * Given a downloader, sets the other repos raw metadata
1159 * path as cache paths for the fetcher, so if another
1160 * repo has the same file, it will not download it
1161 * but copy it from the other repository
1163 for_( it, repoBegin(), repoEnd() )
1165 Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1166 if ( PathInfo(cachepath).isExist() )
1167 downloader_ptr->addCachePath(cachepath);
1170 downloader_ptr->download( media, tmpdir.path() );
1172 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1174 MediaMounter media( url );
1175 RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) ); // dir status
1177 Pathname productpath( tmpdir.path() / info.path() );
1178 filesystem::assert_dir( productpath );
1179 newstatus.saveToCookieFile( productpath/"cookie" );
1183 ZYPP_THROW(RepoUnknownTypeException( info ));
1186 // ok we have the metadata, now exchange
1188 filesystem::exchange( tmpdir.path(), mediarootpath );
1189 reposManip(); // remember to trigger appdata refresh
1194 catch ( const Exception &e )
1197 ERR << "Trying another url..." << endl;
1199 // remember the exception caught for the *first URL*
1200 // if all other URLs fail, the rexception will be thrown with the
1201 // cause of the problem of the first URL remembered
1202 if (it == info.baseUrlsBegin())
1203 rexception.remember(e);
1206 ERR << "No more urls..." << endl;
1207 ZYPP_THROW(rexception);
1210 ////////////////////////////////////////////////////////////////////////////
1212 void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1214 ProgressData progress(100);
1215 progress.sendTo(progressfnc);
1217 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1222 void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1224 ProgressData progress(100);
1225 progress.sendTo(progressfnc);
1227 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1232 void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1235 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1236 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1238 if( filesystem::assert_dir(_options.repoCachePath) )
1240 Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1243 RepoStatus raw_metadata_status = metadataStatus(info);
1244 if ( raw_metadata_status.empty() )
1246 /* if there is no cache at this point, we refresh the raw
1247 in case this is the first time - if it's !autorefresh,
1248 we may still refresh */
1249 refreshMetadata(info, RefreshIfNeeded, progressrcv );
1250 raw_metadata_status = metadataStatus(info);
1253 bool needs_cleaning = false;
1254 if ( isCached( info ) )
1256 MIL << info.alias() << " is already cached." << endl;
1257 RepoStatus cache_status = cacheStatus(info);
1259 if ( cache_status == raw_metadata_status )
1261 MIL << info.alias() << " cache is up to date with metadata." << endl;
1262 if ( policy == BuildIfNeeded ) {
1266 MIL << info.alias() << " cache rebuild is forced" << endl;
1270 needs_cleaning = true;
1273 ProgressData progress(100);
1274 callback::SendReport<ProgressReport> report;
1275 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1276 progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1284 MIL << info.alias() << " building cache..." << info.type() << endl;
1286 Pathname base = solv_path_for_repoinfo( _options, info);
1288 if( filesystem::assert_dir(base) )
1290 Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1294 if( ! PathInfo(base).userMayW() )
1296 Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1299 Pathname solvfile = base / "solv";
1302 repo::RepoType repokind = info.type();
1304 // if the type is unknown, try probing.
1305 switch ( repokind.toEnum() )
1307 case RepoType::NONE_e:
1308 // unknown, probe the local metadata
1309 repokind = probeCache( productdatapath );
1315 MIL << "repo type is " << repokind << endl;
1317 switch ( repokind.toEnum() )
1319 case RepoType::RPMMD_e :
1320 case RepoType::YAST2_e :
1321 case RepoType::RPMPLAINDIR_e :
1323 // Take care we unlink the solvfile on exception
1324 ManagedFile guard( solvfile, filesystem::unlink );
1325 scoped_ptr<MediaMounter> forPlainDirs;
1327 ExternalProgram::Arguments cmd;
1328 cmd.push_back( "repo2solv.sh" );
1329 // repo2solv expects -o as 1st arg!
1330 cmd.push_back( "-o" );
1331 cmd.push_back( solvfile.asString() );
1332 cmd.push_back( "-X" ); // autogenerate pattern from pattern-package
1334 if ( repokind == RepoType::RPMPLAINDIR )
1336 forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1337 // recusive for plaindir as 2nd arg!
1338 cmd.push_back( "-R" );
1339 // FIXME this does only work form dir: URLs
1340 cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1343 cmd.push_back( productdatapath.asString() );
1345 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1346 std::string errdetail;
1348 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1349 WAR << " " << output;
1350 if ( errdetail.empty() ) {
1351 errdetail = prog.command();
1354 errdetail += output;
1357 int ret = prog.close();
1360 RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1361 ex.remember( errdetail );
1366 guard.resetDispose();
1370 ZYPP_THROW(RepoUnknownTypeException( info, _("Unhandled repository type") ));
1373 // update timestamp and checksum
1374 setCacheStatus(info, raw_metadata_status);
1375 MIL << "Commit cache.." << endl;
1379 ////////////////////////////////////////////////////////////////////////////
1382 /** Probe the metadata type of a repository located at \c url.
1383 * Urls here may be rewritten by \ref MediaSetAccess to reflect the correct media number.
1385 * \note Metadata in local cache directories must be probed using \ref probeCache as
1386 * a cache path must not be rewritten (bnc#946129)
1388 repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1390 MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1392 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1394 // Handle non existing local directory in advance, as
1395 // MediaSetAccess does not support it.
1396 MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1397 return repo::RepoType::NONE;
1400 // prepare exception to be thrown if the type could not be determined
1401 // due to a media exception. We can't throw right away, because of some
1402 // problems with proxy servers returning an incorrect error
1403 // on ftp file-not-found(bnc #335906). Instead we'll check another types
1406 // TranslatorExplanation '%s' is an URL
1407 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1408 bool gotMediaException = false;
1411 MediaSetAccess access(url);
1414 if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1416 MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1417 return repo::RepoType::RPMMD;
1420 catch ( const media::MediaException &e )
1423 DBG << "problem checking for repodata/repomd.xml file" << endl;
1425 gotMediaException = true;
1430 if ( access.doesFileExist(path/"/content") )
1432 MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1433 return repo::RepoType::YAST2;
1436 catch ( const media::MediaException &e )
1439 DBG << "problem checking for content file" << endl;
1441 gotMediaException = true;
1444 // if it is a non-downloading URL denoting a directory
1445 if ( ! url.schemeIsDownloading() )
1447 MediaMounter media( url );
1448 if ( PathInfo(media.getPathName()/path).isDir() )
1450 // allow empty dirs for now
1451 MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1452 return repo::RepoType::RPMPLAINDIR;
1456 catch ( const Exception &e )
1459 // TranslatorExplanation '%s' is an URL
1460 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1465 if (gotMediaException)
1468 MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1469 return repo::RepoType::NONE;
1472 /** Probe Metadata in a local cache directory
1474 * \note Metadata in local cache directories must not be probed using \ref probe as
1475 * a cache path must not be rewritten (bnc#946129)
1477 repo::RepoType RepoManager::Impl::probeCache( const Pathname & path_r ) const
1479 MIL << "going to probe the cached repo at " << path_r << endl;
1481 repo::RepoType ret = repo::RepoType::NONE;
1483 if ( PathInfo(path_r/"/repodata/repomd.xml").isFile() )
1484 { ret = repo::RepoType::RPMMD; }
1485 else if ( PathInfo(path_r/"/content").isFile() )
1486 { ret = repo::RepoType::YAST2; }
1487 else if ( PathInfo(path_r).isDir() )
1488 { ret = repo::RepoType::RPMPLAINDIR; }
1490 MIL << "Probed cached type " << ret << " at " << path_r << endl;
1494 ////////////////////////////////////////////////////////////////////////////
1496 void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1498 MIL << "Going to clean up garbage in cache dirs" << endl;
1500 ProgressData progress(300);
1501 progress.sendTo(progressrcv);
1504 std::list<Pathname> cachedirs;
1505 cachedirs.push_back(_options.repoRawCachePath);
1506 cachedirs.push_back(_options.repoPackagesCachePath);
1507 cachedirs.push_back(_options.repoSolvCachePath);
1509 for_( dir, cachedirs.begin(), cachedirs.end() )
1511 if ( PathInfo(*dir).isExist() )
1513 std::list<Pathname> entries;
1514 if ( filesystem::readdir( entries, *dir, false ) != 0 )
1515 // TranslatorExplanation '%s' is a pathname
1516 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1518 unsigned sdircount = entries.size();
1519 unsigned sdircurrent = 1;
1520 for_( subdir, entries.begin(), entries.end() )
1522 // if it does not belong known repo, make it disappear
1524 for_( r, repoBegin(), repoEnd() )
1525 if ( subdir->basename() == r->escaped_alias() )
1526 { found = true; break; }
1528 if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1529 filesystem::recursive_rmdir( *subdir );
1531 progress.set( progress.val() + sdircurrent * 100 / sdircount );
1536 progress.set( progress.val() + 100 );
1541 ////////////////////////////////////////////////////////////////////////////
1543 void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1545 ProgressData progress(100);
1546 progress.sendTo(progressrcv);
1549 MIL << "Removing raw metadata cache for " << info.alias() << endl;
1550 filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1555 ////////////////////////////////////////////////////////////////////////////
1557 void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1560 Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1562 if ( ! PathInfo(solvfile).isExist() )
1563 ZYPP_THROW(RepoNotCachedException(info));
1565 sat::Pool::instance().reposErase( info.alias() );
1568 Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1569 // test toolversion in order to rebuild solv file in case
1570 // it was written by an old libsolv-tool parser.
1572 // Known version strings used:
1576 sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1577 if ( toolversion.begin().asString().empty() )
1579 repo.eraseFromPool();
1580 ZYPP_THROW(Exception("Solv-file was created by old parser."));
1582 // else: up-to-date (or even newer).
1584 catch ( const Exception & exp )
1587 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1588 cleanCache( info, progressrcv );
1589 buildCache( info, BuildIfNeeded, progressrcv );
1591 sat::Pool::instance().addRepoSolv( solvfile, info );
1595 ////////////////////////////////////////////////////////////////////////////
1597 void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1601 ProgressData progress(100);
1602 callback::SendReport<ProgressReport> report;
1603 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1604 progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1607 MIL << "Try adding repo " << info << endl;
1609 RepoInfo tosave = info;
1610 if ( repos().find(tosave) != repos().end() )
1611 ZYPP_THROW(RepoAlreadyExistsException(info));
1613 // check the first url for now
1614 if ( _options.probe )
1616 DBG << "unknown repository type, probing" << endl;
1618 RepoType probedtype;
1619 probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1620 if ( tosave.baseUrlsSize() > 0 )
1622 if ( probedtype == RepoType::NONE )
1623 ZYPP_THROW(RepoUnknownTypeException(info));
1625 tosave.setType(probedtype);
1631 // assert the directory exists
1632 filesystem::assert_dir(_options.knownReposPath);
1634 Pathname repofile = generateNonExistingName(
1635 _options.knownReposPath, generateFilename(tosave));
1636 // now we have a filename that does not exists
1637 MIL << "Saving repo in " << repofile << endl;
1639 std::ofstream file(repofile.c_str());
1642 // TranslatorExplanation '%s' is a filename
1643 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1646 tosave.dumpAsIniOn(file);
1647 tosave.setFilepath(repofile);
1648 tosave.setMetadataPath( metadataPath( tosave ) );
1649 tosave.setPackagesPath( packagesPath( tosave ) );
1651 // We chould fix the API as we must injet those paths
1652 // into the repoinfo in order to keep it usable.
1653 RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1654 oinfo.setMetadataPath( metadataPath( tosave ) );
1655 oinfo.setPackagesPath( packagesPath( tosave ) );
1657 reposManip().insert(tosave);
1661 // check for credentials in Urls
1662 UrlCredentialExtractor( _options.rootDir ).collect( tosave.baseUrls() );
1664 HistoryLog(_options.rootDir).addRepository(tosave);
1667 MIL << "done" << endl;
1671 void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1673 std::list<RepoInfo> repos = readRepoFile(url);
1674 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1678 // look if the alias is in the known repos.
1679 for_ ( kit, repoBegin(), repoEnd() )
1681 if ( (*it).alias() == (*kit).alias() )
1683 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1684 ZYPP_THROW(RepoAlreadyExistsException(*it));
1689 std::string filename = Pathname(url.getPathName()).basename();
1691 if ( filename == Pathname() )
1693 // TranslatorExplanation '%s' is an URL
1694 ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1697 // assert the directory exists
1698 filesystem::assert_dir(_options.knownReposPath);
1700 Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1701 // now we have a filename that does not exists
1702 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1704 std::ofstream file(repofile.c_str());
1707 // TranslatorExplanation '%s' is a filename
1708 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1711 for ( std::list<RepoInfo>::iterator it = repos.begin();
1715 MIL << "Saving " << (*it).alias() << endl;
1716 it->setFilepath(repofile.asString());
1717 it->dumpAsIniOn(file);
1718 reposManip().insert(*it);
1720 HistoryLog(_options.rootDir).addRepository(*it);
1723 MIL << "done" << endl;
1726 ////////////////////////////////////////////////////////////////////////////
1728 void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1730 ProgressData progress;
1731 callback::SendReport<ProgressReport> report;
1732 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1733 progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1735 MIL << "Going to delete repo " << info.alias() << endl;
1737 for_( it, repoBegin(), repoEnd() )
1739 // they can be the same only if the provided is empty, that means
1740 // the provided repo has no alias
1742 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1745 // TODO match by url
1747 // we have a matcing repository, now we need to know
1748 // where it does come from.
1749 RepoInfo todelete = *it;
1750 if (todelete.filepath().empty())
1752 ZYPP_THROW(RepoException( todelete, _("Can't figure out where the repo is stored.") ));
1756 // figure how many repos are there in the file:
1757 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1758 if ( filerepos.size() == 0 // bsc#984494: file may have already been deleted
1759 ||(filerepos.size() == 1 && filerepos.front().alias() == todelete.alias() ) )
1761 // easy: file does not exist, contains no or only the repo to delete: delete the file
1762 int ret = filesystem::unlink( todelete.filepath() );
1763 if ( ! ( ret == 0 || ret == ENOENT ) )
1765 // TranslatorExplanation '%s' is a filename
1766 ZYPP_THROW(RepoException( todelete, str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1768 MIL << todelete.alias() << " successfully deleted." << endl;
1772 // there are more repos in the same file
1773 // write them back except the deleted one.
1775 //std::ofstream file(tmp.path().c_str());
1777 // assert the directory exists
1778 filesystem::assert_dir(todelete.filepath().dirname());
1780 std::ofstream file(todelete.filepath().c_str());
1783 // TranslatorExplanation '%s' is a filename
1784 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1786 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1787 fit != filerepos.end();
1790 if ( (*fit).alias() != todelete.alias() )
1791 (*fit).dumpAsIniOn(file);
1795 CombinedProgressData cSubprogrcv(progress, 20);
1796 CombinedProgressData mSubprogrcv(progress, 40);
1797 CombinedProgressData pSubprogrcv(progress, 40);
1798 // now delete it from cache
1799 if ( isCached(todelete) )
1800 cleanCache( todelete, cSubprogrcv);
1801 // now delete metadata (#301037)
1802 cleanMetadata( todelete, mSubprogrcv );
1803 cleanPackages( todelete, pSubprogrcv );
1804 reposManip().erase(todelete);
1805 MIL << todelete.alias() << " successfully deleted." << endl;
1806 HistoryLog(_options.rootDir).removeRepository(todelete);
1808 } // else filepath is empty
1811 // should not be reached on a sucess workflow
1812 ZYPP_THROW(RepoNotFoundException(info));
1815 ////////////////////////////////////////////////////////////////////////////
1817 void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1819 RepoInfo toedit = getRepositoryInfo(alias);
1820 RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1822 // check if the new alias already exists when renaming the repo
1823 if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1825 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1828 if (toedit.filepath().empty())
1830 ZYPP_THROW(RepoException( toedit, _("Can't figure out where the repo is stored.") ));
1834 // figure how many repos are there in the file:
1835 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1837 // there are more repos in the same file
1838 // write them back except the deleted one.
1840 //std::ofstream file(tmp.path().c_str());
1842 // assert the directory exists
1843 filesystem::assert_dir(toedit.filepath().dirname());
1845 std::ofstream file(toedit.filepath().c_str());
1848 // TranslatorExplanation '%s' is a filename
1849 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1851 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1852 fit != filerepos.end();
1855 // if the alias is different, dump the original
1856 // if it is the same, dump the provided one
1857 if ( (*fit).alias() != toedit.alias() )
1858 (*fit).dumpAsIniOn(file);
1860 newinfo.dumpAsIniOn(file);
1863 newinfo.setFilepath(toedit.filepath());
1864 reposManip().erase(toedit);
1865 reposManip().insert(newinfo);
1866 // check for credentials in Urls
1867 UrlCredentialExtractor( _options.rootDir ).collect( newinfo.baseUrls() );
1868 HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1869 MIL << "repo " << alias << " modified" << endl;
1873 ////////////////////////////////////////////////////////////////////////////
1875 RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1877 RepoConstIterator it( findAlias( alias, repos() ) );
1878 if ( it != repos().end() )
1881 info.setAlias( alias );
1882 ZYPP_THROW( RepoNotFoundException(info) );
1886 RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1888 for_( it, repoBegin(), repoEnd() )
1890 for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1892 if ( (*urlit).asString(urlview) == url.asString(urlview) )
1897 info.setBaseUrl( url );
1898 ZYPP_THROW( RepoNotFoundException(info) );
1901 ////////////////////////////////////////////////////////////////////////////
1905 ////////////////////////////////////////////////////////////////////////////
1907 void RepoManager::Impl::addService( const ServiceInfo & service )
1909 assert_alias( service );
1911 // check if service already exists
1912 if ( hasService( service.alias() ) )
1913 ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1915 // Writable ServiceInfo is needed to save the location
1916 // of the .service file. Finaly insert into the service list.
1917 ServiceInfo toSave( service );
1918 saveService( toSave );
1919 _services.insert( toSave );
1921 // check for credentials in Url
1922 UrlCredentialExtractor( _options.rootDir ).collect( toSave.url() );
1924 MIL << "added service " << toSave.alias() << endl;
1927 ////////////////////////////////////////////////////////////////////////////
1929 void RepoManager::Impl::removeService( const std::string & alias )
1931 MIL << "Going to delete service " << alias << endl;
1933 const ServiceInfo & service = getService( alias );
1935 Pathname location = service.filepath();
1936 if( location.empty() )
1938 ZYPP_THROW(ServiceException( service, _("Can't figure out where the service is stored.") ));
1942 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1944 // only one service definition in the file
1945 if ( tmpSet.size() == 1 )
1947 if ( filesystem::unlink(location) != 0 )
1949 // TranslatorExplanation '%s' is a filename
1950 ZYPP_THROW(ServiceException( service, str::form( _("Can't delete '%s'"), location.c_str() ) ));
1952 MIL << alias << " successfully deleted." << endl;
1956 filesystem::assert_dir(location.dirname());
1958 std::ofstream file(location.c_str());
1961 // TranslatorExplanation '%s' is a filename
1962 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1965 for_(it, tmpSet.begin(), tmpSet.end())
1967 if( it->alias() != alias )
1968 it->dumpAsIniOn(file);
1971 MIL << alias << " successfully deleted from file " << location << endl;
1974 // now remove all repositories added by this service
1975 RepoCollector rcollector;
1976 getRepositoriesInService( alias,
1977 boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1978 // cannot do this directly in getRepositoriesInService - would invalidate iterators
1979 for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1980 removeRepository(*rit);
1983 ////////////////////////////////////////////////////////////////////////////
1985 void RepoManager::Impl::refreshServices( const RefreshServiceOptions & options_r )
1987 // copy the set of services since refreshService
1988 // can eventually invalidate the iterator
1989 ServiceSet services( serviceBegin(), serviceEnd() );
1990 for_( it, services.begin(), services.end() )
1992 if ( !it->enabled() )
1996 refreshService(*it, options_r);
1998 catch ( const repo::ServicePluginInformalException & e )
1999 { ;/* ignore ServicePluginInformalException */ }
2003 void RepoManager::Impl::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2005 ServiceInfo service( getService( alias ) );
2006 assert_alias( service );
2007 assert_url( service );
2008 // NOTE: It might be necessary to modify and rewrite the service info.
2009 // Either when probing the type, or when adjusting the repositories
2010 // enable/disable state.:
2011 bool serviceModified = false;
2012 MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << ", opts: " << options_r << endl;
2014 //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
2016 // if the type is unknown, try probing.
2017 if ( service.type() == repo::ServiceType::NONE )
2019 repo::ServiceType type = probeService( service.url() );
2020 if ( type != ServiceType::NONE )
2022 service.setProbedType( type ); // lazy init!
2023 serviceModified = true;
2027 // get target distro identifier
2028 std::string servicesTargetDistro = _options.servicesTargetDistro;
2029 if ( servicesTargetDistro.empty() )
2031 servicesTargetDistro = Target::targetDistribution( Pathname() );
2033 DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
2036 RepoCollector collector(servicesTargetDistro);
2037 // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
2038 // which is actually a notification. Using an exception for this
2039 // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
2041 std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
2043 ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
2045 catch ( const repo::ServicePluginInformalException & e )
2047 /* ignore ServicePluginInformalException and throw later */
2048 uglyHack.first = true;
2049 uglyHack.second = e;
2052 ////////////////////////////////////////////////////////////////////////////
2053 // On the fly remember the new repo states as defined the reopoindex.xml.
2054 // Move into ServiceInfo later.
2055 ServiceInfo::RepoStates newRepoStates;
2057 // set service alias and base url for all collected repositories
2058 for_( it, collector.repos.begin(), collector.repos.end() )
2060 // First of all: Prepend service alias:
2061 it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
2062 // set reference to the parent service
2063 it->setService( service.alias() );
2065 // remember the new parsed repo state
2066 newRepoStates[it->alias()] = *it;
2068 // - If the repo url was not set by the repoindex parser, set service's url.
2069 // - Libzypp currently has problem with separate url + path handling so just
2070 // append a path, if set, to the baseurls
2071 // - Credentials in the url authority will be extracted later, either if the
2072 // repository is added or if we check for changed urls.
2074 if ( !it->path().empty() )
2076 if ( it->path() != "/" )
2081 if ( it->baseUrlsEmpty() )
2083 Url url( service.rawUrl() );
2084 if ( !path.empty() )
2085 url.setPathName( url.getPathName() / path );
2086 it->setBaseUrl( std::move(url) );
2088 else if ( !path.empty() )
2090 RepoInfo::url_set urls( it->rawBaseUrls() );
2091 for ( Url & url : urls )
2093 url.setPathName( url.getPathName() / path );
2095 it->setBaseUrls( std::move(urls) );
2099 ////////////////////////////////////////////////////////////////////////////
2100 // Now compare collected repos with the ones in the system...
2102 RepoInfoList oldRepos;
2103 getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
2105 ////////////////////////////////////////////////////////////////////////////
2106 // find old repositories to remove...
2107 for_( oldRepo, oldRepos.begin(), oldRepos.end() )
2109 if ( ! foundAliasIn( oldRepo->alias(), collector.repos ) )
2111 if ( oldRepo->enabled() )
2113 // Currently enabled. If this was a user modification remember the state.
2114 const auto & last = service.repoStates().find( oldRepo->alias() );
2115 if ( last != service.repoStates().end() && ! last->second.enabled )
2117 DBG << "Service removes user enabled repo " << oldRepo->alias() << endl;
2118 service.addRepoToEnable( oldRepo->alias() );
2119 serviceModified = true;
2122 DBG << "Service removes enabled repo " << oldRepo->alias() << endl;
2125 DBG << "Service removes disabled repo " << oldRepo->alias() << endl;
2127 removeRepository( *oldRepo );
2131 ////////////////////////////////////////////////////////////////////////////
2132 // create missing repositories and modify existing ones if needed...
2133 UrlCredentialExtractor urlCredentialExtractor( _options.rootDir ); // To collect any credentials stored in repo URLs
2134 for_( it, collector.repos.begin(), collector.repos.end() )
2136 // User explicitly requested the repo being enabled?
2137 // User explicitly requested the repo being disabled?
2138 // And hopefully not both ;) If so, enable wins.
2140 TriBool toBeEnabled( indeterminate ); // indeterminate - follow the service request
2141 DBG << "Service request to " << (it->enabled()?"enable":"disable") << " service repo " << it->alias() << endl;
2143 if ( options_r.testFlag( RefreshService_restoreStatus ) )
2145 DBG << "Opt RefreshService_restoreStatus " << it->alias() << endl;
2146 // this overrides any pending request!
2147 // Remove from enable request list.
2148 // NOTE: repoToDisable is handled differently.
2149 // It gets cleared on each refresh.
2150 service.delRepoToEnable( it->alias() );
2151 // toBeEnabled stays indeterminate!
2155 if ( service.repoToEnableFind( it->alias() ) )
2157 DBG << "User request to enable service repo " << it->alias() << endl;
2159 // Remove from enable request list.
2160 // NOTE: repoToDisable is handled differently.
2161 // It gets cleared on each refresh.
2162 service.delRepoToEnable( it->alias() );
2163 serviceModified = true;
2165 else if ( service.repoToDisableFind( it->alias() ) )
2167 DBG << "User request to disable service repo " << it->alias() << endl;
2168 toBeEnabled = false;
2172 RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
2173 if ( oldRepo == oldRepos.end() )
2175 // Not found in oldRepos ==> a new repo to add
2177 // Make sure the service repo is created with the appropriate enablement
2178 if ( ! indeterminate(toBeEnabled) )
2179 it->setEnabled( toBeEnabled );
2181 DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
2182 addRepository( *it );
2186 // ==> an exising repo to check
2187 bool oldRepoModified = false;
2189 if ( indeterminate(toBeEnabled) )
2191 // No user request: check for an old user modificaton otherwise follow service request.
2192 // NOTE: Assert toBeEnabled is boolean afterwards!
2193 if ( oldRepo->enabled() == it->enabled() )
2194 toBeEnabled = it->enabled(); // service requests no change to the system
2195 else if (options_r.testFlag( RefreshService_restoreStatus ) )
2197 toBeEnabled = it->enabled(); // RefreshService_restoreStatus forced
2198 DBG << "Opt RefreshService_restoreStatus " << it->alias() << " forces " << (toBeEnabled?"enabled":"disabled") << endl;
2202 const auto & last = service.repoStates().find( oldRepo->alias() );
2203 if ( last == service.repoStates().end() || last->second.enabled != it->enabled() )
2204 toBeEnabled = it->enabled(); // service request has changed since last refresh -> follow
2207 toBeEnabled = oldRepo->enabled(); // service request unchaned since last refresh -> keep user modification
2208 DBG << "User modified service repo " << it->alias() << " may stay " << (toBeEnabled?"enabled":"disabled") << endl;
2214 if ( toBeEnabled == oldRepo->enabled() )
2216 DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
2218 else if ( toBeEnabled )
2220 DBG << "Service repo " << it->alias() << " gets enabled" << endl;
2221 oldRepo->setEnabled( true );
2222 oldRepoModified = true;
2226 DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2227 oldRepo->setEnabled( false );
2228 oldRepoModified = true;
2231 // all other attributes follow the service request:
2233 // changed name (raw!)
2234 if ( oldRepo->rawName() != it->rawName() )
2236 DBG << "Service repo " << it->alias() << " gets new NAME " << it->rawName() << endl;
2237 oldRepo->setName( it->rawName() );
2238 oldRepoModified = true;
2241 // changed autorefresh
2242 if ( oldRepo->autorefresh() != it->autorefresh() )
2244 DBG << "Service repo " << it->alias() << " gets new AUTOREFRESH " << it->autorefresh() << endl;
2245 oldRepo->setAutorefresh( it->autorefresh() );
2246 oldRepoModified = true;
2249 // changed priority?
2250 if ( oldRepo->priority() != it->priority() )
2252 DBG << "Service repo " << it->alias() << " gets new PRIORITY " << it->priority() << endl;
2253 oldRepo->setPriority( it->priority() );
2254 oldRepoModified = true;
2259 RepoInfo::url_set newUrls( it->rawBaseUrls() );
2260 urlCredentialExtractor.extract( newUrls ); // Extract! to prevent passwds from disturbing the comparison below
2261 if ( oldRepo->rawBaseUrls() != newUrls )
2263 DBG << "Service repo " << it->alias() << " gets new URLs " << newUrls << endl;
2264 oldRepo->setBaseUrls( std::move(newUrls) );
2265 oldRepoModified = true;
2269 // changed gpg check settings?
2270 // ATM only plugin services can set GPG values.
2271 if ( service.type() == ServiceType::PLUGIN )
2273 TriBool ogpg[3]; // Gpg RepoGpg PkgGpg
2275 oldRepo->getRawGpgChecks( ogpg[0], ogpg[1], ogpg[2] );
2276 it-> getRawGpgChecks( ngpg[0], ngpg[1], ngpg[2] );
2277 #define Z_CHKGPG(I,N) \
2278 if ( ! sameTriboolState( ogpg[I], ngpg[I] ) ) \
2280 DBG << "Service repo " << it->alias() << " gets new "#N"Check " << ngpg[I] << endl; \
2281 oldRepo->set##N##Check( ngpg[I] ); \
2282 oldRepoModified = true; \
2285 Z_CHKGPG( 1, RepoGpg );
2286 Z_CHKGPG( 2, PkgGpg );
2290 // save if modified:
2291 if ( oldRepoModified )
2293 modifyRepository( oldRepo->alias(), *oldRepo );
2298 // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2299 if ( ! service.reposToDisableEmpty() )
2301 service.clearReposToDisable();
2302 serviceModified = true;
2305 // Remember original service request for next refresh
2306 if ( service.repoStates() != newRepoStates )
2308 service.setRepoStates( std::move(newRepoStates) );
2309 serviceModified = true;
2312 ////////////////////////////////////////////////////////////////////////////
2313 // save service if modified: (unless a plugin service)
2314 if ( serviceModified && service.type() != ServiceType::PLUGIN )
2316 // write out modified service file.
2317 modifyService( service.alias(), service );
2320 if ( uglyHack.first )
2322 throw( uglyHack.second ); // intentionally not ZYPP_THROW
2326 ////////////////////////////////////////////////////////////////////////////
2328 void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2330 MIL << "Going to modify service " << oldAlias << endl;
2332 // we need a writable copy to link it to the file where
2333 // it is saved if we modify it
2334 ServiceInfo service(newService);
2336 if ( service.type() == ServiceType::PLUGIN )
2338 ZYPP_THROW(ServicePluginImmutableException( service ));
2341 const ServiceInfo & oldService = getService(oldAlias);
2343 Pathname location = oldService.filepath();
2344 if( location.empty() )
2346 ZYPP_THROW(ServiceException( oldService, _("Can't figure out where the service is stored.") ));
2349 // remember: there may multiple services being defined in one file:
2351 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2353 filesystem::assert_dir(location.dirname());
2354 std::ofstream file(location.c_str());
2355 for_(it, tmpSet.begin(), tmpSet.end())
2357 if( *it != oldAlias )
2358 it->dumpAsIniOn(file);
2360 service.dumpAsIniOn(file);
2362 service.setFilepath(location);
2364 _services.erase(oldAlias);
2365 _services.insert(service);
2366 // check for credentials in Urls
2367 UrlCredentialExtractor( _options.rootDir ).collect( service.url() );
2370 // changed properties affecting also repositories
2371 if ( oldAlias != service.alias() // changed alias
2372 || oldService.enabled() != service.enabled() ) // changed enabled status
2374 std::vector<RepoInfo> toModify;
2375 getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2376 for_( it, toModify.begin(), toModify.end() )
2378 if ( oldService.enabled() != service.enabled() )
2380 if ( service.enabled() )
2382 // reset to last refreshs state
2383 const auto & last = service.repoStates().find( it->alias() );
2384 if ( last != service.repoStates().end() )
2385 it->setEnabled( last->second.enabled );
2388 it->setEnabled( false );
2391 if ( oldAlias != service.alias() )
2392 it->setService(service.alias());
2394 modifyRepository(it->alias(), *it);
2398 //! \todo refresh the service automatically if url is changed?
2401 ////////////////////////////////////////////////////////////////////////////
2403 repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2407 MediaSetAccess access(url);
2408 if ( access.doesFileExist("/repo/repoindex.xml") )
2409 return repo::ServiceType::RIS;
2411 catch ( const media::MediaException &e )
2414 // TranslatorExplanation '%s' is an URL
2415 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2419 catch ( const Exception &e )
2422 // TranslatorExplanation '%s' is an URL
2423 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2428 return repo::ServiceType::NONE;
2431 ///////////////////////////////////////////////////////////////////
2433 // CLASS NAME : RepoManager
2435 ///////////////////////////////////////////////////////////////////
2437 RepoManager::RepoManager( const RepoManagerOptions & opt )
2438 : _pimpl( new Impl(opt) )
2441 RepoManager::~RepoManager()
2444 bool RepoManager::repoEmpty() const
2445 { return _pimpl->repoEmpty(); }
2447 RepoManager::RepoSizeType RepoManager::repoSize() const
2448 { return _pimpl->repoSize(); }
2450 RepoManager::RepoConstIterator RepoManager::repoBegin() const
2451 { return _pimpl->repoBegin(); }
2453 RepoManager::RepoConstIterator RepoManager::repoEnd() const
2454 { return _pimpl->repoEnd(); }
2456 RepoInfo RepoManager::getRepo( const std::string & alias ) const
2457 { return _pimpl->getRepo( alias ); }
2459 bool RepoManager::hasRepo( const std::string & alias ) const
2460 { return _pimpl->hasRepo( alias ); }
2462 std::string RepoManager::makeStupidAlias( const Url & url_r )
2464 std::string ret( url_r.getScheme() );
2470 std::string host( url_r.getHost() );
2471 if ( ! host.empty() )
2477 static Date::ValueType serial = Date::now();
2478 ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2482 RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2483 { return _pimpl->metadataStatus( info ); }
2485 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2486 { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2488 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2489 { return _pimpl->metadataPath( info ); }
2491 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2492 { return _pimpl->packagesPath( info ); }
2494 void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2495 { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2497 void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2498 { return _pimpl->cleanMetadata( info, progressrcv ); }
2500 void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2501 { return _pimpl->cleanPackages( info, progressrcv ); }
2503 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2504 { return _pimpl->cacheStatus( info ); }
2506 void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2507 { return _pimpl->buildCache( info, policy, progressrcv ); }
2509 void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2510 { return _pimpl->cleanCache( info, progressrcv ); }
2512 bool RepoManager::isCached( const RepoInfo &info ) const
2513 { return _pimpl->isCached( info ); }
2515 void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2516 { return _pimpl->loadFromCache( info, progressrcv ); }
2518 void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2519 { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2521 repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2522 { return _pimpl->probe( url, path ); }
2524 repo::RepoType RepoManager::probe( const Url & url ) const
2525 { return _pimpl->probe( url ); }
2527 void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2528 { return _pimpl->addRepository( info, progressrcv ); }
2530 void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2531 { return _pimpl->addRepositories( url, progressrcv ); }
2533 void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2534 { return _pimpl->removeRepository( info, progressrcv ); }
2536 void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2537 { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2539 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2540 { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2542 RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2543 { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2545 bool RepoManager::serviceEmpty() const
2546 { return _pimpl->serviceEmpty(); }
2548 RepoManager::ServiceSizeType RepoManager::serviceSize() const
2549 { return _pimpl->serviceSize(); }
2551 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2552 { return _pimpl->serviceBegin(); }
2554 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2555 { return _pimpl->serviceEnd(); }
2557 ServiceInfo RepoManager::getService( const std::string & alias ) const
2558 { return _pimpl->getService( alias ); }
2560 bool RepoManager::hasService( const std::string & alias ) const
2561 { return _pimpl->hasService( alias ); }
2563 repo::ServiceType RepoManager::probeService( const Url &url ) const
2564 { return _pimpl->probeService( url ); }
2566 void RepoManager::addService( const std::string & alias, const Url& url )
2567 { return _pimpl->addService( alias, url ); }
2569 void RepoManager::addService( const ServiceInfo & service )
2570 { return _pimpl->addService( service ); }
2572 void RepoManager::removeService( const std::string & alias )
2573 { return _pimpl->removeService( alias ); }
2575 void RepoManager::removeService( const ServiceInfo & service )
2576 { return _pimpl->removeService( service ); }
2578 void RepoManager::refreshServices( const RefreshServiceOptions & options_r )
2579 { return _pimpl->refreshServices( options_r ); }
2581 void RepoManager::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2582 { return _pimpl->refreshService( alias, options_r ); }
2584 void RepoManager::refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
2585 { return _pimpl->refreshService( service, options_r ); }
2587 void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2588 { return _pimpl->modifyService( oldAlias, service ); }
2590 ////////////////////////////////////////////////////////////////////////////
2592 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2593 { return str << *obj._pimpl; }
2595 /////////////////////////////////////////////////////////////////
2597 ///////////////////////////////////////////////////////////////////