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 std::list<std::string> repoEscAliases;
641 for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
643 // set the metadata path for the repo
644 repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
645 // set the downloaded packages path for the repo
646 repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
648 _repos.insert( repoInfo );
649 repoEscAliases.push_back(repoInfo.escaped_alias());
651 repoEscAliases.sort();
653 // delete metadata folders without corresponding repo (e.g. old tmp directories)
654 for ( const Pathname & cachePath : { _options.repoRawCachePath
655 , _options.repoSolvCachePath } )
657 std::list<std::string> entries;
658 if ( filesystem::readdir( entries, cachePath, false ) == 0 )
661 std::set<std::string> oldfiles;
662 set_difference( entries.begin(), entries.end(), repoEscAliases.begin(), repoEscAliases.end(),
663 std::inserter( oldfiles, oldfiles.end() ) );
664 for ( const std::string & old : oldfiles )
666 filesystem::recursive_rmdir( cachePath / old );
671 MIL << "end construct known repos" << endl;
674 ///////////////////////////////////////////////////////////////////
676 RepoStatus RepoManager::Impl::metadataStatus( const RepoInfo & info ) const
678 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
679 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
680 RepoType repokind = info.type();
683 switch ( repokind.toEnum() )
685 case RepoType::NONE_e:
686 // unknown, probe the local metadata
687 repokind = probe( productdatapath.asUrl() );
693 switch ( repokind.toEnum() )
695 case RepoType::RPMMD_e :
697 status = RepoStatus( productdatapath + "/repodata/repomd.xml");
701 case RepoType::YAST2_e :
703 status = RepoStatus( productdatapath + "/content") && (RepoStatus( mediarootpath + "/media.1/media"));
707 case RepoType::RPMPLAINDIR_e :
709 if ( PathInfo(Pathname(productdatapath + "/cookie")).isExist() )
710 status = RepoStatus( productdatapath + "/cookie");
714 case RepoType::NONE_e :
715 // Return default RepoStatus in case of RepoType::NONE
716 // indicating it should be created?
717 // ZYPP_THROW(RepoUnknownTypeException());
724 void RepoManager::Impl::touchIndexFile( const RepoInfo & info )
726 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
728 RepoType repokind = info.type();
729 if ( repokind.toEnum() == RepoType::NONE_e )
730 // unknown, probe the local metadata
731 repokind = probe( productdatapath.asUrl() );
732 // if still unknown, just return
733 if (repokind == RepoType::NONE_e)
737 switch ( repokind.toEnum() )
739 case RepoType::RPMMD_e :
740 p = Pathname(productdatapath + "/repodata/repomd.xml");
743 case RepoType::YAST2_e :
744 p = Pathname(productdatapath + "/content");
747 case RepoType::RPMPLAINDIR_e :
748 p = Pathname(productdatapath + "/cookie");
751 case RepoType::NONE_e :
756 // touch the file, ignore error (they are logged anyway)
757 filesystem::touch(p);
761 RepoManager::RefreshCheckStatus RepoManager::Impl::checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy )
765 RepoStatus oldstatus;
766 RepoStatus newstatus;
770 MIL << "Going to try to check whether refresh is needed for " << url << endl;
772 // first check old (cached) metadata
773 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
774 filesystem::assert_dir(mediarootpath);
775 oldstatus = metadataStatus(info);
777 if ( oldstatus.empty() )
779 MIL << "No cached metadata, going to refresh" << endl;
780 return REFRESH_NEEDED;
784 std::string scheme( url.getScheme() );
785 if ( scheme == "cd" || scheme == "dvd" )
787 MIL << "never refresh CD/DVD" << endl;
788 return REPO_UP_TO_DATE;
792 // now we've got the old (cached) status, we can decide repo.refresh.delay
793 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
795 // difference in seconds
796 double diff = difftime(
797 (Date::ValueType)Date::now(),
798 (Date::ValueType)oldstatus.timestamp()) / 60;
800 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
801 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
802 DBG << "last refresh = " << diff << " minutes ago" << endl;
804 if ( diff < ZConfig::instance().repo_refresh_delay() )
808 WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
812 MIL << "Repository '" << info.alias()
813 << "' has been refreshed less than repo.refresh.delay ("
814 << ZConfig::instance().repo_refresh_delay()
815 << ") minutes ago. Advising to skip refresh" << endl;
816 return REPO_CHECK_DELAYED;
821 // To test the new matadta create temp dir as sibling of mediarootpath
822 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
824 repo::RepoType repokind = info.type();
825 // if the type is unknown, try probing.
826 switch ( repokind.toEnum() )
828 case RepoType::NONE_e:
829 // unknown, probe it \todo respect productdir
830 repokind = probe( url, info.path() );
836 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
837 ( repokind.toEnum() == RepoType::YAST2_e ) )
839 MediaSetAccess media(url);
840 shared_ptr<repo::Downloader> downloader_ptr;
842 if ( repokind.toEnum() == RepoType::RPMMD_e )
843 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
845 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath));
847 RepoStatus newstatus = downloader_ptr->status(media);
848 bool refresh = false;
849 if ( oldstatus.checksum() == newstatus.checksum() )
851 MIL << "repo has not changed" << endl;
852 if ( policy == RefreshForced )
854 MIL << "refresh set to forced" << endl;
860 MIL << "repo has changed, going to refresh" << endl;
865 touchIndexFile(info);
867 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
869 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
871 MediaMounter media( url );
872 RepoStatus newstatus = parser::plaindir::dirStatus( media.getPathName( info.path() ) );
873 bool refresh = false;
874 if ( oldstatus.checksum() == newstatus.checksum() )
876 MIL << "repo has not changed" << endl;
877 if ( policy == RefreshForced )
879 MIL << "refresh set to forced" << endl;
885 MIL << "repo has changed, going to refresh" << endl;
890 touchIndexFile(info);
892 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
896 ZYPP_THROW(RepoUnknownTypeException(info));
899 catch ( const Exception &e )
902 ERR << "refresh check failed for " << url << endl;
906 return REFRESH_NEEDED; // default
910 void RepoManager::Impl::refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progress )
915 // we will throw this later if no URL checks out fine
916 RepoException rexception(_PL("Valid metadata not found at specified URL",
917 "Valid metadata not found at specified URLs",
918 info.baseUrlsSize() ) );
920 // try urls one by one
921 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
927 // check whether to refresh metadata
928 // if the check fails for this url, it throws, so another url will be checked
929 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
932 MIL << "Going to refresh metadata from " << url << endl;
934 repo::RepoType repokind = info.type();
936 // if the type is unknown, try probing.
937 switch ( repokind.toEnum() )
939 case RepoType::NONE_e:
941 repokind = probe( *it, info.path() );
943 if (repokind.toEnum() != RepoType::NONE_e)
945 // Adjust the probed type in RepoInfo
946 info.setProbedType( repokind ); // lazy init!
947 //save probed type only for repos in system
948 for_( it, repoBegin(), repoEnd() )
950 if ( info.alias() == (*it).alias() )
952 RepoInfo modifiedrepo = info;
953 modifiedrepo.setType( repokind );
954 modifyRepository( info.alias(), modifiedrepo );
964 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
965 if( filesystem::assert_dir(mediarootpath) )
967 Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
971 // create temp dir as sibling of mediarootpath
972 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
973 if( tmpdir.path().empty() )
975 Exception ex(_("Can't create metadata cache directory."));
979 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
980 ( repokind.toEnum() == RepoType::YAST2_e ) )
982 MediaSetAccess media(url);
983 shared_ptr<repo::Downloader> downloader_ptr;
985 MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
987 if ( repokind.toEnum() == RepoType::RPMMD_e )
988 downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
990 downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
993 * Given a downloader, sets the other repos raw metadata
994 * path as cache paths for the fetcher, so if another
995 * repo has the same file, it will not download it
996 * but copy it from the other repository
998 for_( it, repoBegin(), repoEnd() )
1000 Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1001 if ( PathInfo(cachepath).isExist() )
1002 downloader_ptr->addCachePath(cachepath);
1005 downloader_ptr->download( media, tmpdir.path() );
1007 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1009 MediaMounter media( url );
1010 RepoStatus newstatus = parser::plaindir::dirStatus( media.getPathName( info.path() ) );
1012 Pathname productpath( tmpdir.path() / info.path() );
1013 filesystem::assert_dir( productpath );
1014 std::ofstream file( (productpath/"cookie").c_str() );
1017 // TranslatorExplanation '%s' is a filename
1018 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), (productpath/"cookie").c_str() )));
1021 if ( ! info.path().empty() && info.path() != "/" )
1022 file << " (" << info.path() << ")";
1024 file << newstatus.checksum() << endl;
1030 ZYPP_THROW(RepoUnknownTypeException());
1033 // ok we have the metadata, now exchange
1035 filesystem::exchange( tmpdir.path(), mediarootpath );
1040 catch ( const Exception &e )
1043 ERR << "Trying another url..." << endl;
1045 // remember the exception caught for the *first URL*
1046 // if all other URLs fail, the rexception will be thrown with the
1047 // cause of the problem of the first URL remembered
1048 if (it == info.baseUrlsBegin())
1049 rexception.remember(e);
1052 ERR << "No more urls..." << endl;
1053 ZYPP_THROW(rexception);
1056 ////////////////////////////////////////////////////////////////////////////
1058 void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1060 ProgressData progress(100);
1061 progress.sendTo(progressfnc);
1063 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1068 void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1070 ProgressData progress(100);
1071 progress.sendTo(progressfnc);
1073 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1078 void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1081 Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1082 Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1084 if( filesystem::assert_dir(_options.repoCachePath) )
1086 Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1089 RepoStatus raw_metadata_status = metadataStatus(info);
1090 if ( raw_metadata_status.empty() )
1092 /* if there is no cache at this point, we refresh the raw
1093 in case this is the first time - if it's !autorefresh,
1094 we may still refresh */
1095 refreshMetadata(info, RefreshIfNeeded, progressrcv );
1096 raw_metadata_status = metadataStatus(info);
1099 bool needs_cleaning = false;
1100 if ( isCached( info ) )
1102 MIL << info.alias() << " is already cached." << endl;
1103 RepoStatus cache_status = cacheStatus(info);
1105 if ( cache_status.checksum() == raw_metadata_status.checksum() )
1107 MIL << info.alias() << " cache is up to date with metadata." << endl;
1108 if ( policy == BuildIfNeeded ) {
1112 MIL << info.alias() << " cache rebuild is forced" << endl;
1116 needs_cleaning = true;
1119 ProgressData progress(100);
1120 callback::SendReport<ProgressReport> report;
1121 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1122 progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1130 MIL << info.alias() << " building cache..." << info.type() << endl;
1132 Pathname base = solv_path_for_repoinfo( _options, info);
1134 if( filesystem::assert_dir(base) )
1136 Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1140 if( ! PathInfo(base).userMayW() )
1142 Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1145 Pathname solvfile = base / "solv";
1148 repo::RepoType repokind = info.type();
1150 // if the type is unknown, try probing.
1151 switch ( repokind.toEnum() )
1153 case RepoType::NONE_e:
1154 // unknown, probe the local metadata
1155 repokind = probe( productdatapath.asUrl() );
1161 MIL << "repo type is " << repokind << endl;
1163 switch ( repokind.toEnum() )
1165 case RepoType::RPMMD_e :
1166 case RepoType::YAST2_e :
1167 case RepoType::RPMPLAINDIR_e :
1169 // Take care we unlink the solvfile on exception
1170 ManagedFile guard( solvfile, filesystem::unlink );
1171 scoped_ptr<MediaMounter> forPlainDirs;
1173 ExternalProgram::Arguments cmd;
1174 cmd.push_back( "repo2solv.sh" );
1176 // repo2solv expects -o as 1st arg!
1177 cmd.push_back( "-o" );
1178 cmd.push_back( solvfile.asString() );
1180 if ( repokind == RepoType::RPMPLAINDIR )
1182 forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1183 // recusive for plaindir as 2nd arg!
1184 cmd.push_back( "-R" );
1185 // FIXME this does only work form dir: URLs
1186 cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1189 cmd.push_back( productdatapath.asString() );
1191 ExternalProgram prog( cmd, ExternalProgram::Stderr_To_Stdout );
1192 std::string errdetail;
1194 for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1195 WAR << " " << output;
1196 if ( errdetail.empty() ) {
1197 errdetail = prog.command();
1200 errdetail += output;
1203 int ret = prog.close();
1206 RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1207 ex.remember( errdetail );
1212 guard.resetDispose();
1216 ZYPP_THROW(RepoUnknownTypeException( _("Unhandled repository type") ));
1219 // update timestamp and checksum
1220 setCacheStatus(info, raw_metadata_status);
1221 MIL << "Commit cache.." << endl;
1225 ////////////////////////////////////////////////////////////////////////////
1227 repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1229 MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1231 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1233 // Handle non existing local directory in advance, as
1234 // MediaSetAccess does not support it.
1235 MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1236 return repo::RepoType::NONE;
1239 // prepare exception to be thrown if the type could not be determined
1240 // due to a media exception. We can't throw right away, because of some
1241 // problems with proxy servers returning an incorrect error
1242 // on ftp file-not-found(bnc #335906). Instead we'll check another types
1245 // TranslatorExplanation '%s' is an URL
1246 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1247 bool gotMediaException = false;
1250 MediaSetAccess access(url);
1253 if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1255 MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1256 return repo::RepoType::RPMMD;
1259 catch ( const media::MediaException &e )
1262 DBG << "problem checking for repodata/repomd.xml file" << endl;
1264 gotMediaException = true;
1269 if ( access.doesFileExist(path/"/content") )
1271 MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1272 return repo::RepoType::YAST2;
1275 catch ( const media::MediaException &e )
1278 DBG << "problem checking for content file" << endl;
1280 gotMediaException = true;
1283 // if it is a non-downloading URL denoting a directory
1284 if ( ! url.schemeIsDownloading() )
1286 MediaMounter media( url );
1287 if ( PathInfo(media.getPathName()/path).isDir() )
1289 // allow empty dirs for now
1290 MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1291 return repo::RepoType::RPMPLAINDIR;
1295 catch ( const Exception &e )
1298 // TranslatorExplanation '%s' is an URL
1299 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1304 if (gotMediaException)
1307 MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1308 return repo::RepoType::NONE;
1311 ////////////////////////////////////////////////////////////////////////////
1313 void RepoManager::Impl::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
1315 MIL << "Going to clean up garbage in cache dirs" << endl;
1317 ProgressData progress(300);
1318 progress.sendTo(progressrcv);
1321 std::list<Pathname> cachedirs;
1322 cachedirs.push_back(_options.repoRawCachePath);
1323 cachedirs.push_back(_options.repoPackagesCachePath);
1324 cachedirs.push_back(_options.repoSolvCachePath);
1326 for_( dir, cachedirs.begin(), cachedirs.end() )
1328 if ( PathInfo(*dir).isExist() )
1330 std::list<Pathname> entries;
1331 if ( filesystem::readdir( entries, *dir, false ) != 0 )
1332 // TranslatorExplanation '%s' is a pathname
1333 ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1335 unsigned sdircount = entries.size();
1336 unsigned sdircurrent = 1;
1337 for_( subdir, entries.begin(), entries.end() )
1339 // if it does not belong known repo, make it disappear
1341 for_( r, repoBegin(), repoEnd() )
1342 if ( subdir->basename() == r->escaped_alias() )
1343 { found = true; break; }
1346 filesystem::recursive_rmdir( *subdir );
1348 progress.set( progress.val() + sdircurrent * 100 / sdircount );
1353 progress.set( progress.val() + 100 );
1358 ////////////////////////////////////////////////////////////////////////////
1360 void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1362 ProgressData progress(100);
1363 progress.sendTo(progressrcv);
1366 MIL << "Removing raw metadata cache for " << info.alias() << endl;
1367 filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1372 ////////////////////////////////////////////////////////////////////////////
1374 void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1377 Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1379 if ( ! PathInfo(solvfile).isExist() )
1380 ZYPP_THROW(RepoNotCachedException(info));
1382 sat::Pool::instance().reposErase( info.alias() );
1385 Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1386 // test toolversion in order to rebuild solv file in case
1387 // it was written by an old libsolv-tool parser.
1389 // Known version strings used:
1393 sat::LookupRepoAttr toolversion( sat::SolvAttr::repositoryToolVersion, repo );
1394 if ( toolversion.begin().asString().empty() )
1396 repo.eraseFromPool();
1397 ZYPP_THROW(Exception("Solv-file was created by old parser."));
1399 // else: up-to-date (or even newer).
1401 catch ( const Exception & exp )
1404 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1405 cleanCache( info, progressrcv );
1406 buildCache( info, BuildIfNeeded, progressrcv );
1408 sat::Pool::instance().addRepoSolv( solvfile, info );
1412 ////////////////////////////////////////////////////////////////////////////
1414 void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1418 ProgressData progress(100);
1419 callback::SendReport<ProgressReport> report;
1420 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1421 progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1424 MIL << "Try adding repo " << info << endl;
1426 RepoInfo tosave = info;
1427 if ( _repos.find(tosave) != _repos.end() )
1428 ZYPP_THROW(RepoAlreadyExistsException(info));
1430 // check the first url for now
1431 if ( _options.probe )
1433 DBG << "unknown repository type, probing" << endl;
1435 RepoType probedtype;
1436 probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1437 if ( tosave.baseUrlsSize() > 0 )
1439 if ( probedtype == RepoType::NONE )
1440 ZYPP_THROW(RepoUnknownTypeException());
1442 tosave.setType(probedtype);
1448 // assert the directory exists
1449 filesystem::assert_dir(_options.knownReposPath);
1451 Pathname repofile = generateNonExistingName(
1452 _options.knownReposPath, generateFilename(tosave));
1453 // now we have a filename that does not exists
1454 MIL << "Saving repo in " << repofile << endl;
1456 std::ofstream file(repofile.c_str());
1459 // TranslatorExplanation '%s' is a filename
1460 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1463 tosave.dumpAsIniOn(file);
1464 tosave.setFilepath(repofile);
1465 tosave.setMetadataPath( metadataPath( tosave ) );
1466 tosave.setPackagesPath( packagesPath( tosave ) );
1468 // We chould fix the API as we must injet those paths
1469 // into the repoinfo in order to keep it usable.
1470 RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1471 oinfo.setMetadataPath( metadataPath( tosave ) );
1472 oinfo.setPackagesPath( packagesPath( tosave ) );
1474 _repos.insert(tosave);
1478 // check for credentials in Urls
1479 bool havePasswords = false;
1480 for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1481 if ( urlit->hasCredentialsInAuthority() )
1483 havePasswords = true;
1486 // save the credentials
1487 if ( havePasswords )
1489 media::CredentialManager cm(
1490 media::CredManagerOptions(_options.rootDir) );
1492 for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1493 if (urlit->hasCredentialsInAuthority())
1494 //! \todo use a method calling UI callbacks to ask where to save creds?
1495 cm.saveInUser(media::AuthData(*urlit));
1498 HistoryLog().addRepository(tosave);
1501 MIL << "done" << endl;
1505 void RepoManager::Impl::addRepositories( const Url & url, const ProgressData::ReceiverFnc & progressrcv )
1507 std::list<RepoInfo> repos = readRepoFile(url);
1508 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1512 // look if the alias is in the known repos.
1513 for_ ( kit, repoBegin(), repoEnd() )
1515 if ( (*it).alias() == (*kit).alias() )
1517 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1518 ZYPP_THROW(RepoAlreadyExistsException(*it));
1523 std::string filename = Pathname(url.getPathName()).basename();
1525 if ( filename == Pathname() )
1527 // TranslatorExplanation '%s' is an URL
1528 ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1531 // assert the directory exists
1532 filesystem::assert_dir(_options.knownReposPath);
1534 Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1535 // now we have a filename that does not exists
1536 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1538 std::ofstream file(repofile.c_str());
1541 // TranslatorExplanation '%s' is a filename
1542 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1545 for ( std::list<RepoInfo>::iterator it = repos.begin();
1549 MIL << "Saving " << (*it).alias() << endl;
1550 it->setFilepath(repofile.asString());
1551 it->dumpAsIniOn(file);
1554 HistoryLog(_options.rootDir).addRepository(*it);
1557 MIL << "done" << endl;
1560 ////////////////////////////////////////////////////////////////////////////
1562 void RepoManager::Impl::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1564 ProgressData progress;
1565 callback::SendReport<ProgressReport> report;
1566 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1567 progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1569 MIL << "Going to delete repo " << info.alias() << endl;
1571 for_( it, repoBegin(), repoEnd() )
1573 // they can be the same only if the provided is empty, that means
1574 // the provided repo has no alias
1576 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1579 // TODO match by url
1581 // we have a matcing repository, now we need to know
1582 // where it does come from.
1583 RepoInfo todelete = *it;
1584 if (todelete.filepath().empty())
1586 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1590 // figure how many repos are there in the file:
1591 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1592 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1594 // easy, only this one, just delete the file
1595 if ( filesystem::unlink(todelete.filepath()) != 0 )
1597 // TranslatorExplanation '%s' is a filename
1598 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1600 MIL << todelete.alias() << " sucessfully deleted." << endl;
1604 // there are more repos in the same file
1605 // write them back except the deleted one.
1607 //std::ofstream file(tmp.path().c_str());
1609 // assert the directory exists
1610 filesystem::assert_dir(todelete.filepath().dirname());
1612 std::ofstream file(todelete.filepath().c_str());
1615 // TranslatorExplanation '%s' is a filename
1616 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1618 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1619 fit != filerepos.end();
1622 if ( (*fit).alias() != todelete.alias() )
1623 (*fit).dumpAsIniOn(file);
1627 CombinedProgressData cSubprogrcv(progress, 20);
1628 CombinedProgressData mSubprogrcv(progress, 40);
1629 CombinedProgressData pSubprogrcv(progress, 40);
1630 // now delete it from cache
1631 if ( isCached(todelete) )
1632 cleanCache( todelete, cSubprogrcv);
1633 // now delete metadata (#301037)
1634 cleanMetadata( todelete, mSubprogrcv );
1635 cleanPackages( todelete, pSubprogrcv );
1636 _repos.erase(todelete);
1637 MIL << todelete.alias() << " sucessfully deleted." << endl;
1638 HistoryLog(_options.rootDir).removeRepository(todelete);
1640 } // else filepath is empty
1643 // should not be reached on a sucess workflow
1644 ZYPP_THROW(RepoNotFoundException(info));
1647 ////////////////////////////////////////////////////////////////////////////
1649 void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1651 RepoInfo toedit = getRepositoryInfo(alias);
1652 RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1654 // check if the new alias already exists when renaming the repo
1655 if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1657 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1660 if (toedit.filepath().empty())
1662 ZYPP_THROW(RepoException( _("Can't figure out where the repo is stored.") ));
1666 // figure how many repos are there in the file:
1667 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1669 // there are more repos in the same file
1670 // write them back except the deleted one.
1672 //std::ofstream file(tmp.path().c_str());
1674 // assert the directory exists
1675 filesystem::assert_dir(toedit.filepath().dirname());
1677 std::ofstream file(toedit.filepath().c_str());
1680 // TranslatorExplanation '%s' is a filename
1681 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1683 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1684 fit != filerepos.end();
1687 // if the alias is different, dump the original
1688 // if it is the same, dump the provided one
1689 if ( (*fit).alias() != toedit.alias() )
1690 (*fit).dumpAsIniOn(file);
1692 newinfo.dumpAsIniOn(file);
1695 newinfo.setFilepath(toedit.filepath());
1696 _repos.erase(toedit);
1697 _repos.insert(newinfo);
1698 HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1699 MIL << "repo " << alias << " modified" << endl;
1703 ////////////////////////////////////////////////////////////////////////////
1705 RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1707 RepoConstIterator it( findAlias( alias, _repos ) );
1708 if ( it != _repos.end() )
1711 info.setAlias( alias );
1712 ZYPP_THROW( RepoNotFoundException(info) );
1716 RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1718 for_( it, repoBegin(), repoEnd() )
1720 for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1722 if ( (*urlit).asString(urlview) == url.asString(urlview) )
1727 info.setBaseUrl( url );
1728 ZYPP_THROW( RepoNotFoundException(info) );
1731 ////////////////////////////////////////////////////////////////////////////
1735 ////////////////////////////////////////////////////////////////////////////
1737 void RepoManager::Impl::addService( const ServiceInfo & service )
1739 assert_alias( service );
1741 // check if service already exists
1742 if ( hasService( service.alias() ) )
1743 ZYPP_THROW( ServiceAlreadyExistsException( service ) );
1745 // Writable ServiceInfo is needed to save the location
1746 // of the .service file. Finaly insert into the service list.
1747 ServiceInfo toSave( service );
1748 saveService( toSave );
1749 _services.insert( toSave );
1751 // check for credentials in Url (username:password, not ?credentials param)
1752 if ( toSave.url().hasCredentialsInAuthority() )
1754 media::CredentialManager cm(
1755 media::CredManagerOptions(_options.rootDir) );
1757 //! \todo use a method calling UI callbacks to ask where to save creds?
1758 cm.saveInUser(media::AuthData(toSave.url()));
1761 MIL << "added service " << toSave.alias() << endl;
1764 ////////////////////////////////////////////////////////////////////////////
1766 void RepoManager::Impl::removeService( const std::string & alias )
1768 MIL << "Going to delete repo " << alias << endl;
1770 const ServiceInfo & service = getService( alias );
1772 Pathname location = service.filepath();
1773 if( location.empty() )
1775 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
1779 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1781 // only one service definition in the file
1782 if ( tmpSet.size() == 1 )
1784 if ( filesystem::unlink(location) != 0 )
1786 // TranslatorExplanation '%s' is a filename
1787 ZYPP_THROW(RepoException(str::form( _("Can't delete '%s'"), location.c_str() )));
1789 MIL << alias << " sucessfully deleted." << endl;
1793 filesystem::assert_dir(location.dirname());
1795 std::ofstream file(location.c_str());
1798 // TranslatorExplanation '%s' is a filename
1799 ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1802 for_(it, tmpSet.begin(), tmpSet.end())
1804 if( it->alias() != alias )
1805 it->dumpAsIniOn(file);
1808 MIL << alias << " sucessfully deleted from file " << location << endl;
1811 // now remove all repositories added by this service
1812 RepoCollector rcollector;
1813 getRepositoriesInService( alias,
1814 boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1815 // cannot do this directly in getRepositoriesInService - would invalidate iterators
1816 for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1817 removeRepository(*rit);
1820 ////////////////////////////////////////////////////////////////////////////
1822 void RepoManager::Impl::refreshServices()
1824 // copy the set of services since refreshService
1825 // can eventually invalidate the iterator
1826 ServiceSet services( serviceBegin(), serviceEnd() );
1827 for_( it, services.begin(), services.end() )
1829 if ( !it->enabled() )
1833 refreshService(*it);
1835 catch ( const repo::ServicePluginInformalException & e )
1836 { ;/* ignore ServicePluginInformalException */ }
1840 void RepoManager::Impl::refreshService( const std::string & alias )
1842 ServiceInfo service( getService( alias ) );
1843 assert_alias( service );
1844 assert_url( service );
1845 // NOTE: It might be necessary to modify and rewrite the service info.
1846 // Either when probing the type, or when adjusting the repositories
1847 // enable/disable state.:
1848 bool serviceModified = false;
1849 MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << endl;
1851 //! \todo add callbacks for apps (start, end, repo removed, repo added, repo changed)
1853 // if the type is unknown, try probing.
1854 if ( service.type() == repo::ServiceType::NONE )
1856 repo::ServiceType type = probeService( service.url() );
1857 if ( type != ServiceType::NONE )
1859 service.setProbedType( type ); // lazy init!
1860 serviceModified = true;
1864 // get target distro identifier
1865 std::string servicesTargetDistro = _options.servicesTargetDistro;
1866 if ( servicesTargetDistro.empty() )
1868 servicesTargetDistro = Target::targetDistribution( Pathname() );
1870 DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
1873 RepoCollector collector(servicesTargetDistro);
1874 // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
1875 // which is actually a notification. Using an exception for this
1876 // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
1878 std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
1880 ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
1882 catch ( const repo::ServicePluginInformalException & e )
1884 /* ignore ServicePluginInformalException and throw later */
1885 uglyHack.first = true;
1886 uglyHack.second = e;
1889 // set service alias and base url for all collected repositories
1890 for_( it, collector.repos.begin(), collector.repos.end() )
1892 // if the repo url was not set by the repoindex parser, set service's url
1895 if ( it->baseUrlsEmpty() )
1896 url = service.url();
1899 // service repo can contain only one URL now, so no need to iterate.
1900 url = *it->baseUrlsBegin();
1903 // libzypp currently has problem with separate url + path handling
1904 // so just append the path to the baseurl
1905 if ( !it->path().empty() )
1907 Pathname path(url.getPathName());
1909 url.setPathName( path.asString() );
1913 // Prepend service alias:
1914 it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
1917 it->setBaseUrl( url );
1918 // set refrence to the parent service
1919 it->setService( service.alias() );
1922 ////////////////////////////////////////////////////////////////////////////
1923 // Now compare collected repos with the ones in the system...
1925 RepoInfoList oldRepos;
1926 getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
1928 // find old repositories to remove...
1929 for_( it, oldRepos.begin(), oldRepos.end() )
1931 if ( ! foundAliasIn( it->alias(), collector.repos ) )
1933 if ( it->enabled() && ! service.repoToDisableFind( it->alias() ) )
1935 DBG << "Service removes enabled repo " << it->alias() << endl;
1936 service.addRepoToEnable( it->alias() );
1937 serviceModified = true;
1941 DBG << "Service removes disabled repo " << it->alias() << endl;
1943 removeRepository( *it );
1947 ////////////////////////////////////////////////////////////////////////////
1948 // create missing repositories and modify exising ones if needed...
1949 for_( it, collector.repos.begin(), collector.repos.end() )
1951 // Service explicitly requests the repo being enabled?
1952 // Service explicitly requests the repo being disabled?
1953 // And hopefully not both ;) If so, enable wins.
1954 bool beEnabled = service.repoToEnableFind( it->alias() );
1955 bool beDisabled = service.repoToDisableFind( it->alias() );
1957 // Make sure the service repo is created with the
1958 // appropriate enable
1959 if ( beEnabled ) it->setEnabled(true);
1960 if ( beDisabled ) it->setEnabled(false);
1964 // Remove from enable request list.
1965 // NOTE: repoToDisable is handled differently.
1966 // It gets cleared on each refresh.
1967 service.delRepoToEnable( it->alias() );
1968 serviceModified = true;
1971 RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
1972 if ( oldRepo == oldRepos.end() )
1974 // Not found in oldRepos ==> a new repo to add
1976 // At that point check whether a repo with the same alias
1977 // exists outside this service. Maybe forcefully re-alias
1978 // the existing repo?
1979 DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
1980 addRepository( *it );
1982 // save repo credentials
1983 // ma@: task for modifyRepository?
1987 // ==> an exising repo to check
1988 bool oldRepoModified = false;
1993 if ( ! oldRepo->enabled() )
1995 DBG << "Service repo " << it->alias() << " gets enabled" << endl;
1996 oldRepo->setEnabled( true );
1997 oldRepoModified = true;
2001 DBG << "Service repo " << it->alias() << " stays enabled" << endl;
2004 else if ( beDisabled )
2006 if ( oldRepo->enabled() )
2008 DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2009 oldRepo->setEnabled( false );
2010 oldRepoModified = true;
2014 DBG << "Service repo " << it->alias() << " stays disabled" << endl;
2019 DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
2023 // service repo can contain only one URL now, so no need to iterate.
2024 if ( oldRepo->url() != it->url() )
2026 DBG << "Service repo " << it->alias() << " gets new URL " << it->url() << endl;
2027 oldRepo->setBaseUrl( it->url() );
2028 oldRepoModified = true;
2031 // save if modified:
2032 if ( oldRepoModified )
2034 modifyRepository( oldRepo->alias(), *oldRepo );
2039 // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2040 if ( ! service.reposToDisableEmpty() )
2042 service.clearReposToDisable();
2043 serviceModified = true;
2046 ////////////////////////////////////////////////////////////////////////////
2047 // save service if modified:
2048 if ( serviceModified )
2050 // write out modified service file.
2051 modifyService( service.alias(), service );
2054 if ( uglyHack.first )
2056 throw( uglyHack.second ); // intentionally not ZYPP_THROW
2060 ////////////////////////////////////////////////////////////////////////////
2062 void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2064 MIL << "Going to modify service " << oldAlias << endl;
2066 // we need a writable copy to link it to the file where
2067 // it is saved if we modify it
2068 ServiceInfo service(newService);
2070 if ( service.type() == ServiceType::PLUGIN )
2072 MIL << "Not modifying plugin service '" << oldAlias << "'" << endl;
2076 const ServiceInfo & oldService = getService(oldAlias);
2078 Pathname location = oldService.filepath();
2079 if( location.empty() )
2081 ZYPP_THROW(RepoException( _("Can't figure out where the service is stored.") ));
2084 // remember: there may multiple services being defined in one file:
2086 parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2088 filesystem::assert_dir(location.dirname());
2089 std::ofstream file(location.c_str());
2090 for_(it, tmpSet.begin(), tmpSet.end())
2092 if( *it != oldAlias )
2093 it->dumpAsIniOn(file);
2095 service.dumpAsIniOn(file);
2097 service.setFilepath(location);
2099 _services.erase(oldAlias);
2100 _services.insert(service);
2102 // changed properties affecting also repositories
2103 if( oldAlias != service.alias() // changed alias
2104 || oldService.enabled() != service.enabled() // changed enabled status
2107 std::vector<RepoInfo> toModify;
2108 getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2109 for_( it, toModify.begin(), toModify.end() )
2111 if (oldService.enabled() && !service.enabled())
2112 it->setEnabled(false);
2113 else if (!oldService.enabled() && service.enabled())
2115 //! \todo do nothing? the repos will be enabled on service refresh
2116 //! \todo how to know the service needs a (auto) refresh????
2119 it->setService(service.alias());
2120 modifyRepository(it->alias(), *it);
2124 //! \todo refresh the service automatically if url is changed?
2127 ////////////////////////////////////////////////////////////////////////////
2129 repo::ServiceType RepoManager::Impl::probeService( const Url & url ) const
2133 MediaSetAccess access(url);
2134 if ( access.doesFileExist("/repo/repoindex.xml") )
2135 return repo::ServiceType::RIS;
2137 catch ( const media::MediaException &e )
2140 // TranslatorExplanation '%s' is an URL
2141 RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2145 catch ( const Exception &e )
2148 // TranslatorExplanation '%s' is an URL
2149 Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2154 return repo::ServiceType::NONE;
2157 ///////////////////////////////////////////////////////////////////
2159 // CLASS NAME : RepoManager
2161 ///////////////////////////////////////////////////////////////////
2163 RepoManager::RepoManager( const RepoManagerOptions & opt )
2164 : _pimpl( new Impl(opt) )
2167 RepoManager::~RepoManager()
2170 bool RepoManager::repoEmpty() const
2171 { return _pimpl->repoEmpty(); }
2173 RepoManager::RepoSizeType RepoManager::repoSize() const
2174 { return _pimpl->repoSize(); }
2176 RepoManager::RepoConstIterator RepoManager::repoBegin() const
2177 { return _pimpl->repoBegin(); }
2179 RepoManager::RepoConstIterator RepoManager::repoEnd() const
2180 { return _pimpl->repoEnd(); }
2182 RepoInfo RepoManager::getRepo( const std::string & alias ) const
2183 { return _pimpl->getRepo( alias ); }
2185 bool RepoManager::hasRepo( const std::string & alias ) const
2186 { return _pimpl->hasRepo( alias ); }
2188 std::string RepoManager::makeStupidAlias( const Url & url_r )
2190 std::string ret( url_r.getScheme() );
2196 std::string host( url_r.getHost() );
2197 if ( ! host.empty() )
2203 static Date::ValueType serial = Date::now();
2204 ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2208 RepoStatus RepoManager::metadataStatus( const RepoInfo & info ) const
2209 { return _pimpl->metadataStatus( info ); }
2211 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata( const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy )
2212 { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2214 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2215 { return _pimpl->metadataPath( info ); }
2217 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2218 { return _pimpl->packagesPath( info ); }
2220 void RepoManager::refreshMetadata( const RepoInfo &info, RawMetadataRefreshPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2221 { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2223 void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2224 { return _pimpl->cleanMetadata( info, progressrcv ); }
2226 void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2227 { return _pimpl->cleanPackages( info, progressrcv ); }
2229 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
2230 { return _pimpl->cacheStatus( info ); }
2232 void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2233 { return _pimpl->buildCache( info, policy, progressrcv ); }
2235 void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2236 { return _pimpl->cleanCache( info, progressrcv ); }
2238 bool RepoManager::isCached( const RepoInfo &info ) const
2239 { return _pimpl->isCached( info ); }
2241 void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2242 { return _pimpl->loadFromCache( info, progressrcv ); }
2244 void RepoManager::cleanCacheDirGarbage( const ProgressData::ReceiverFnc & progressrcv )
2245 { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2247 repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2248 { return _pimpl->probe( url, path ); }
2250 repo::RepoType RepoManager::probe( const Url & url ) const
2251 { return _pimpl->probe( url ); }
2253 void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2254 { return _pimpl->addRepository( info, progressrcv ); }
2256 void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2257 { return _pimpl->addRepositories( url, progressrcv ); }
2259 void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2260 { return _pimpl->removeRepository( info, progressrcv ); }
2262 void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2263 { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2265 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2266 { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2268 RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2269 { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2271 bool RepoManager::serviceEmpty() const
2272 { return _pimpl->serviceEmpty(); }
2274 RepoManager::ServiceSizeType RepoManager::serviceSize() const
2275 { return _pimpl->serviceSize(); }
2277 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
2278 { return _pimpl->serviceBegin(); }
2280 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
2281 { return _pimpl->serviceEnd(); }
2283 ServiceInfo RepoManager::getService( const std::string & alias ) const
2284 { return _pimpl->getService( alias ); }
2286 bool RepoManager::hasService( const std::string & alias ) const
2287 { return _pimpl->hasService( alias ); }
2289 repo::ServiceType RepoManager::probeService( const Url &url ) const
2290 { return _pimpl->probeService( url ); }
2292 void RepoManager::addService( const std::string & alias, const Url& url )
2293 { return _pimpl->addService( alias, url ); }
2295 void RepoManager::addService( const ServiceInfo & service )
2296 { return _pimpl->addService( service ); }
2298 void RepoManager::removeService( const std::string & alias )
2299 { return _pimpl->removeService( alias ); }
2301 void RepoManager::removeService( const ServiceInfo & service )
2302 { return _pimpl->removeService( service ); }
2304 void RepoManager::refreshServices()
2305 { return _pimpl->refreshServices(); }
2307 void RepoManager::refreshService( const std::string & alias )
2308 { return _pimpl->refreshService( alias ); }
2310 void RepoManager::refreshService( const ServiceInfo & service )
2311 { return _pimpl->refreshService( service ); }
2313 void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2314 { return _pimpl->modifyService( oldAlias, service ); }
2316 ////////////////////////////////////////////////////////////////////////////
2318 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2319 { return str << *obj._pimpl; }
2321 /////////////////////////////////////////////////////////////////
2323 ///////////////////////////////////////////////////////////////////