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/parser/RepoindexFileReader.h"
42 #include "zypp/repo/yum/Downloader.h"
43 #include "zypp/repo/susetags/Downloader.h"
44 #include "zypp/parser/plaindir/RepoParser.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 ///////////////////////////////////////////////////////////////////
60 { /////////////////////////////////////////////////////////////////
64 /** Check if alias_r is present in repo/service container. */
65 template <class Iterator>
66 inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
68 for_( it, begin_r, end_r )
69 if ( it->alias() == alias_r )
74 template <class Container>
75 inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
76 { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
78 /** Find alias_r in repo/service container. */
79 template <class Iterator>
80 inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
82 for_( it, begin_r, end_r )
83 if ( it->alias() == alias_r )
88 template <class Container>
89 inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
90 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
92 template <class Container>
93 inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
94 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
97 ///////////////////////////////////////////////////////////////////
99 // CLASS NAME : RepoManagerOptions
101 ///////////////////////////////////////////////////////////////////
103 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
105 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
106 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
107 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
108 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
109 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
110 knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
111 probe = ZConfig::instance().repo_add_probe();
116 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
118 RepoManagerOptions ret;
119 ret.repoCachePath = root_r;
120 ret.repoRawCachePath = root_r/"raw";
121 ret.repoSolvCachePath = root_r/"solv";
122 ret.repoPackagesCachePath = root_r/"packages";
123 ret.knownReposPath = root_r/"repos.d";
124 ret.knownServicesPath = root_r/"services.d";
125 ret.rootDir = root_r;
129 ////////////////////////////////////////////////////////////////////////////
132 * \short Simple callback to collect the results
134 * Classes like RepoFileParser call the callback
135 * once per each repo in a file.
137 * Passing this functor as callback, you can collect
138 * all results at the end, without dealing with async
141 * If targetDistro is set, all repos with non-empty RepoInfo::targetDistribution()
144 * \todo do this through a separate filter
146 struct RepoCollector : private base::NonCopyable
151 RepoCollector(const std::string & targetDistro_)
152 : targetDistro(targetDistro_)
155 bool collect( const RepoInfo &repo )
157 // skip repositories meant for other distros than specified
158 if (!targetDistro.empty()
159 && !repo.targetDistribution().empty()
160 && repo.targetDistribution() != targetDistro)
163 << "Skipping repository meant for '" << targetDistro
164 << "' distribution (current distro is '"
165 << repo.targetDistribution() << "')." << endl;
170 repos.push_back(repo);
175 std::string targetDistro;
178 ////////////////////////////////////////////////////////////////////////////
181 * Reads RepoInfo's from a repo file.
183 * \param file pathname of the file to read.
185 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
187 MIL << "repo file: " << file << endl;
188 RepoCollector collector;
189 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
190 return collector.repos;
193 ////////////////////////////////////////////////////////////////////////////
196 * \short List of RepoInfo's from a directory
198 * Goes trough every file ending with ".repo" in a directory and adds all
199 * RepoInfo's contained in that file.
201 * \param dir pathname of the directory to read.
203 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
205 MIL << "directory " << dir << endl;
206 std::list<RepoInfo> repos;
207 std::list<Pathname> entries;
208 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
209 ZYPP_THROW(Exception("failed to read directory"));
211 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
212 for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
214 if (str::regex_match(it->extension(), allowedRepoExt))
216 std::list<RepoInfo> tmp = repositories_in_file( *it );
217 repos.insert( repos.end(), tmp.begin(), tmp.end() );
219 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
220 //MIL << "ok" << endl;
226 ////////////////////////////////////////////////////////////////////////////
228 std::list<RepoInfo> readRepoFile(const Url & repo_file)
230 // no interface to download a specific file, using workaround:
231 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
233 Pathname path(url.getPathName());
234 url.setPathName ("/");
235 MediaSetAccess access(url);
236 Pathname local = access.provideFile(path);
238 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
240 return repositories_in_file(local);
243 ////////////////////////////////////////////////////////////////////////////
245 inline void assert_alias( const RepoInfo & info )
247 if ( info.alias().empty() )
248 ZYPP_THROW( RepoNoAliasException() );
251 inline void assert_alias( const ServiceInfo & info )
253 if ( info.alias().empty() )
254 ZYPP_THROW( ServiceNoAliasException() );
257 ////////////////////////////////////////////////////////////////////////////
259 inline void assert_urls( const RepoInfo & info )
261 if ( info.baseUrlsEmpty() )
262 ZYPP_THROW( RepoNoUrlException( info ) );
265 inline void assert_url( const ServiceInfo & info )
267 if ( ! info.url().isValid() )
268 ZYPP_THROW( ServiceNoUrlException( info ) );
271 ////////////////////////////////////////////////////////////////////////////
274 * \short Calculates the raw cache path for a repository, this is usually
275 * /var/cache/zypp/alias
277 inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
280 return opt.repoRawCachePath / info.escaped_alias();
284 * \short Calculates the raw metadata cache path for a repository, this is
285 * inside the raw cache dir, plus the path where the metadata is.
287 * It should be different only for repositories that are not in the root of
289 * for example /var/cache/zypp/alias/addondir
291 inline Pathname rawmetadata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
294 return opt.repoRawCachePath / info.escaped_alias() / info.path();
299 * \short Calculates the packages cache path for a repository
301 inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
304 return opt.repoPackagesCachePath / info.escaped_alias();
308 * \short Calculates the solv cache path for a repository
310 inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
313 return opt.repoSolvCachePath / info.escaped_alias();
316 ////////////////////////////////////////////////////////////////////////////
318 /** Functor collecting ServiceInfos into a ServiceSet. */
319 class ServiceCollector
322 typedef std::set<ServiceInfo> ServiceSet;
324 ServiceCollector( ServiceSet & services_r )
325 : _services( services_r )
328 bool operator()( const ServiceInfo & service_r ) const
330 _services.insert( service_r );
335 ServiceSet & _services;
338 ////////////////////////////////////////////////////////////////////////////
340 ///////////////////////////////////////////////////////////////////
342 // CLASS NAME : RepoManager::Impl
344 ///////////////////////////////////////////////////////////////////
347 * \short RepoManager implementation.
349 struct RepoManager::Impl
351 Impl( const RepoManagerOptions &opt )
354 init_knownServices();
355 init_knownRepositories();
358 RepoManagerOptions options;
366 void saveService( ServiceInfo & service ) const;
368 Pathname generateNonExistingName( const Pathname &dir,
369 const std::string &basefilename ) const;
371 std::string generateFilename( const RepoInfo & info ) const;
372 std::string generateFilename( const ServiceInfo & info ) const;
376 void init_knownServices();
377 void init_knownRepositories();
380 friend Impl * rwcowClone<Impl>( const Impl * rhs );
381 /** clone for RWCOW_pointer */
383 { return new Impl( *this ); }
386 ///////////////////////////////////////////////////////////////////
388 /** \relates RepoManager::Impl Stream output */
389 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
391 return str << "RepoManager::Impl";
394 ///////////////////////////////////////////////////////////////////
396 void RepoManager::Impl::saveService( ServiceInfo & service ) const
398 filesystem::assert_dir( options.knownServicesPath );
399 Pathname servfile = generateNonExistingName( options.knownServicesPath,
400 generateFilename( service ) );
401 service.setFilepath( servfile );
403 MIL << "saving service in " << servfile << endl;
405 std::ofstream file( servfile.c_str() );
408 ZYPP_THROW( Exception( "Can't open " + servfile.asString() ) );
410 service.dumpAsIniOn( file );
411 MIL << "done" << endl;
415 * Generate a non existing filename in a directory, using a base
416 * name. For example if a directory contains 3 files
422 * If you try to generate a unique filename for this directory,
423 * based on "ruu" you will get "ruu", but if you use the base
424 * "foo" you will get "foo_1"
426 * \param dir Directory where the file needs to be unique
427 * \param basefilename string to base the filename on.
429 Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
430 const std::string & basefilename ) const
432 std::string final_filename = basefilename;
434 while ( PathInfo(dir + final_filename).isExist() )
436 final_filename = basefilename + "_" + str::numstring(counter);
439 return dir + Pathname(final_filename);
442 ////////////////////////////////////////////////////////////////////////////
445 * \short Generate a related filename from a repo info
447 * From a repo info, it will try to use the alias as a filename
448 * escaping it if necessary. Other fallbacks can be added to
449 * this function in case there is no way to use the alias
451 std::string RepoManager::Impl::generateFilename( const RepoInfo & info ) const
453 std::string filename = info.alias();
454 // replace slashes with underscores
455 str::replaceAll( filename, "/", "_" );
457 filename = Pathname(filename).extend(".repo").asString();
458 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
462 std::string RepoManager::Impl::generateFilename( const ServiceInfo & info ) const
464 std::string filename = info.alias();
465 // replace slashes with underscores
466 str::replaceAll( filename, "/", "_" );
468 filename = Pathname(filename).extend(".service").asString();
469 MIL << "generating filename for service [" << info.alias() << "] : '" << filename << "'" << endl;
474 void RepoManager::Impl::init_knownServices()
476 Pathname dir = options.knownServicesPath;
477 std::list<Pathname> entries;
478 if (PathInfo(dir).isExist())
480 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
481 ZYPP_THROW(Exception("failed to read directory"));
483 //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
484 for_(it, entries.begin(), entries.end() )
486 parser::ServiceFileReader(*it, ServiceCollector(services));
491 void RepoManager::Impl::init_knownRepositories()
493 MIL << "start construct known repos" << endl;
495 if ( PathInfo(options.knownReposPath).isExist() )
497 RepoInfoList repol = repositories_in_dir(options.knownReposPath);
498 for ( RepoInfoList::iterator it = repol.begin();
502 // set the metadata path for the repo
503 Pathname metadata_path = rawmetadata_path_for_repoinfo(options, (*it));
504 (*it).setMetadataPath(metadata_path);
506 // set the downloaded packages path for the repo
507 Pathname packages_path = packagescache_path_for_repoinfo(options, (*it));
508 (*it).setPackagesPath(packages_path);
514 MIL << "end construct known repos" << endl;
517 ///////////////////////////////////////////////////////////////////
519 // CLASS NAME : RepoManager
521 ///////////////////////////////////////////////////////////////////
523 RepoManager::RepoManager( const RepoManagerOptions &opt )
524 : _pimpl( new Impl(opt) )
527 ////////////////////////////////////////////////////////////////////////////
529 RepoManager::~RepoManager()
532 ////////////////////////////////////////////////////////////////////////////
534 bool RepoManager::repoEmpty() const
535 { return _pimpl->repos.empty(); }
537 RepoManager::RepoSizeType RepoManager::repoSize() const
538 { return _pimpl->repos.size(); }
540 RepoManager::RepoConstIterator RepoManager::repoBegin() const
541 { return _pimpl->repos.begin(); }
543 RepoManager::RepoConstIterator RepoManager::repoEnd() const
544 { return _pimpl->repos.end(); }
546 RepoInfo RepoManager::getRepo( const std::string & alias ) const
548 for_( it, repoBegin(), repoEnd() )
549 if ( it->alias() == alias )
551 return RepoInfo::noRepo;
554 bool RepoManager::hasRepo( const std::string & alias ) const
556 for_( it, repoBegin(), repoEnd() )
557 if ( it->alias() == alias )
562 ////////////////////////////////////////////////////////////////////////////
564 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
566 return rawmetadata_path_for_repoinfo(_pimpl->options, info );
569 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
571 return packagescache_path_for_repoinfo(_pimpl->options, info );
574 ////////////////////////////////////////////////////////////////////////////
576 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
578 Pathname rawpath = rawmetadata_path_for_repoinfo( _pimpl->options, info );
579 Pathname mediarootpath = rawcache_path_for_repoinfo( _pimpl->options, info );
580 RepoType repokind = info.type();
583 switch ( repokind.toEnum() )
585 case RepoType::NONE_e:
586 // unknown, probe the local metadata
587 repokind = probe(rawpath.asUrl());
593 switch ( repokind.toEnum() )
595 case RepoType::RPMMD_e :
597 status = RepoStatus( rawpath + "/repodata/repomd.xml");
601 case RepoType::YAST2_e :
603 status = RepoStatus( rawpath + "/content") && (RepoStatus( mediarootpath + "/media.1/media"));
607 case RepoType::RPMPLAINDIR_e :
609 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
610 status = RepoStatus( rawpath + "/cookie");
614 case RepoType::NONE_e :
615 // Return default RepoStatus in case of RepoType::NONE
616 // indicating it should be created?
617 // ZYPP_THROW(RepoUnknownTypeException());
623 void RepoManager::touchIndexFile(const RepoInfo & info)
625 Pathname rawpath = rawmetadata_path_for_repoinfo( _pimpl->options, info );
627 RepoType repokind = info.type();
628 if ( repokind.toEnum() == RepoType::NONE_e )
629 // unknown, probe the local metadata
630 repokind = probe(rawpath.asUrl());
631 // if still unknown, just return
632 if (repokind == RepoType::NONE_e)
636 switch ( repokind.toEnum() )
638 case RepoType::RPMMD_e :
639 p = Pathname(rawpath + "/repodata/repomd.xml");
642 case RepoType::YAST2_e :
643 p = Pathname(rawpath + "/content");
646 case RepoType::RPMPLAINDIR_e :
647 p = Pathname(rawpath + "/cookie");
650 case RepoType::NONE_e :
655 // touch the file, ignore error (they are logged anyway)
656 filesystem::touch(p);
659 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata(
660 const RepoInfo &info,
662 RawMetadataRefreshPolicy policy )
666 RepoStatus oldstatus;
667 RepoStatus newstatus;
671 MIL << "Going to try to check whether refresh is needed for " << url << endl;
673 repo::RepoType repokind = info.type();
675 // if the type is unknown, try probing.
676 switch ( repokind.toEnum() )
678 case RepoType::NONE_e:
680 repokind = probe(url);
686 Pathname rawpath = rawmetadata_path_for_repoinfo( _pimpl->options, info );
687 filesystem::assert_dir(rawpath);
688 oldstatus = metadataStatus(info);
690 // now we've got the old (cached) status, we can decide repo.refresh.delay
691 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
693 // difference in seconds
694 double diff = difftime(
695 (Date::ValueType)Date::now(),
696 (Date::ValueType)oldstatus.timestamp()) / 60;
698 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
699 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
700 DBG << "last refresh = " << diff << " minutes ago" << endl;
702 if (diff < ZConfig::instance().repo_refresh_delay())
704 MIL << "Repository '" << info.alias()
705 << "' has been refreshed less than repo.refresh.delay ("
706 << ZConfig::instance().repo_refresh_delay()
707 << ") minutes ago. Advising to skip refresh" << endl;
708 return REPO_CHECK_DELAYED;
712 // create temp dir as sibling of rawpath
713 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
715 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
716 ( repokind.toEnum() == RepoType::YAST2_e ) )
718 MediaSetAccess media(url);
719 shared_ptr<repo::Downloader> downloader_ptr;
721 if ( repokind.toEnum() == RepoType::RPMMD_e )
722 downloader_ptr.reset(new yum::Downloader(info));
724 downloader_ptr.reset( new susetags::Downloader(info));
726 RepoStatus newstatus = downloader_ptr->status(media);
727 bool refresh = false;
728 if ( oldstatus.checksum() == newstatus.checksum() )
730 MIL << "repo has not changed" << endl;
731 if ( policy == RefreshForced )
733 MIL << "refresh set to forced" << endl;
739 MIL << "repo has changed, going to refresh" << endl;
744 touchIndexFile(info);
746 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
748 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
750 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
751 bool refresh = false;
752 if ( oldstatus.checksum() == newstatus.checksum() )
754 MIL << "repo has not changed" << endl;
755 if ( policy == RefreshForced )
757 MIL << "refresh set to forced" << endl;
763 MIL << "repo has changed, going to refresh" << endl;
768 touchIndexFile(info);
770 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
774 ZYPP_THROW(RepoUnknownTypeException(info));
777 catch ( const Exception &e )
780 ERR << "refresh check failed for " << url << endl;
784 return REFRESH_NEEDED; // default
787 void RepoManager::refreshMetadata( const RepoInfo &info,
788 RawMetadataRefreshPolicy policy,
789 const ProgressData::ReceiverFnc & progress )
794 // we will throw this later if no URL checks out fine
795 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
797 // try urls one by one
798 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
804 // check whether to refresh metadata
805 // if the check fails for this url, it throws, so another url will be checked
806 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
809 MIL << "Going to refresh metadata from " << url << endl;
811 repo::RepoType repokind = info.type();
813 // if the type is unknown, try probing.
814 switch ( repokind.toEnum() )
816 case RepoType::NONE_e:
818 repokind = probe(*it);
820 if (repokind.toEnum() != RepoType::NONE_e)
822 // Adjust the probed type in RepoInfo
823 info.setProbedType( repokind ); // lazy init!
824 //save probed type only for repos in system
825 for_( it, repoBegin(), repoEnd() )
827 if ( info.alias() == (*it).alias() )
829 RepoInfo modifiedrepo = info;
830 modifiedrepo.setType( repokind );
831 modifyRepository( info.alias(), modifiedrepo );
841 Pathname rawpath = rawmetadata_path_for_repoinfo( _pimpl->options, info );
842 filesystem::assert_dir(rawpath);
844 // create temp dir as sibling of rawpath
845 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
847 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
848 ( repokind.toEnum() == RepoType::YAST2_e ) )
850 MediaSetAccess media(url);
851 shared_ptr<repo::Downloader> downloader_ptr;
853 MIL << "Creating downloader for [ " << info.name() << " ]" << endl;
855 if ( repokind.toEnum() == RepoType::RPMMD_e )
856 downloader_ptr.reset(new yum::Downloader(info));
858 downloader_ptr.reset( new susetags::Downloader(info) );
861 * Given a downloader, sets the other repos raw metadata
862 * path as cache paths for the fetcher, so if another
863 * repo has the same file, it will not download it
864 * but copy it from the other repository
866 for_( it, repoBegin(), repoEnd() )
868 Pathname cachepath(rawmetadata_path_for_repoinfo( _pimpl->options, *it ));
869 if ( PathInfo(cachepath).isExist() )
870 downloader_ptr->addCachePath(cachepath);
873 downloader_ptr->download( media, tmpdir.path());
875 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
877 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
879 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
881 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
884 file << newstatus.checksum() << endl;
890 ZYPP_THROW(RepoUnknownTypeException());
893 // ok we have the metadata, now exchange
896 filesystem::TmpDir oldmetadata( filesystem::TmpDir::makeSibling( rawpath ) );
897 filesystem::rename( rawpath, oldmetadata.path() );
898 // move the just downloaded there
899 filesystem::rename( tmpdir.path(), rawpath );
904 catch ( const Exception &e )
907 ERR << "Trying another url..." << endl;
909 // remember the exception caught for the *first URL*
910 // if all other URLs fail, the rexception will be thrown with the
911 // cause of the problem of the first URL remembered
912 if (it == info.baseUrlsBegin())
913 rexception.remember(e);
916 ERR << "No more urls..." << endl;
917 ZYPP_THROW(rexception);
920 ////////////////////////////////////////////////////////////////////////////
922 void RepoManager::cleanMetadata( const RepoInfo &info,
923 const ProgressData::ReceiverFnc & progressfnc )
925 ProgressData progress(100);
926 progress.sendTo(progressfnc);
928 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
932 void RepoManager::cleanPackages( const RepoInfo &info,
933 const ProgressData::ReceiverFnc & progressfnc )
935 ProgressData progress(100);
936 progress.sendTo(progressfnc);
938 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
942 void RepoManager::buildCache( const RepoInfo &info,
943 CacheBuildPolicy policy,
944 const ProgressData::ReceiverFnc & progressrcv )
947 Pathname rawpath = rawmetadata_path_for_repoinfo(_pimpl->options, info);
949 filesystem::assert_dir(_pimpl->options.repoCachePath);
950 RepoStatus raw_metadata_status = metadataStatus(info);
951 if ( raw_metadata_status.empty() )
953 /* if there is no cache at this point, we refresh the raw
954 in case this is the first time - if it's !autorefresh,
955 we may still refresh */
956 refreshMetadata(info, RefreshIfNeeded, progressrcv );
957 raw_metadata_status = metadataStatus(info);
960 bool needs_cleaning = false;
961 if ( isCached( info ) )
963 MIL << info.alias() << " is already cached." << endl;
964 RepoStatus cache_status = cacheStatus(info);
966 if ( cache_status.checksum() == raw_metadata_status.checksum() )
968 MIL << info.alias() << " cache is up to date with metadata." << endl;
969 if ( policy == BuildIfNeeded ) {
973 MIL << info.alias() << " cache rebuild is forced" << endl;
977 needs_cleaning = true;
980 ProgressData progress(100);
981 callback::SendReport<ProgressReport> report;
982 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
983 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
991 MIL << info.alias() << " building cache..." << endl;
993 Pathname base = solv_path_for_repoinfo( _pimpl->options, info);
994 filesystem::assert_dir(base);
995 Pathname solvfile = base / "solv";
998 repo::RepoType repokind = info.type();
1000 // if the type is unknown, try probing.
1001 switch ( repokind.toEnum() )
1003 case RepoType::NONE_e:
1004 // unknown, probe the local metadata
1005 repokind = probe(rawpath.asUrl());
1011 MIL << "repo type is " << repokind << endl;
1013 switch ( repokind.toEnum() )
1015 case RepoType::RPMMD_e :
1016 case RepoType::YAST2_e :
1017 case RepoType::RPMPLAINDIR_e :
1019 // Take care we unlink the solvfile on exception
1020 ManagedFile guard( solvfile, filesystem::unlink );
1022 ExternalProgram::Arguments cmd;
1023 cmd.push_back( "repo2solv.sh" );
1025 // repo2solv expects -o as 1st arg!
1026 cmd.push_back( "-o" );
1027 cmd.push_back( solvfile.asString() );
1029 if ( repokind == RepoType::RPMPLAINDIR )
1030 // FIXME this does only work form dir: URLs
1031 cmd.push_back( info.baseUrlsBegin()->getPathName() );
1033 cmd.push_back( rawpath.asString() );
1035 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1036 std::string errdetail;
1038 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1039 WAR << " " << output;
1040 if ( errdetail.empty() ) {
1041 errdetail = prog.command();
1044 errdetail += output;
1047 int ret = prog.close();
1050 RepoException ex(str::form("Failed to cache repo (%d).", ret));
1051 ex.remember( errdetail );
1056 guard.resetDispose();
1060 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
1063 // update timestamp and checksum
1064 setCacheStatus(info, raw_metadata_status);
1065 MIL << "Commit cache.." << endl;
1069 ////////////////////////////////////////////////////////////////////////////
1071 repo::RepoType RepoManager::probe( const Url &url ) const
1073 MIL << "going to probe the type of the repo " << endl;
1075 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
1077 // Handle non existing local directory in advance, as
1078 // MediaSetAccess does not support it.
1079 return repo::RepoType::NONE;
1082 // prepare exception to be thrown if the type could not be determined
1083 // due to a media exception. We can't throw right away, because of some
1084 // problems with proxy servers returning an incorrect error
1085 // on ftp file-not-found(bnc #335906). Instead we'll check another types
1087 RepoException enew("Error trying to read from " + url.asString());
1088 bool gotMediaException = false;
1091 MediaSetAccess access(url);
1094 if ( access.doesFileExist("/repodata/repomd.xml") )
1095 return repo::RepoType::RPMMD;
1097 catch ( const media::MediaException &e )
1100 DBG << "problem checking for repodata/repomd.xml file" << endl;
1102 gotMediaException = true;
1107 if ( access.doesFileExist("/content") )
1108 return repo::RepoType::YAST2;
1110 catch ( const media::MediaException &e )
1113 DBG << "problem checking for content file" << endl;
1115 gotMediaException = true;
1118 // if it is a local url of type dir
1119 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
1121 Pathname path = Pathname(url.getPathName());
1122 if ( PathInfo(path).isDir() )
1124 // allow empty dirs for now
1125 return repo::RepoType::RPMPLAINDIR;
1129 catch ( const Exception &e )
1132 Exception enew("Unknown error reading from " + url.asString());
1137 if (gotMediaException)
1140 return repo::RepoType::NONE;
1143 ////////////////////////////////////////////////////////////////////////////
1145 void RepoManager::cleanCache( const RepoInfo &info,
1146 const ProgressData::ReceiverFnc & progressrcv )
1148 ProgressData progress(100);
1149 progress.sendTo(progressrcv);
1152 filesystem::recursive_rmdir(solv_path_for_repoinfo(_pimpl->options, info));
1157 ////////////////////////////////////////////////////////////////////////////
1159 bool RepoManager::isCached( const RepoInfo &info ) const
1161 return PathInfo(solv_path_for_repoinfo( _pimpl->options, info ) / "solv").isExist();
1164 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
1167 Pathname cookiefile = solv_path_for_repoinfo(_pimpl->options, info) / "cookie";
1169 return RepoStatus::fromCookieFile(cookiefile);
1172 void RepoManager::setCacheStatus( const RepoInfo &info, const RepoStatus &status )
1174 Pathname base = solv_path_for_repoinfo(_pimpl->options, info);
1175 filesystem::assert_dir(base);
1176 Pathname cookiefile = base / "cookie";
1178 status.saveToCookieFile(cookiefile);
1181 void RepoManager::loadFromCache( const RepoInfo & info,
1182 const ProgressData::ReceiverFnc & progressrcv )
1185 Pathname solvfile = solv_path_for_repoinfo(_pimpl->options, info) / "solv";
1187 if ( ! PathInfo(solvfile).isExist() )
1188 ZYPP_THROW(RepoNotCachedException(info));
1192 sat::Pool::instance().addRepoSolv( solvfile, info );
1194 catch ( const Exception & exp )
1197 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1198 cleanCache( info, progressrcv );
1199 buildCache( info, BuildIfNeeded, progressrcv );
1201 sat::Pool::instance().addRepoSolv( solvfile, info );
1205 ////////////////////////////////////////////////////////////////////////////
1207 void RepoManager::addRepository( const RepoInfo &info,
1208 const ProgressData::ReceiverFnc & progressrcv )
1212 ProgressData progress(100);
1213 callback::SendReport<ProgressReport> report;
1214 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1215 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1218 RepoInfo tosave = info;
1219 if(_pimpl->repos.find(tosave)!= _pimpl->repos.end())
1220 ZYPP_THROW(RepoAlreadyExistsException(info));
1223 // check the first url for now
1224 if ( _pimpl->options.probe )
1226 DBG << "unknown repository type, probing" << endl;
1228 RepoType probedtype;
1229 probedtype = probe(*tosave.baseUrlsBegin());
1230 if ( tosave.baseUrlsSize() > 0 )
1232 if ( probedtype == RepoType::NONE )
1233 ZYPP_THROW(RepoUnknownTypeException());
1235 tosave.setType(probedtype);
1241 // assert the directory exists
1242 filesystem::assert_dir(_pimpl->options.knownReposPath);
1244 Pathname repofile = _pimpl->generateNonExistingName(
1245 _pimpl->options.knownReposPath, _pimpl->generateFilename(tosave));
1246 // now we have a filename that does not exists
1247 MIL << "Saving repo in " << repofile << endl;
1249 std::ofstream file(repofile.c_str());
1251 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1254 tosave.dumpAsIniOn(file);
1255 tosave.setFilepath(repofile);
1256 _pimpl->repos.insert(tosave);
1260 // check for credentials in Urls
1261 bool havePasswords = false;
1262 for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1263 if ( urlit->hasCredentialsInAuthority() )
1265 havePasswords = true;
1268 // save the credentials
1269 if ( havePasswords )
1271 media::CredentialManager cm(
1272 media::CredManagerOptions(_pimpl->options.rootDir) );
1274 for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1275 if (urlit->hasCredentialsInAuthority())
1276 //! \todo use a method calling UI callbacks to ask where to save creds?
1277 cm.saveInUser(media::AuthData(*urlit));
1280 HistoryLog().addRepository(tosave);
1283 MIL << "done" << endl;
1286 void RepoManager::addRepositories( const Url &url,
1287 const ProgressData::ReceiverFnc & progressrcv )
1289 std::list<RepoInfo> repos = readRepoFile(url);
1290 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1294 // look if the alias is in the known repos.
1295 for_ ( kit, repoBegin(), repoEnd() )
1297 if ( (*it).alias() == (*kit).alias() )
1299 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1300 ZYPP_THROW(RepoAlreadyExistsException(*it));
1305 std::string filename = Pathname(url.getPathName()).basename();
1307 if ( filename == Pathname() )
1308 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1310 // assert the directory exists
1311 filesystem::assert_dir(_pimpl->options.knownReposPath);
1313 Pathname repofile = _pimpl->generateNonExistingName(_pimpl->options.knownReposPath, filename);
1314 // now we have a filename that does not exists
1315 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1317 std::ofstream file(repofile.c_str());
1319 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1322 for ( std::list<RepoInfo>::iterator it = repos.begin();
1326 MIL << "Saving " << (*it).alias() << endl;
1327 it->setFilepath(repofile.asString());
1328 it->dumpAsIniOn(file);
1329 _pimpl->repos.insert(*it);
1331 HistoryLog(_pimpl->options.rootDir).addRepository(*it);
1334 MIL << "done" << endl;
1337 ////////////////////////////////////////////////////////////////////////////
1339 void RepoManager::removeRepository( const RepoInfo & info,
1340 const ProgressData::ReceiverFnc & progressrcv)
1342 ProgressData progress;
1343 callback::SendReport<ProgressReport> report;
1344 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1345 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1347 MIL << "Going to delete repo " << info.alias() << endl;
1349 for_( it, repoBegin(), repoEnd() )
1351 // they can be the same only if the provided is empty, that means
1352 // the provided repo has no alias
1354 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1357 // TODO match by url
1359 // we have a matcing repository, now we need to know
1360 // where it does come from.
1361 RepoInfo todelete = *it;
1362 if (todelete.filepath().empty())
1364 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1368 // figure how many repos are there in the file:
1369 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1370 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1372 // easy, only this one, just delete the file
1373 if ( filesystem::unlink(todelete.filepath()) != 0 )
1375 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1377 MIL << todelete.alias() << " sucessfully deleted." << endl;
1381 // there are more repos in the same file
1382 // write them back except the deleted one.
1384 //std::ofstream file(tmp.path().c_str());
1386 // assert the directory exists
1387 filesystem::assert_dir(todelete.filepath().dirname());
1389 std::ofstream file(todelete.filepath().c_str());
1391 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1392 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1394 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1395 fit != filerepos.end();
1398 if ( (*fit).alias() != todelete.alias() )
1399 (*fit).dumpAsIniOn(file);
1403 CombinedProgressData subprogrcv(progress, 70);
1404 CombinedProgressData cleansubprogrcv(progress, 30);
1405 // now delete it from cache
1406 if ( isCached(todelete) )
1407 cleanCache( todelete, subprogrcv);
1408 // now delete metadata (#301037)
1409 cleanMetadata( todelete, cleansubprogrcv);
1410 _pimpl->repos.erase(todelete);
1411 MIL << todelete.alias() << " sucessfully deleted." << endl;
1412 HistoryLog(_pimpl->options.rootDir).removeRepository(todelete);
1414 } // else filepath is empty
1417 // should not be reached on a sucess workflow
1418 ZYPP_THROW(RepoNotFoundException(info));
1421 ////////////////////////////////////////////////////////////////////////////
1423 void RepoManager::modifyRepository( const std::string &alias,
1424 const RepoInfo & newinfo,
1425 const ProgressData::ReceiverFnc & progressrcv )
1427 RepoInfo toedit = getRepositoryInfo(alias);
1429 // check if the new alias already exists when renaming the repo
1430 if (alias != newinfo.alias())
1432 for_( it, repoBegin(), repoEnd() )
1434 if ( newinfo.alias() == (*it).alias() )
1435 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1439 if (toedit.filepath().empty())
1441 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1445 // figure how many repos are there in the file:
1446 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1448 // there are more repos in the same file
1449 // write them back except the deleted one.
1451 //std::ofstream file(tmp.path().c_str());
1453 // assert the directory exists
1454 filesystem::assert_dir(toedit.filepath().dirname());
1456 std::ofstream file(toedit.filepath().c_str());
1458 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1459 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1461 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1462 fit != filerepos.end();
1465 // if the alias is different, dump the original
1466 // if it is the same, dump the provided one
1467 if ( (*fit).alias() != toedit.alias() )
1468 (*fit).dumpAsIniOn(file);
1470 newinfo.dumpAsIniOn(file);
1473 _pimpl->repos.erase(toedit);
1474 _pimpl->repos.insert(newinfo);
1475 HistoryLog(_pimpl->options.rootDir).modifyRepository(toedit, newinfo);
1476 MIL << "repo " << alias << " modified" << endl;
1480 ////////////////////////////////////////////////////////////////////////////
1482 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1483 const ProgressData::ReceiverFnc & progressrcv )
1486 info.setAlias(alias);
1487 RepoConstIterator it = _pimpl->repos.find( info );
1488 if( it == repoEnd() )
1489 ZYPP_THROW(RepoNotFoundException(info));
1494 ////////////////////////////////////////////////////////////////////////////
1496 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1497 const url::ViewOption & urlview,
1498 const ProgressData::ReceiverFnc & progressrcv )
1500 for_( it, repoBegin(), repoEnd() )
1502 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1503 urlit != (*it).baseUrlsEnd();
1506 if ((*urlit).asString(urlview) == url.asString(urlview))
1511 info.setBaseUrl(url);
1512 ZYPP_THROW(RepoNotFoundException(info));
1515 ////////////////////////////////////////////////////////////////////////////
1519 ////////////////////////////////////////////////////////////////////////////
1521 bool RepoManager::serviceEmpty() const
1522 { return _pimpl->services.empty(); }
1524 RepoManager::ServiceSizeType RepoManager::serviceSize() const
1525 { return _pimpl->services.size(); }
1527 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
1528 { return _pimpl->services.begin(); }
1530 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
1531 { return _pimpl->services.end(); }
1533 ServiceInfo RepoManager::getService( const std::string & alias ) const
1535 for_( it, serviceBegin(), serviceEnd() )
1536 if ( it->alias() == alias )
1538 return ServiceInfo::noService;
1541 bool RepoManager::hasService( const std::string & alias ) const
1543 for_( it, serviceBegin(), serviceEnd() )
1544 if ( it->alias() == alias )
1549 ////////////////////////////////////////////////////////////////////////////
1551 void RepoManager::addService( const std::string & alias, const Url & url )
1553 addService( ServiceInfo(alias, url) );
1556 void RepoManager::addService( const ServiceInfo & service )
1558 assert_alias( service );
1560 // check if service already exists
1561 if ( hasService( service.alias() ) )
1562 ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1564 // Writable ServiceInfo is needed to save the location
1565 // of the .service file. Finaly insert into the service list.
1566 ServiceInfo toSave( service );
1567 _pimpl->saveService( toSave );
1568 _pimpl->services.insert( toSave );
1570 // check for credentials in Url (username:password, not ?credentials param)
1571 if ( toSave.url().hasCredentialsInAuthority() )
1573 media::CredentialManager cm(
1574 media::CredManagerOptions(_pimpl->options.rootDir) );
1576 //! \todo use a method calling UI callbacks to ask where to save creds?
1577 cm.saveInUser(media::AuthData(toSave.url()));
1580 MIL << "added service " << toSave.alias() << endl;
1583 ////////////////////////////////////////////////////////////////////////////
1585 void RepoManager::removeService( const std::string & alias )
1587 MIL << "Going to delete repo " << alias << endl;
1589 const ServiceInfo & service = getService( alias );
1591 Pathname location = service.filepath();
1592 if( location.empty() )
1594 ZYPP_THROW(RepoException("Can't figure where the service is stored"));
1598 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1600 // only one service definition in the file
1601 if ( tmpSet.size() == 1 )
1603 if ( filesystem::unlink(location) != 0 )
1605 ZYPP_THROW(RepoException("Can't delete " + location.asString()));
1607 MIL << alias << " sucessfully deleted." << endl;
1611 filesystem::assert_dir(location.dirname());
1613 std::ofstream file(location.c_str());
1615 ZYPP_THROW(Exception("failed open file to write"));
1617 for_(it, tmpSet.begin(), tmpSet.end())
1619 if( it->alias() != alias )
1620 it->dumpAsIniOn(file);
1623 MIL << alias << " sucessfully deleted from file " << location << endl;
1626 // now remove all repositories added by this service
1627 RepoCollector rcollector;
1628 getRepositoriesInService( alias,
1629 boost::make_function_output_iterator(
1630 bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1631 // cannot do this directly in getRepositoriesInService - would invalidate iterators
1632 for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1633 removeRepository(*rit);
1636 void RepoManager::removeService( const ServiceInfo & service )
1637 { removeService(service.alias()); }
1639 ////////////////////////////////////////////////////////////////////////////
1641 void RepoManager::refreshServices()
1643 // copy the set of services since refreshService
1644 // can eventually invalidate the iterator
1645 ServiceSet services( serviceBegin(), serviceEnd() );
1646 for_( it, services.begin(), services.end() )
1648 if ( !it->enabled() )
1651 refreshService(*it);
1655 void RepoManager::refreshService( const ServiceInfo & service )
1656 { refreshService( service.alias() ); }
1658 void RepoManager::refreshService( const std::string & alias )
1660 ServiceInfo service( getService( alias ) );
1661 assert_alias( service );
1662 assert_url( service );
1663 // NOTE: It might be necessary to modify and rewrite the service info.
1664 // Either when probing the type, or when adjusting the repositories
1665 // enable/disable state.:
1666 bool serviceModified = false;
1667 MIL << "going to refresh service '" << service.alias() << "', url: "<< service.url() << endl;
1669 //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
1671 // if the type is unknown, try probing.
1672 if ( service.type() == repo::ServiceType::NONE )
1674 repo::ServiceType type = probeService( service.url() );
1675 if ( type != ServiceType::NONE )
1677 service.setProbedType( type ); // lazy init!
1678 serviceModified = true;
1682 // download the repo index file
1683 media::MediaManager mediamanager;
1684 media::MediaAccessId mid = mediamanager.open( service.url() );
1685 mediamanager.attachDesiredMedia( mid );
1686 mediamanager.provideFile( mid, "repo/repoindex.xml" );
1687 Pathname path = mediamanager.localPath(mid, "repo/repoindex.xml" );
1689 // get target distro identifier
1690 std::string servicesTargetDistro = _pimpl->options.servicesTargetDistro;
1691 if ( servicesTargetDistro.empty() && getZYpp()->getTarget() )
1692 servicesTargetDistro = getZYpp()->target()->targetDistribution();
1693 DBG << "servicesTargetDistro: " << servicesTargetDistro << endl;
1696 RepoCollector collector(servicesTargetDistro);
1697 parser::RepoindexFileReader reader( path, bind( &RepoCollector::collect, &collector, _1 ) );
1698 mediamanager.release( mid );
1699 mediamanager.close( mid );
1702 // set service alias and base url for all collected repositories
1703 for_( it, collector.repos.begin(), collector.repos.end() )
1705 // if the repo url was not set by the repoindex parser, set service's url
1708 if ( it->baseUrlsEmpty() )
1709 url = service.url();
1712 // service repo can contain only one URL now, so no need to iterate.
1713 url = *it->baseUrlsBegin();
1716 // libzypp currently has problem with separate url + path handling
1717 // so just append the path to the baseurl
1718 if ( !it->path().empty() )
1720 Pathname path(url.getPathName());
1722 url.setPathName( path.asString() );
1726 // Prepend service alias:
1727 it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
1730 it->setBaseUrl( url );
1731 // set refrence to the parent service
1732 it->setService( service.alias() );
1735 ////////////////////////////////////////////////////////////////////////////
1736 // Now compare collected repos with the ones in the system...
1738 RepoInfoList oldRepos;
1739 getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
1741 // find old repositories to remove...
1742 for_( it, oldRepos.begin(), oldRepos.end() )
1744 if ( ! foundAliasIn( it->alias(), collector.repos ) )
1746 removeRepository( *it );
1750 ////////////////////////////////////////////////////////////////////////////
1751 // create missing repositories and modify exising ones if needed...
1752 for_( it, collector.repos.begin(), collector.repos.end() )
1754 // Service explicitly requests the repo being enabled?
1755 // Service explicitly requests the repo being disabled?
1756 // And hopefully not both ;) If so, enable wins.
1757 bool beEnabled = service.repoToEnableFind( it->alias() );
1758 bool beDisabled = service.repoToDisableFind( it->alias() );
1762 // Remove from enable request list.
1763 // NOTE: repoToDisable is handled differently.
1764 // It gets cleared on each refresh.
1765 service.delRepoToEnable( it->alias() );
1766 serviceModified = true;
1769 RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
1770 if ( oldRepo == oldRepos.end() )
1772 // Not found in oldRepos ==> a new repo to add
1774 // Make sure the service repo is created with the
1775 // appropriate enable and autorefresh true.
1776 it->setEnabled( beEnabled );
1777 it->setAutorefresh( true );
1779 // At that point check whether a repo with the same alias
1780 // exists outside this service. Maybe forcefully re-alias
1781 // the existing repo?
1782 addRepository( *it );
1784 // save repo credentials
1785 // ma@: task for modifyRepository?
1789 // ==> an exising repo to check
1790 bool oldRepoModified = false;
1794 if ( ! oldRepo->enabled() )
1796 oldRepo->setEnabled( true );
1797 oldRepoModified = true;
1800 else if ( beDisabled )
1802 if ( oldRepo->enabled() )
1804 oldRepo->setEnabled( false );
1805 oldRepoModified = true;
1809 #warning also check changed URL due to PATH/URL change in service, but ignore ?credentials param!
1810 // ma@: task for modifyRepository?
1812 // save if modified:
1813 if ( oldRepoModified )
1815 modifyRepository( oldRepo->alias(), *oldRepo );
1820 // Unlike reposToEnable, reposToDisable is always cleared after refresh.
1821 if ( ! service.reposToDisableEmpty() )
1823 service.clearReposToDisable();
1824 serviceModified = true;
1827 ////////////////////////////////////////////////////////////////////////////
1828 // save service if modified:
1829 if ( serviceModified )
1831 // write out modified service file.
1832 modifyService( service.alias(), service );
1836 ////////////////////////////////////////////////////////////////////////////
1838 void RepoManager::modifyService(const std::string & oldAlias, const ServiceInfo & service)
1840 MIL << "Going to modify service " << oldAlias << endl;
1842 const ServiceInfo & oldService = getService(oldAlias);
1844 Pathname location = oldService.filepath();
1845 if( location.empty() )
1847 ZYPP_THROW(RepoException(
1848 "Cannot figure out where the service file is stored."));
1851 // remember: there may multiple services being defined in one file:
1853 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1855 filesystem::assert_dir(location.dirname());
1856 std::ofstream file(location.c_str());
1857 for_(it, tmpSet.begin(), tmpSet.end())
1859 if( *it != oldAlias )
1860 it->dumpAsIniOn(file);
1862 service.dumpAsIniOn(file);
1865 _pimpl->services.erase(oldAlias);
1866 _pimpl->services.insert(service);
1868 // changed properties affecting also repositories
1869 if( oldAlias != service.alias() // changed alias
1870 || oldService.enabled() != service.enabled() // changed enabled status
1873 std::vector<RepoInfo> toModify;
1874 getRepositoriesInService(oldAlias, std::back_inserter(toModify));
1875 for_( it, toModify.begin(), toModify.end() )
1877 if (oldService.enabled() && !service.enabled())
1878 it->setEnabled(false);
1879 else if (!oldService.enabled() && service.enabled())
1881 //! \todo do nothing? the repos will be enabled on service refresh
1882 //! \todo how to know the service needs a (auto) refresh????
1885 it->setService(service.alias());
1886 modifyRepository(it->alias(), *it);
1890 //! \todo refresh the service automatically if url is changed?
1893 ////////////////////////////////////////////////////////////////////////////
1895 repo::ServiceType RepoManager::probeService( const Url &url ) const
1899 MediaSetAccess access(url);
1900 if ( access.doesFileExist("/repo/repoindex.xml") )
1901 return repo::ServiceType::RIS;
1903 catch ( const media::MediaException &e )
1906 RepoException enew("Error trying to read from " + url.asString());
1910 catch ( const Exception &e )
1913 Exception enew("Unknown error reading from " + url.asString());
1918 return repo::ServiceType::NONE;
1921 ////////////////////////////////////////////////////////////////////////////
1923 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1925 return str << *obj._pimpl;
1928 /////////////////////////////////////////////////////////////////
1930 ///////////////////////////////////////////////////////////////////