1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
21 #include "zypp/base/InputStream.h"
22 #include "zypp/base/LogTools.h"
23 #include "zypp/base/Gettext.h"
24 #include "zypp/base/Function.h"
25 #include "zypp/base/Regex.h"
26 #include "zypp/PathInfo.h"
27 #include "zypp/TmpPath.h"
29 #include "zypp/ServiceInfo.h"
30 #include "zypp/repo/RepoException.h"
31 #include "zypp/RepoManager.h"
33 #include "zypp/media/MediaManager.h"
34 #include "zypp/media/CredentialManager.h"
35 #include "zypp/MediaSetAccess.h"
36 #include "zypp/ExternalProgram.h"
37 #include "zypp/ManagedFile.h"
39 #include "zypp/parser/RepoFileReader.h"
40 #include "zypp/parser/ServiceFileReader.h"
41 #include "zypp/repo/ServiceRepos.h"
42 #include "zypp/repo/yum/Downloader.h"
43 #include "zypp/repo/susetags/Downloader.h"
44 #include "zypp/parser/plaindir/RepoParser.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 /** Simple media mounter to access non-downloading URLs e.g. for non-local plaindir repos.
73 /** Ctor provides media access. */
74 MediaMounter( const Url & url_r )
76 media::MediaManager mediamanager;
77 _mid = mediamanager.open( url_r );
78 mediamanager.attach( _mid );
81 /** Ctor releases the media. */
84 media::MediaManager mediamanager;
85 mediamanager.release( _mid );
86 mediamanager.close( _mid );
89 /** Convert a path relative to the media into an absolute path.
91 * Called without argument it returns the path to the medias root directory.
93 Pathname getPathName( const Pathname & path_r = Pathname() ) const
95 media::MediaManager mediamanager;
96 return mediamanager.localPath( _mid, path_r );
100 media::MediaAccessId _mid;
102 ///////////////////////////////////////////////////////////////////
104 /** Check if alias_r is present in repo/service container. */
105 template <class Iterator>
106 inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
108 for_( it, begin_r, end_r )
109 if ( it->alias() == alias_r )
114 template <class Container>
115 inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
116 { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
118 /** Find alias_r in repo/service container. */
119 template <class Iterator>
120 inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
122 for_( it, begin_r, end_r )
123 if ( it->alias() == alias_r )
128 template <class Container>
129 inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
130 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
132 template <class Container>
133 inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
134 { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
137 /** \short Generate a related filename from a repo/service infos alias */
138 inline std::string filenameFromAlias( const std::string & alias_r, const std::string & stem_r )
140 std::string filename( alias_r );
141 // replace slashes with underscores
142 str::replaceAll( filename, "/", "_" );
144 filename = Pathname(filename).extend("."+stem_r).asString();
145 MIL << "generating filename for " << stem_r << " [" << alias_r << "] : '" << filename << "'" << endl;
150 * \short Simple callback to collect the results
152 * Classes like RepoFileParser call the callback
153 * once per each repo in a file.
155 * Passing this functor as callback, you can collect
156 * all results at the end, without dealing with async
159 * If targetDistro is set, all repos with non-empty RepoInfo::targetDistribution()
162 * \todo do this through a separate filter
164 struct RepoCollector : private base::NonCopyable
169 RepoCollector(const std::string & targetDistro_)
170 : targetDistro(targetDistro_)
173 bool collect( const RepoInfo &repo )
175 // skip repositories meant for other distros than specified
176 if (!targetDistro.empty()
177 && !repo.targetDistribution().empty()
178 && repo.targetDistribution() != targetDistro)
181 << "Skipping repository meant for '" << targetDistro
182 << "' distribution (current distro is '"
183 << repo.targetDistribution() << "')." << endl;
188 repos.push_back(repo);
193 std::string targetDistro;
195 ////////////////////////////////////////////////////////////////////////////
198 * Reads RepoInfo's from a repo file.
200 * \param file pathname of the file to read.
202 std::list<RepoInfo> repositories_in_file( const Pathname & file )
204 MIL << "repo file: " << file << endl;
205 RepoCollector collector;
206 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
207 return collector.repos;
210 ////////////////////////////////////////////////////////////////////////////
213 * \short List of RepoInfo's from a directory
215 * Goes trough every file ending with ".repo" in a directory and adds all
216 * RepoInfo's contained in that file.
218 * \param dir pathname of the directory to read.
220 std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
222 MIL << "directory " << dir << endl;
223 std::list<RepoInfo> repos;
224 std::list<Pathname> entries;
225 if ( filesystem::readdir( entries, dir, false ) != 0 )
227 // TranslatorExplanation '%s' is a pathname
228 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
231 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
232 for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
234 if (str::regex_match(it->extension(), allowedRepoExt))
236 std::list<RepoInfo> tmp = repositories_in_file( *it );
237 repos.insert( repos.end(), tmp.begin(), tmp.end() );
239 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
240 //MIL << "ok" << endl;
246 ////////////////////////////////////////////////////////////////////////////
248 inline void assert_alias( const RepoInfo & info )
250 if ( info.alias().empty() )
251 ZYPP_THROW( RepoNoAliasException() );
252 // bnc #473834. Maybe we can match the alias against a regex to define
253 // and check for valid aliases
254 if ( info.alias()[0] == '.')
255 ZYPP_THROW(RepoInvalidAliasException(
256 info, _("Repository alias cannot start with dot.")));
259 inline void assert_alias( const ServiceInfo & info )
261 if ( info.alias().empty() )
262 ZYPP_THROW( ServiceNoAliasException() );
263 // bnc #473834. Maybe we can match the alias against a regex to define
264 // and check for valid aliases
265 if ( info.alias()[0] == '.')
266 ZYPP_THROW(ServiceInvalidAliasException(
267 info, _("Service alias cannot start with dot.")));
270 ////////////////////////////////////////////////////////////////////////////
272 inline void assert_urls( const RepoInfo & info )
274 if ( info.baseUrlsEmpty() )
275 ZYPP_THROW( RepoNoUrlException( info ) );
278 inline void assert_url( const ServiceInfo & info )
280 if ( ! info.url().isValid() )
281 ZYPP_THROW( ServiceNoUrlException( info ) );
284 ////////////////////////////////////////////////////////////////////////////
287 * \short Calculates the raw cache path for a repository, this is usually
288 * /var/cache/zypp/alias
290 inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
293 return opt.repoRawCachePath / info.escaped_alias();
297 * \short Calculates the raw product metadata path for a repository, this is
298 * inside the raw cache dir, plus an optional path where the metadata is.
300 * It should be different only for repositories that are not in the root of
302 * for example /var/cache/zypp/alias/addondir
304 inline Pathname rawproductdata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
307 return opt.repoRawCachePath / info.escaped_alias() / info.path();
311 * \short Calculates the packages cache path for a repository
313 inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
316 return opt.repoPackagesCachePath / info.escaped_alias();
320 * \short Calculates the solv cache path for a repository
322 inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
325 return opt.repoSolvCachePath / info.escaped_alias();
328 ////////////////////////////////////////////////////////////////////////////
330 /** Functor collecting ServiceInfos into a ServiceSet. */
331 class ServiceCollector
334 typedef std::set<ServiceInfo> ServiceSet;
336 ServiceCollector( ServiceSet & services_r )
337 : _services( services_r )
340 bool operator()( const ServiceInfo & service_r ) const
342 _services.insert( service_r );
347 ServiceSet & _services;
349 ////////////////////////////////////////////////////////////////////////////
352 ///////////////////////////////////////////////////////////////////
354 std::list<RepoInfo> readRepoFile( const Url & repo_file )
356 // no interface to download a specific file, using workaround:
357 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
359 Pathname path(url.getPathName());
360 url.setPathName ("/");
361 MediaSetAccess access(url);
362 Pathname local = access.provideFile(path);
364 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
366 return repositories_in_file(local);
369 ///////////////////////////////////////////////////////////////////
371 // class RepoManagerOptions
373 ////////////////////////////////////////////////////////////////////
375 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
377 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
378 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
379 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
380 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
381 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
382 knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
383 pluginsPath = Pathname::assertprefix( root_r, ZConfig::instance().pluginsPath() );
384 probe = ZConfig::instance().repo_add_probe();
389 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
391 RepoManagerOptions ret;
392 ret.repoCachePath = root_r;
393 ret.repoRawCachePath = root_r/"raw";
394 ret.repoSolvCachePath = root_r/"solv";
395 ret.repoPackagesCachePath = root_r/"packages";
396 ret.knownReposPath = root_r/"repos.d";
397 ret.knownServicesPath = root_r/"services.d";
398 ret.pluginsPath = root_r/"plugins";
399 ret.rootDir = root_r;
403 ///////////////////////////////////////////////////////////////////
404 /// \class RepoManager::Impl
405 /// \brief RepoManager implementation.
407 ///////////////////////////////////////////////////////////////////
408 struct RepoManager::Impl
411 Impl( const RepoManagerOptions &opt )
414 init_knownServices();
415 init_knownRepositories();
419 bool repoEmpty() const { return _repos.empty(); }
420 RepoSizeType repoSize() const { return _repos.size(); }
421 RepoConstIterator repoBegin() const { return _repos.begin(); }
422 RepoConstIterator repoEnd() const { return _repos.end(); }
424 bool hasRepo( const std::string & alias ) const
425 { return foundAliasIn( alias, _repos ); }
427 RepoInfo getRepo( const std::string & alias ) const
429 RepoConstIterator it( findAlias( alias, _repos ) );
430 return it == _repos.end() ? RepoInfo::noRepo : *it;
434 Pathname metadataPath( const RepoInfo & info ) const
435 { return rawcache_path_for_repoinfo( _options, info ); }
437 Pathname packagesPath( const RepoInfo & info ) const
438 { return packagescache_path_for_repoinfo( _options, info ); }
440 RepoStatus metadataStatus( const RepoInfo & info ) const;
442 RefreshCheckStatus checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy );
444 void refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, OPT_PROGRESS );
446 void cleanMetadata( const RepoInfo & info, OPT_PROGRESS );
448 void cleanPackages( const RepoInfo & info, OPT_PROGRESS );
450 void buildCache( const RepoInfo & info, CacheBuildPolicy policy, OPT_PROGRESS );
452 repo::RepoType probe( const Url & url, const Pathname & path = Pathname() ) const;
454 void cleanCacheDirGarbage( OPT_PROGRESS );
456 void cleanCache( const RepoInfo & info, OPT_PROGRESS );
458 bool isCached( const RepoInfo & info ) const
459 { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
461 RepoStatus cacheStatus( const RepoInfo & info ) const
462 { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
464 void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
466 void addRepository( const RepoInfo & info, OPT_PROGRESS );
468 void addRepositories( const Url & url, OPT_PROGRESS );
470 void removeRepository( const RepoInfo & info, OPT_PROGRESS );
472 void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
474 RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
475 RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
478 bool serviceEmpty() const { return _services.empty(); }
479 ServiceSizeType serviceSize() const { return _services.size(); }
480 ServiceConstIterator serviceBegin() const { return _services.begin(); }
481 ServiceConstIterator serviceEnd() const { return _services.end(); }
483 bool hasService( const std::string & alias ) const
484 { return foundAliasIn( alias, _services ); }
486 ServiceInfo getService( const std::string & alias ) const
488 ServiceConstIterator it( findAlias( alias, _services ) );
489 return it == _services.end() ? ServiceInfo::noService : *it;
493 void addService( const ServiceInfo & service );
494 void addService( const std::string & alias, const Url & url )
495 { addService( ServiceInfo( alias, url ) ); }
497 void removeService( const std::string & alias );
498 void removeService( const ServiceInfo & service )
499 { removeService( service.alias() ); }
501 void refreshServices();
503 void refreshService( const std::string & alias );
504 void refreshService( const ServiceInfo & service )
505 { refreshService( service.alias() ); }
507 void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
509 repo::ServiceType probeService( const Url & url ) const;
512 void saveService( ServiceInfo & service ) const;
514 Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
516 std::string generateFilename( const RepoInfo & info ) const
517 { return filenameFromAlias( info.alias(), "repo" ); }
519 std::string generateFilename( const ServiceInfo & info ) const
520 { return filenameFromAlias( info.alias(), "service" ); }
522 void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
524 Pathname base = solv_path_for_repoinfo( _options, info );
525 filesystem::assert_dir(base);
526 status.saveToCookieFile( base / "cookie" );
529 void touchIndexFile( const RepoInfo & info );
531 template<typename OutputIterator>
532 void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
534 MatchServiceAlias filter( alias );
535 std::copy( boost::make_filter_iterator( filter, _repos.begin(), _repos.end() ),
536 boost::make_filter_iterator( filter, _repos.end(), _repos.end() ),
541 void init_knownServices();
542 void init_knownRepositories();
545 RepoManagerOptions _options;
547 ServiceSet _services;
550 friend Impl * rwcowClone<Impl>( const Impl * rhs );
551 /** clone for RWCOW_pointer */
553 { return new Impl( *this ); }
555 ///////////////////////////////////////////////////////////////////
557 /** \relates RepoManager::Impl Stream output */
558 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
559 { return str << "RepoManager::Impl"; }
561 ///////////////////////////////////////////////////////////////////
563 void RepoManager::Impl::saveService( ServiceInfo & service ) const
565 filesystem::assert_dir( _options.knownServicesPath );
566 Pathname servfile = generateNonExistingName( _options.knownServicesPath,
567 generateFilename( service ) );
568 service.setFilepath( servfile );
570 MIL << "saving service in " << servfile << endl;
572 std::ofstream file( servfile.c_str() );
575 // TranslatorExplanation '%s' is a filename
576 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
578 service.dumpAsIniOn( file );
579 MIL << "done" << endl;
583 * Generate a non existing filename in a directory, using a base
584 * name. For example if a directory contains 3 files
590 * If you try to generate a unique filename for this directory,
591 * based on "ruu" you will get "ruu", but if you use the base
592 * "foo" you will get "foo_1"
594 * \param dir Directory where the file needs to be unique
595 * \param basefilename string to base the filename on.
597 Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
598 const std::string & basefilename ) const
600 std::string final_filename = basefilename;
602 while ( PathInfo(dir + final_filename).isExist() )
604 final_filename = basefilename + "_" + str::numstring(counter);
607 return dir + Pathname(final_filename);
610 ////////////////////////////////////////////////////////////////////////////
612 void RepoManager::Impl::init_knownServices()
614 Pathname dir = _options.knownServicesPath;
615 std::list<Pathname> entries;
616 if (PathInfo(dir).isExist())
618 if ( filesystem::readdir( entries, dir, false ) != 0 )
620 // TranslatorExplanation '%s' is a pathname
621 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
624 //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
625 for_(it, entries.begin(), entries.end() )
627 parser::ServiceFileReader(*it, ServiceCollector(_services));
631 repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
634 void RepoManager::Impl::init_knownRepositories()
636 MIL << "start construct known repos" << endl;
638 if ( PathInfo(_options.knownReposPath).isExist() )
640 RepoInfoList repol = repositories_in_dir(_options.knownReposPath);
641 std::list<string> repo_esc_aliases;
642 std::list<string> entries;
643 for ( RepoInfoList::iterator it = repol.begin();
647 // set the metadata path for the repo
648 Pathname metadata_path = rawcache_path_for_repoinfo(_options, (*it));
649 (*it).setMetadataPath(metadata_path);
651 // set the downloaded packages path for the repo
652 Pathname packages_path = packagescache_path_for_repoinfo(_options, (*it));
653 (*it).setPackagesPath(packages_path);
656 repo_esc_aliases.push_back(it->escaped_alias());
659 // delete metadata folders without corresponding repo (e.g. old tmp directories)
660 if ( filesystem::readdir( entries, _options.repoRawCachePath, false ) == 0 )
662 std::set<string> oldfiles;
663 repo_esc_aliases.sort();
665 set_difference(entries.begin(), entries.end(), repo_esc_aliases.begin(), repo_esc_aliases.end(), std::inserter(oldfiles, oldfiles.end()));
666 for_(it, oldfiles.begin(), oldfiles.end())
668 filesystem::recursive_rmdir(_options.repoRawCachePath / *it);
673 MIL << "end construct known repos" << endl;
676 ///////////////////////////////////////////////////////////////////
678 RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
680 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
681 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
682 RepoType repokind = info.type();
685 switch ( repokind.toEnum() )
687 case RepoType::NONE_e:
688 // unknown, probe the local metadata
689 repokind = probe( productdatapath.asUrl() );
695 switch ( repokind.toEnum() )
697 case RepoType::RPMMD_e :
699 status = RepoStatus( productdatapath + "/repodata/repomd.xml");
703 case RepoType::YAST2_e :
705 status = RepoStatus( productdatapath + "/content") && (RepoStatus( mediarootpath + "/media.1/media"));
709 case RepoType::RPMPLAINDIR_e :
711 if ( PathInfo(Pathname(productdatapath + "/cookie")).isExist() )
712 status = RepoStatus( productdatapath + "/cookie");
716 case RepoType::NONE_e :
717 // Return default RepoStatus in case of RepoType::NONE
718 // indicating it should be created?
719 // ZYPP_THROW(RepoUnknownTypeException());
726 void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
728 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
730 RepoType repokind = info.type();
731 if ( repokind.toEnum() == RepoType::NONE_e )
732 // unknown, probe the local metadata
733 repokind = probe( productdatapath.asUrl() );
734 // if still unknown, just return
735 if (repokind == RepoType::NONE_e)
739 switch ( repokind.toEnum() )
741 case RepoType::RPMMD_e :
742 p = Pathname(productdatapath + "/repodata/repomd.xml");
745 case RepoType::YAST2_e :
746 p = Pathname(productdatapath + "/content");
749 case RepoType::RPMPLAINDIR_e :
750 p = Pathname(productdatapath + "/cookie");
753 case RepoType::NONE_e :
758 // touch the file, ignore error (they are logged anyway)
759 filesystem::touch(p);
763 RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
767 RepoStatus oldstatus;
768 RepoStatus newstatus;
772 MIL << "Going to try to check whether refresh is needed for " << url << endl;
774 // first check old (cached) metadata
775 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
776 filesystem::assert_dir(mediarootpath);
777 oldstatus = metadataStatus(info);
779 if ( oldstatus.empty() )
781 MIL << "No cached metadata, going to refresh" << endl;
782 return REFRESH_NEEDED;
786 std::string scheme( url.getScheme() );
787 if ( scheme == "cd" || scheme == "dvd" )
789 MIL << "never refresh CD/DVD" << endl;
790 return REPO_UP_TO_DATE;
794 // now we've got the old (cached) status, we can decide repo.refresh.delay
795 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
797 // difference in seconds
798 double diff = difftime(
799 (Date::ValueType)Date::now(),
800 (Date::ValueType)oldstatus.timestamp()) / 60;
802 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
803 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
804 DBG << "last refresh = " << diff << " minutes ago" << endl;
806 if ( diff < ZConfig::instance().repo_refresh_delay() )
810 WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
814 MIL << "Repository '" << info.alias()
815 << "' has been refreshed less than repo.refresh.delay ("
816 << ZConfig::instance().repo_refresh_delay()
817 << ") minutes ago. Advising to skip refresh" << endl;
818 return REPO_CHECK_DELAYED;
823 // To test the new matadta create temp dir as sibling of mediarootpath
824 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
826 repo::RepoType repokind = info.type();
827 // if the type is unknown, try probing.
828 switch ( repokind.toEnum() )
830 case RepoType::NONE_e:
831 // unknown, probe it \todo respect productdir
832 repokind = probe( url, info.path() );
838 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
839 ( repokind.toEnum() == RepoType::YAST2_e ) )
841 MediaSetAccess media(url);
842 shared_ptr<repo::Downloader> downloader_ptr;
844 if ( repokind.toEnum() == RepoType::RPMMD_e )
845 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
847 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath));
849 RepoStatus newstatus = downloader_ptr->status(media);
850 bool refresh = false;
851 if ( oldstatus.checksum() == newstatus.checksum() )
853 MIL << "repo has not changed" << endl;
854 if ( policy == RefreshForced )
856 MIL << "refresh set to forced" << endl;
862 MIL << "repo has changed, going to refresh" << endl;
867 touchIndexFile(info);
869 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
871 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
873 MediaMounter media( url );
874 RepoStatus newstatus = parser::plaindir::dirStatus( media.getPathName( info.path() ) );
875 bool refresh = false;
876 if ( oldstatus.checksum() == newstatus.checksum() )
878 MIL << "repo has not changed" << endl;
879 if ( policy == RefreshForced )
881 MIL << "refresh set to forced" << endl;
887 MIL << "repo has changed, going to refresh" << endl;
892 touchIndexFile(info);
894 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
898 ZYPP_THROW(RepoUnknownTypeException(info));
901 catch ( const Exception &e )
904 ERR << "refresh check failed for " << url << endl;
908 return REFRESH_NEEDED; // default
912 void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
917 // we will throw this later if no URL checks out fine
918 RepoException rexception(_PL("Valid metadata not found at specified URL",
919 "Valid metadata not found at specified URLs",
920 info.baseUrlsSize() ) );
922 // try urls one by one
923 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
929 // check whether to refresh metadata
930 // if the check fails for this url, it throws, so another url will be checked
931 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
934 MIL << "Going to refresh metadata from " << url << endl;
936 repo::RepoType repokind = info.type();
938 // if the type is unknown, try probing.
939 switch ( repokind.toEnum() )
941 case RepoType::NONE_e:
943 repokind = probe( *it, info.path() );
945 if (repokind.toEnum() != RepoType::NONE_e)
947 // Adjust the probed type in RepoInfo
948 info.setProbedType( repokind ); // lazy init!
949 //save probed type only for repos in system
950 for_( it, repoBegin(), repoEnd() )
952 if ( info.alias() == (*it).alias() )
954 RepoInfo modifiedrepo = info;
955 modifiedrepo.setType( repokind );
956 modifyRepository( info.alias(), modifiedrepo );
966 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
967 if( filesystem::assert_dir(mediarootpath) )
969 Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
973 // create temp dir as sibling of mediarootpath
974 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
975 if( tmpdir.path().empty() )
977 Exception ex(_("Can't create metadata cache directory."));
981 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
982 ( repokind.toEnum() == RepoType::YAST2_e ) )
984 MediaSetAccess media(url);
985 shared_ptr<repo::Downloader> downloader_ptr;
987 MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
989 if ( repokind.toEnum() == RepoType::RPMMD_e )
990 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
992 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
995 * Given a downloader, sets the other repos raw metadata
996 * path as cache paths for the fetcher, so if another
997 * repo has the same file, it will not download it
998 * but copy it from the other repository
1000 for_( it, repoBegin(), repoEnd() )
1002 Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1003 if ( PathInfo(cachepath).isExist() )
1004 downloader_ptr->addCachePath(cachepath);
1007 downloader_ptr->download( media, tmpdir.path() );
1009 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1011 MediaMounter media( url );
1012 RepoStatus newstatus = parser::plaindir::dirStatus( media.getPathName( info.path() ) );
1014 Pathname productpath( tmpdir.path() / info.path() );
1015 filesystem::assert_dir( productpath );
1016 std::ofstream file( (productpath/"cookie").c_str() );
1019 // TranslatorExplanation '%s' is a filename
1020 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), (productpath/"cookie").c_str() )));
1023 if ( ! info.path().empty() && info.path() != "/" )
1024 file << " (" << info.path() << ")";
1026 file << newstatus.checksum() << endl;
1032 ZYPP_THROW(RepoUnknownTypeException());
1035 // ok we have the metadata, now exchange
1037 filesystem::exchange( tmpdir.path(), mediarootpath );
1042 catch ( const Exception &e )
1045 ERR << "Trying another url..." << endl;
1047 // remember the exception caught for the *first URL*
1048 // if all other URLs fail, the rexception will be thrown with the
1049 // cause of the problem of the first URL remembered
1050 if (it == info.baseUrlsBegin())
1051 rexception.remember(e);
1054 ERR << "No more urls..." << endl;
1055 ZYPP_THROW(rexception);
1058 ////////////////////////////////////////////////////////////////////////////
1060 void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1062 ProgressData progress(100);
1063 progress.sendTo(progressfnc);
1065 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1070 void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1072 ProgressData progress(100);
1073 progress.sendTo(progressfnc);
1075 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1080 void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1083 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1084 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1086 if( filesystem::assert_dir(_options.repoCachePath) )
1088 Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1091 RepoStatus raw_metadata_status = metadataStatus(info);
1092 if ( raw_metadata_status.empty() )
1094 /* if there is no cache at this point, we refresh the raw
1095 in case this is the first time - if it's !autorefresh,
1096 we may still refresh */
1097 refreshMetadata(info, RefreshIfNeeded, progressrcv );
1098 raw_metadata_status = metadataStatus(info);
1101 bool needs_cleaning = false;
1102 if ( isCached( info ) )
1104 MIL << info.alias() << " is already cached." << endl;
1105 RepoStatus cache_status = cacheStatus(info);
1107 if ( cache_status.checksum() == raw_metadata_status.checksum() )
1109 MIL << info.alias() << " cache is up to date with metadata." << endl;
1110 if ( policy == BuildIfNeeded ) {
1114 MIL << info.alias() << " cache rebuild is forced" << endl;
1118 needs_cleaning = true;
1121 ProgressData progress(100);
1122 callback::SendReport<ProgressReport> report;
1123 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1124 progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1132 MIL << info.alias() << " building cache..." << info.type() << endl;
1134 Pathname base = solv_path_for_repoinfo( _options, info);
1136 if( filesystem::assert_dir(base) )
1138 Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1142 if( ! PathInfo(base).userMayW() )
1144 Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1147 Pathname solvfile = base / "solv";
1150 repo::RepoType repokind = info.type();
1152 // if the type is unknown, try probing.
1153 switch ( repokind.toEnum() )
1155 case RepoType::NONE_e:
1156 // unknown, probe the local metadata
1157 repokind = probe( productdatapath.asUrl() );
1163 MIL << "repo type is " << repokind << endl;
1165 switch ( repokind.toEnum() )
1167 case RepoType::RPMMD_e :
1168 case RepoType::YAST2_e :
1169 case RepoType::RPMPLAINDIR_e :
1171 // Take care we unlink the solvfile on exception
1172 ManagedFile guard( solvfile, filesystem::unlink );
1173 scoped_ptr<MediaMounter> forPlainDirs;
1175 ExternalProgram::Arguments cmd;
1176 cmd.push_back( "repo2solv.sh" );
1178 // repo2solv expects -o as 1st arg!
1179 cmd.push_back( "-o" );
1180 cmd.push_back( solvfile.asString() );
1182 if ( repokind == RepoType::RPMPLAINDIR )
1184 forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1185 // recusive for plaindir as 2nd arg!
1186 cmd.push_back( "-R" );
1187 // FIXME this does only work form dir: URLs
1188 cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1191 cmd.push_back( productdatapath.asString() );
1193 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1194 std::string errdetail;
1196 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1197 WAR << " " << output;
1198 if ( errdetail.empty() ) {
1199 errdetail = prog.command();
1202 errdetail += output;
1205 int ret = prog.close();
1208 RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1209 ex.remember( errdetail );
1214 guard.resetDispose();
1218 ZYPP_THROW(RepoUnknownTypeException( _("Unhandled repository type") ));
1221 // update timestamp and checksum
1222 setCacheStatus(info, raw_metadata_status);
1223 MIL << "Commit cache.." << endl;
1227 ////////////////////////////////////////////////////////////////////////////
1229 repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1231 MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1233 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1235 // Handle non existing local directory in advance, as
1236 // MediaSetAccess does not support it.
1237 MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1238 return repo::RepoType::NONE;
1241 // prepare exception to be thrown if the type could not be determined
1242 // due to a media exception. We can't throw right away, because of some
1243 // problems with proxy servers returning an incorrect error
1244 // on ftp file-not-found(bnc #335906). Instead we'll check another types
1247 // TranslatorExplanation '%s' is an URL
1248 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1249 bool gotMediaException = false;
1252 MediaSetAccess access(url);
1255 if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1257 MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1258 return repo::RepoType::RPMMD;
1261 catch ( const media::MediaException &e )
1264 DBG << "problem checking for repodata/repomd.xml file" << endl;
1266 gotMediaException = true;
1271 if ( access.doesFileExist(path/"/content") )
1273 MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1274 return repo::RepoType::YAST2;
1277 catch ( const media::MediaException &e )
1280 DBG << "problem checking for content file" << endl;
1282 gotMediaException = true;
1285 // if it is a non-downloading URL denoting a directory
1286 if ( ! url.schemeIsDownloading() )
1288 MediaMounter media( url );
1289 if ( PathInfo(media.getPathName()/path).isDir() )
1291 // allow empty dirs for now
1292 MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1293 return repo::RepoType::RPMPLAINDIR;
1297 catch ( const Exception &e )
1300 // TranslatorExplanation '%s' is an URL
1301 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1306 if (gotMediaException)
1309 MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1310 return repo::RepoType::NONE;
1313 ////////////////////////////////////////////////////////////////////////////
1315 void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1317 MIL << "Going to clean up garbage in cache dirs" << endl;
1319 ProgressData progress(300);
1320 progress.sendTo(progressrcv);
1323 std::list<Pathname> cachedirs;
1324 cachedirs.push_back(_options.repoRawCachePath);
1325 cachedirs.push_back(_options.repoPackagesCachePath);
1326 cachedirs.push_back(_options.repoSolvCachePath);
1328 for_( dir, cachedirs.begin(), cachedirs.end() )
1330 if ( PathInfo(*dir).isExist() )
1332 std::list<Pathname> entries;
1333 if ( filesystem::readdir( entries, *dir, false ) != 0 )
1334 // TranslatorExplanation '%s' is a pathname
1335 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1337 unsigned sdircount = entries.size();
1338 unsigned sdircurrent = 1;
1339 for_( subdir, entries.begin(), entries.end() )
1341 // if it does not belong known repo, make it disappear
1343 for_( r, repoBegin(), repoEnd() )
1344 if ( subdir->basename() == r->escaped_alias() )
1345 { found = true; break; }
1348 filesystem::recursive_rmdir( *subdir );
1350 progress.set( progress.val() + sdircurrent * 100 / sdircount );
1355 progress.set( progress.val() + 100 );
1360 ////////////////////////////////////////////////////////////////////////////
1362 void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1364 ProgressData progress(100);
1365 progress.sendTo(progressrcv);
1368 MIL << "Removing raw metadata cache for " << info.alias() << endl;
1369 filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1374 ////////////////////////////////////////////////////////////////////////////
1376 void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1379 Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1381 if ( ! PathInfo(solvfile).isExist() )
1382 ZYPP_THROW(RepoNotCachedException(info));
1384 sat::Pool::instance().reposErase( info.alias() );
1387 Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1388 // test toolversion in order to rebuild solv file in case
1389 // it was written by an old libsolv-tool parser.
1391 // Known version strings used:
1395 sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1396 if ( toolversion.begin().asString().empty() )
1398 repo.eraseFromPool();
1399 ZYPP_THROW(Exception("Solv-file was created by old parser."));
1401 // else: up-to-date (or even newer).
1403 catch ( const Exception & exp )
1406 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1407 cleanCache( info, progressrcv );
1408 buildCache( info, BuildIfNeeded, progressrcv );
1410 sat::Pool::instance().addRepoSolv( solvfile, info );
1414 ////////////////////////////////////////////////////////////////////////////
1416 void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1420 ProgressData progress(100);
1421 callback::SendReport<ProgressReport> report;
1422 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1423 progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1426 MIL << "Try adding repo " << info << endl;
1428 RepoInfo tosave = info;
1429 if ( _repos.find(tosave) != _repos.end() )
1430 ZYPP_THROW(RepoAlreadyExistsException(info));
1432 // check the first url for now
1433 if ( _options.probe )
1435 DBG << "unknown repository type, probing" << endl;
1437 RepoType probedtype;
1438 probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1439 if ( tosave.baseUrlsSize() > 0 )
1441 if ( probedtype == RepoType::NONE )
1442 ZYPP_THROW(RepoUnknownTypeException());
1444 tosave.setType(probedtype);
1450 // assert the directory exists
1451 filesystem::assert_dir(_options.knownReposPath);
1453 Pathname repofile = generateNonExistingName(
1454 _options.knownReposPath, generateFilename(tosave));
1455 // now we have a filename that does not exists
1456 MIL << "Saving repo in " << repofile << endl;
1458 std::ofstream file(repofile.c_str());
1461 // TranslatorExplanation '%s' is a filename
1462 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1465 tosave.dumpAsIniOn(file);
1466 tosave.setFilepath(repofile);
1467 tosave.setMetadataPath( metadataPath( tosave ) );
1468 tosave.setPackagesPath( packagesPath( tosave ) );
1470 // We chould fix the API as we must injet those paths
1471 // into the repoinfo in order to keep it usable.
1472 RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1473 oinfo.setMetadataPath( metadataPath( tosave ) );
1474 oinfo.setPackagesPath( packagesPath( tosave ) );
1476 _repos.insert(tosave);
1480 // check for credentials in Urls
1481 bool havePasswords = false;
1482 for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1483 if ( urlit->hasCredentialsInAuthority() )
1485 havePasswords = true;
1488 // save the credentials
1489 if ( havePasswords )
1491 media::CredentialManager cm(
1492 media::CredManagerOptions(_options.rootDir) );
1494 for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1495 if (urlit->hasCredentialsInAuthority())
1496 //! \todo use a method calling UI callbacks to ask where to save creds?
1497 cm.saveInUser(media::AuthData(*urlit));
1500 HistoryLog().addRepository(tosave);
1503 MIL << "done" << endl;
1507 void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1509 std::list<RepoInfo> repos = readRepoFile(url);
1510 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1514 // look if the alias is in the known repos.
1515 for_ ( kit, repoBegin(), repoEnd() )
1517 if ( (*it).alias() == (*kit).alias() )
1519 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1520 ZYPP_THROW(RepoAlreadyExistsException(*it));
1525 std::string filename = Pathname(url.getPathName()).basename();
1527 if ( filename == Pathname() )
1529 // TranslatorExplanation '%s' is an URL
1530 ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1533 // assert the directory exists
1534 filesystem::assert_dir(_options.knownReposPath);
1536 Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1537 // now we have a filename that does not exists
1538 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1540 std::ofstream file(repofile.c_str());
1543 // TranslatorExplanation '%s' is a filename
1544 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1547 for ( std::list<RepoInfo>::iterator it = repos.begin();
1551 MIL << "Saving " << (*it).alias() << endl;
1552 it->setFilepath(repofile.asString());
1553 it->dumpAsIniOn(file);
1556 HistoryLog(_options.rootDir).addRepository(*it);
1559 MIL << "done" << endl;
1562 ////////////////////////////////////////////////////////////////////////////
1564 void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1566 ProgressData progress;
1567 callback::SendReport<ProgressReport> report;
1568 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1569 progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1571 MIL << "Going to delete repo " << info.alias() << endl;
1573 for_( it, repoBegin(), repoEnd() )
1575 // they can be the same only if the provided is empty, that means
1576 // the provided repo has no alias
1578 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1581 // TODO match by url
1583 // we have a matcing repository, now we need to know
1584 // where it does come from.
1585 RepoInfo todelete = *it;
1586 if (todelete.filepath().empty())
1588 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1592 // figure how many repos are there in the file:
1593 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1594 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1596 // easy, only this one, just delete the file
1597 if ( filesystem::unlink(todelete.filepath()) != 0 )
1599 // TranslatorExplanation '%s' is a filename
1600 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1602 MIL << todelete.alias() << " sucessfully deleted." << endl;
1606 // there are more repos in the same file
1607 // write them back except the deleted one.
1609 //std::ofstream file(tmp.path().c_str());
1611 // assert the directory exists
1612 filesystem::assert_dir(todelete.filepath().dirname());
1614 std::ofstream file(todelete.filepath().c_str());
1617 // TranslatorExplanation '%s' is a filename
1618 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1620 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1621 fit != filerepos.end();
1624 if ( (*fit).alias() != todelete.alias() )
1625 (*fit).dumpAsIniOn(file);
1629 CombinedProgressData cSubprogrcv(progress, 20);
1630 CombinedProgressData mSubprogrcv(progress, 40);
1631 CombinedProgressData pSubprogrcv(progress, 40);
1632 // now delete it from cache
1633 if ( isCached(todelete) )
1634 cleanCache( todelete, cSubprogrcv);
1635 // now delete metadata (#301037)
1636 cleanMetadata( todelete, mSubprogrcv );
1637 cleanPackages( todelete, pSubprogrcv );
1638 _repos.erase(todelete);
1639 MIL << todelete.alias() << " sucessfully deleted." << endl;
1640 HistoryLog(_options.rootDir).removeRepository(todelete);
1642 } // else filepath is empty
1645 // should not be reached on a sucess workflow
1646 ZYPP_THROW(RepoNotFoundException(info));
1649 ////////////////////////////////////////////////////////////////////////////
1651 void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1653 RepoInfo toedit = getRepositoryInfo(alias);
1654 RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1656 // check if the new alias already exists when renaming the repo
1657 if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1659 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1662 if (toedit.filepath().empty())
1664 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1668 // figure how many repos are there in the file:
1669 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1671 // there are more repos in the same file
1672 // write them back except the deleted one.
1674 //std::ofstream file(tmp.path().c_str());
1676 // assert the directory exists
1677 filesystem::assert_dir(toedit.filepath().dirname());
1679 std::ofstream file(toedit.filepath().c_str());
1682 // TranslatorExplanation '%s' is a filename
1683 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1685 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1686 fit != filerepos.end();
1689 // if the alias is different, dump the original
1690 // if it is the same, dump the provided one
1691 if ( (*fit).alias() != toedit.alias() )
1692 (*fit).dumpAsIniOn(file);
1694 newinfo.dumpAsIniOn(file);
1697 newinfo.setFilepath(toedit.filepath());
1698 _repos.erase(toedit);
1699 _repos.insert(newinfo);
1700 HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1701 MIL << "repo " << alias << " modified" << endl;
1705 ////////////////////////////////////////////////////////////////////////////
1707 RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1709 RepoConstIterator it( findAlias( alias, _repos ) );
1710 if ( it != _repos.end() )
1713 info.setAlias( alias );
1714 ZYPP_THROW( RepoNotFoundException(info) );
1718 RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1720 for_( it, repoBegin(), repoEnd() )
1722 for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1724 if ( (*urlit).asString(urlview) == url.asString(urlview) )
1729 info.setBaseUrl( url );
1730 ZYPP_THROW( RepoNotFoundException(info) );
1733 ////////////////////////////////////////////////////////////////////////////
1737 ////////////////////////////////////////////////////////////////////////////
1739 void RepoManager::Impl::addService( const ServiceInfo & service )
1741 assert_alias( service );
1743 // check if service already exists
1744 if ( hasService( service.alias() ) )
1745 ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1747 // Writable ServiceInfo is needed to save the location
1748 // of the .service file. Finaly insert into the service list.
1749 ServiceInfo toSave( service );
1750 saveService( toSave );
1751 _services.insert( toSave );
1753 // check for credentials in Url (username:password, not ?credentials param)
1754 if ( toSave.url().hasCredentialsInAuthority() )
1756 media::CredentialManager cm(
1757 media::CredManagerOptions(_options.rootDir) );
1759 //! \todo use a method calling UI callbacks to ask where to save creds?
1760 cm.saveInUser(media::AuthData(toSave.url()));
1763 MIL << "added service " << toSave.alias() << endl;
1766 ////////////////////////////////////////////////////////////////////////////
1768 void RepoManager::Impl::removeService( const std::string & alias )
1770 MIL << "Going to delete repo " << alias << endl;
1772 const ServiceInfo & service = getService( alias );
1774 Pathname location = service.filepath();
1775 if( location.empty() )
1777 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
1781 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1783 // only one service definition in the file
1784 if ( tmpSet.size() == 1 )
1786 if ( filesystem::unlink(location) != 0 )
1788 // TranslatorExplanation '%s' is a filename
1789 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), location.c_str() )));
1791 MIL << alias << " sucessfully deleted." << endl;
1795 filesystem::assert_dir(location.dirname());
1797 std::ofstream file(location.c_str());
1800 // TranslatorExplanation '%s' is a filename
1801 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1804 for_(it, tmpSet.begin(), tmpSet.end())
1806 if( it->alias() != alias )
1807 it->dumpAsIniOn(file);
1810 MIL << alias << " sucessfully deleted from file " << location << endl;
1813 // now remove all repositories added by this service
1814 RepoCollector rcollector;
1815 getRepositoriesInService( alias,
1816 boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1817 // cannot do this directly in getRepositoriesInService - would invalidate iterators
1818 for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1819 removeRepository(*rit);
1822 ////////////////////////////////////////////////////////////////////////////
1824 void RepoManager::Impl::refreshServices()
1826 // copy the set of services since refreshService
1827 // can eventually invalidate the iterator
1828 ServiceSet services( serviceBegin(), serviceEnd() );
1829 for_( it, services.begin(), services.end() )
1831 if ( !it->enabled() )
1835 refreshService(*it);
1837 catch ( const repo::ServicePluginInformalException & e )
1838 { ;/* ignore ServicePluginInformalException */ }
1842 void RepoManager::Impl::refreshService( const std::string & alias )
1844 ServiceInfo service( getService( alias ) );
1845 assert_alias( service );
1846 assert_url( service );
1847 // NOTE: It might be necessary to modify and rewrite the service info.
1848 // Either when probing the type, or when adjusting the repositories
1849 // enable/disable state.:
1850 bool serviceModified = false;
1851 MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << endl;
1853 //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
1855 // if the type is unknown, try probing.
1856 if ( service.type() == repo::ServiceType::NONE )
1858 repo::ServiceType type = probeService( service.url() );
1859 if ( type != ServiceType::NONE )
1861 service.setProbedType( type ); // lazy init!
1862 serviceModified = true;
1866 // get target distro identifier
1867 std::string servicesTargetDistro = _options.servicesTargetDistro;
1868 if ( servicesTargetDistro.empty() )
1870 servicesTargetDistro = Target::targetDistribution( Pathname() );
1872 DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
1875 RepoCollector collector(servicesTargetDistro);
1876 // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
1877 // which is actually a notification. Using an exception for this
1878 // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
1880 std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
1882 ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
1884 catch ( const repo::ServicePluginInformalException & e )
1886 /* ignore ServicePluginInformalException and throw later */
1887 uglyHack.first = true;
1888 uglyHack.second = e;
1891 // set service alias and base url for all collected repositories
1892 for_( it, collector.repos.begin(), collector.repos.end() )
1894 // if the repo url was not set by the repoindex parser, set service's url
1897 if ( it->baseUrlsEmpty() )
1898 url = service.url();
1901 // service repo can contain only one URL now, so no need to iterate.
1902 url = *it->baseUrlsBegin();
1905 // libzypp currently has problem with separate url + path handling
1906 // so just append the path to the baseurl
1907 if ( !it->path().empty() )
1909 Pathname path(url.getPathName());
1911 url.setPathName( path.asString() );
1915 // Prepend service alias:
1916 it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
1919 it->setBaseUrl( url );
1920 // set refrence to the parent service
1921 it->setService( service.alias() );
1924 ////////////////////////////////////////////////////////////////////////////
1925 // Now compare collected repos with the ones in the system...
1927 RepoInfoList oldRepos;
1928 getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
1930 // find old repositories to remove...
1931 for_( it, oldRepos.begin(), oldRepos.end() )
1933 if ( ! foundAliasIn( it->alias(), collector.repos ) )
1935 if ( it->enabled() && ! service.repoToDisableFind( it->alias() ) )
1937 DBG << "Service removes enabled repo " << it->alias() << endl;
1938 service.addRepoToEnable( it->alias() );
1939 serviceModified = true;
1943 DBG << "Service removes disabled repo " << it->alias() << endl;
1945 removeRepository( *it );
1949 ////////////////////////////////////////////////////////////////////////////
1950 // create missing repositories and modify exising ones if needed...
1951 for_( it, collector.repos.begin(), collector.repos.end() )
1953 // Service explicitly requests the repo being enabled?
1954 // Service explicitly requests the repo being disabled?
1955 // And hopefully not both ;) If so, enable wins.
1956 bool beEnabled = service.repoToEnableFind( it->alias() );
1957 bool beDisabled = service.repoToDisableFind( it->alias() );
1959 // Make sure the service repo is created with the
1960 // appropriate enable
1961 if ( beEnabled ) it->setEnabled(true);
1962 if ( beDisabled ) it->setEnabled(false);
1966 // Remove from enable request list.
1967 // NOTE: repoToDisable is handled differently.
1968 // It gets cleared on each refresh.
1969 service.delRepoToEnable( it->alias() );
1970 serviceModified = true;
1973 RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
1974 if ( oldRepo == oldRepos.end() )
1976 // Not found in oldRepos ==> a new repo to add
1978 // At that point check whether a repo with the same alias
1979 // exists outside this service. Maybe forcefully re-alias
1980 // the existing repo?
1981 DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
1982 addRepository( *it );
1984 // save repo credentials
1985 // ma@: task for modifyRepository?
1989 // ==> an exising repo to check
1990 bool oldRepoModified = false;
1995 if ( ! oldRepo->enabled() )
1997 DBG << "Service repo " << it->alias() << " gets enabled" << endl;
1998 oldRepo->setEnabled( true );
1999 oldRepoModified = true;
2003 DBG << "Service repo " << it->alias() << " stays enabled" << endl;
2006 else if ( beDisabled )
2008 if ( oldRepo->enabled() )
2010 DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2011 oldRepo->setEnabled( false );
2012 oldRepoModified = true;
2016 DBG << "Service repo " << it->alias() << " stays disabled" << endl;
2021 DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
2025 // service repo can contain only one URL now, so no need to iterate.
2026 if ( oldRepo->url() != it->url() )
2028 DBG << "Service repo " << it->alias() << " gets new URL " << it->url() << endl;
2029 oldRepo->setBaseUrl( it->url() );
2030 oldRepoModified = true;
2033 // save if modified:
2034 if ( oldRepoModified )
2036 modifyRepository( oldRepo->alias(), *oldRepo );
2041 // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2042 if ( ! service.reposToDisableEmpty() )
2044 service.clearReposToDisable();
2045 serviceModified = true;
2048 ////////////////////////////////////////////////////////////////////////////
2049 // save service if modified:
2050 if ( serviceModified )
2052 // write out modified service file.
2053 modifyService( service.alias(), service );
2056 if ( uglyHack.first )
2058 throw( uglyHack.second ); // intentionally not ZYPP_THROW
2062 ////////////////////////////////////////////////////////////////////////////
2064 void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2066 MIL << "Going to modify service " << oldAlias << endl;
2068 // we need a writable copy to link it to the file where
2069 // it is saved if we modify it
2070 ServiceInfo service(newService);
2072 if ( service.type() == ServiceType::PLUGIN )
2074 MIL << "Not modifying plugin service '" << oldAlias << "'" << endl;
2078 const ServiceInfo & oldService = getService(oldAlias);
2080 Pathname location = oldService.filepath();
2081 if( location.empty() )
2083 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
2086 // remember: there may multiple services being defined in one file:
2088 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2090 filesystem::assert_dir(location.dirname());
2091 std::ofstream file(location.c_str());
2092 for_(it, tmpSet.begin(), tmpSet.end())
2094 if( *it != oldAlias )
2095 it->dumpAsIniOn(file);
2097 service.dumpAsIniOn(file);
2099 service.setFilepath(location);
2101 _services.erase(oldAlias);
2102 _services.insert(service);
2104 // changed properties affecting also repositories
2105 if( oldAlias != service.alias() // changed alias
2106 || oldService.enabled() != service.enabled() // changed enabled status
2109 std::vector<RepoInfo> toModify;
2110 getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2111 for_( it, toModify.begin(), toModify.end() )
2113 if (oldService.enabled() && !service.enabled())
2114 it->setEnabled(false);
2115 else if (!oldService.enabled() && service.enabled())
2117 //! \todo do nothing? the repos will be enabled on service refresh
2118 //! \todo how to know the service needs a (auto) refresh????
2121 it->setService(service.alias());
2122 modifyRepository(it->alias(), *it);
2126 //! \todo refresh the service automatically if url is changed?
2129 ////////////////////////////////////////////////////////////////////////////
2131 repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2135 MediaSetAccess access(url);
2136 if ( access.doesFileExist("/repo/repoindex.xml") )
2137 return repo::ServiceType::RIS;
2139 catch ( const media::MediaException &e )
2142 // TranslatorExplanation '%s' is an URL
2143 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2147 catch ( const Exception &e )
2150 // TranslatorExplanation '%s' is an URL
2151 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2156 return repo::ServiceType::NONE;
2159 ///////////////////////////////////////////////////////////////////
2161 // CLASS NAME : RepoManager
2163 ///////////////////////////////////////////////////////////////////
2165 RepoManager::RepoManager( const RepoManagerOptions & opt )
2166 : _pimpl( new Impl(opt) )
2169 RepoManager::~RepoManager()
2172 bool RepoManager::repoEmpty() const
2173 { return _pimpl->repoEmpty(); }
2175 RepoManager::RepoSizeType RepoManager::repoSize() const
2176 { return _pimpl->repoSize(); }
2178 RepoManager::RepoConstIterator RepoManager::repoBegin() const
2179 { return _pimpl->repoBegin(); }
2181 RepoManager::RepoConstIterator RepoManager::repoEnd() const
2182 { return _pimpl->repoEnd(); }
2184 RepoInfo RepoManager::getRepo( const std::string & alias ) const
2185 { return _pimpl->getRepo( alias ); }
2187 bool RepoManager::hasRepo( const std::string & alias ) const
2188 { return _pimpl->hasRepo( alias ); }
2190 std::string RepoManager::makeStupidAlias( const Url & url_r )
2192 std::string ret( url_r.getScheme() );
2198 std::string host( url_r.getHost() );
2199 if ( ! host.empty() )
2205 static Date::ValueType serial = Date::now();
2206 ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2210 RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2211 { return _pimpl->metadataStatus( info ); }
2213 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2214 { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2216 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2217 { return _pimpl->metadataPath( info ); }
2219 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2220 { return _pimpl->packagesPath( info ); }
2222 void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2223 { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2225 void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2226 { return _pimpl->cleanMetadata( info, progressrcv ); }
2228 void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2229 { return _pimpl->cleanPackages( info, progressrcv ); }
2231 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2232 { return _pimpl->cacheStatus( info ); }
2234 void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2235 { return _pimpl->buildCache( info, policy, progressrcv ); }
2237 void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2238 { return _pimpl->cleanCache( info, progressrcv ); }
2240 bool RepoManager::isCached( const RepoInfo &info ) const
2241 { return _pimpl->isCached( info ); }
2243 void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2244 { return _pimpl->loadFromCache( info, progressrcv ); }
2246 void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2247 { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2249 repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2250 { return _pimpl->probe( url, path ); }
2252 repo::RepoType RepoManager::probe( const Url & url ) const
2253 { return _pimpl->probe( url ); }
2255 void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2256 { return _pimpl->addRepository( info, progressrcv ); }
2258 void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2259 { return _pimpl->addRepositories( url, progressrcv ); }
2261 void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2262 { return _pimpl->removeRepository( info, progressrcv ); }
2264 void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2265 { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2267 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2268 { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2270 RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2271 { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2273 bool RepoManager::serviceEmpty() const
2274 { return _pimpl->serviceEmpty(); }
2276 RepoManager::ServiceSizeType RepoManager::serviceSize() const
2277 { return _pimpl->serviceSize(); }
2279 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2280 { return _pimpl->serviceBegin(); }
2282 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2283 { return _pimpl->serviceEnd(); }
2285 ServiceInfo RepoManager::getService( const std::string & alias ) const
2286 { return _pimpl->getService( alias ); }
2288 bool RepoManager::hasService( const std::string & alias ) const
2289 { return _pimpl->hasService( alias ); }
2291 repo::ServiceType RepoManager::probeService( const Url &url ) const
2292 { return _pimpl->probeService( url ); }
2294 void RepoManager::addService( const std::string & alias, const Url& url )
2295 { return _pimpl->addService( alias, url ); }
2297 void RepoManager::addService( const ServiceInfo & service )
2298 { return _pimpl->addService( service ); }
2300 void RepoManager::removeService( const std::string & alias )
2301 { return _pimpl->removeService( alias ); }
2303 void RepoManager::removeService( const ServiceInfo & service )
2304 { return _pimpl->removeService( service ); }
2306 void RepoManager::refreshServices()
2307 { return _pimpl->refreshServices(); }
2309 void RepoManager::refreshService( const std::string & alias )
2310 { return _pimpl->refreshService( alias ); }
2312 void RepoManager::refreshService( const ServiceInfo & service )
2313 { return _pimpl->refreshService( service ); }
2315 void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2316 { return _pimpl->modifyService( oldAlias, service ); }
2318 ////////////////////////////////////////////////////////////////////////////
2320 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2321 { return str << *obj._pimpl; }
2323 /////////////////////////////////////////////////////////////////
2325 ///////////////////////////////////////////////////////////////////