1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/RepoManager.cc
20 #include "zypp/base/InputStream.h"
21 #include "zypp/base/Logger.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/base/Function.h"
24 #include "zypp/base/Regex.h"
25 #include "zypp/PathInfo.h"
26 #include "zypp/TmpPath.h"
27 #include "zypp/Service.h"
29 #include "zypp/repo/RepoException.h"
30 #include "zypp/RepoManager.h"
32 #include "zypp/media/MediaManager.h"
33 #include "zypp/MediaSetAccess.h"
34 #include "zypp/ExternalProgram.h"
35 #include "zypp/ManagedFile.h"
37 #include "zypp/parser/RepoFileReader.h"
38 #include "zypp/parser/ServiceFileReader.h"
39 #include "zypp/parser/RepoindexFileReader.h"
40 #include "zypp/repo/yum/Downloader.h"
41 #include "zypp/parser/yum/RepoParser.h"
42 #include "zypp/repo/susetags/Downloader.h"
43 #include "zypp/parser/susetags/RepoParser.h"
44 #include "zypp/parser/plaindir/RepoParser.h"
46 #include "zypp/ZYppCallbacks.h"
49 #include "satsolver/pool.h"
50 #include "satsolver/repo.h"
51 #include "satsolver/repo_solv.h"
55 using namespace zypp::repo;
56 using namespace zypp::filesystem;
58 using namespace zypp::repo;
60 ///////////////////////////////////////////////////////////////////
62 { /////////////////////////////////////////////////////////////////
64 ///////////////////////////////////////////////////////////////////
66 // CLASS NAME : RepoManagerOptions
68 ///////////////////////////////////////////////////////////////////
70 RepoManagerOptions::RepoManagerOptions( const Pathname & root_r )
72 repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
73 repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
74 repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
75 repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
76 knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
77 knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
78 probe = ZConfig::instance().repo_add_probe();
81 RepoManagerOptions RepoManagerOptions::makeTestSetup( const Pathname & root_r )
83 RepoManagerOptions ret;
84 ret.repoCachePath = root_r;
85 ret.repoRawCachePath = root_r/"raw";
86 ret.repoSolvCachePath = root_r/"solv";
87 ret.repoPackagesCachePath = root_r/"packages";
88 ret.knownReposPath = root_r/"repos.d";
89 ret.knownServicesPath = root_r/"services.d";
93 ////////////////////////////////////////////////////////////////////////////
96 * \short Simple callback to collect the results
98 * Classes like RepoFileParser call the callback
99 * once per each repo in a file.
101 * Passing this functor as callback, you can collect
102 * all resuls at the end, without dealing with async
113 bool collect( const RepoInfo &repo )
115 repos.push_back(repo);
122 ////////////////////////////////////////////////////////////////////////////
125 * Reads RepoInfo's from a repo file.
127 * \param file pathname of the file to read.
129 static std::list<RepoInfo> repositories_in_file( const Pathname & file )
131 MIL << "repo file: " << file << endl;
132 RepoCollector collector;
133 parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
134 return collector.repos;
137 ////////////////////////////////////////////////////////////////////////////
139 std::list<RepoInfo> readRepoFile(const Url & repo_file)
141 // no interface to download a specific file, using workaround:
142 //! \todo add MediaManager::provideFile(Url file_url) to easily access any file URLs? (no need for media access id or media_nr)
144 Pathname path(url.getPathName());
145 url.setPathName ("/");
146 MediaSetAccess access(url);
147 Pathname local = access.provideFile(path);
149 DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
151 return repositories_in_file(local);
154 ////////////////////////////////////////////////////////////////////////////
157 * \short List of RepoInfo's from a directory
159 * Goes trough every file ending with ".repo" in a directory and adds all
160 * RepoInfo's contained in that file.
162 * \param dir pathname of the directory to read.
164 static std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
166 MIL << "directory " << dir << endl;
167 list<RepoInfo> repos;
168 list<Pathname> entries;
169 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
170 ZYPP_THROW(Exception("failed to read directory"));
172 str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
173 for ( list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
175 if (str::regex_match(it->extension(), allowedRepoExt))
177 list<RepoInfo> tmp = repositories_in_file( *it );
178 repos.insert( repos.end(), tmp.begin(), tmp.end() );
180 //std::copy( collector.repos.begin(), collector.repos.end(), std::back_inserter(repos));
181 //MIL << "ok" << endl;
187 ////////////////////////////////////////////////////////////////////////////
189 static void assert_alias( const RepoInfo &info )
191 if (info.alias().empty())
192 ZYPP_THROW(RepoNoAliasException());
195 ////////////////////////////////////////////////////////////////////////////
197 static void assert_urls( const RepoInfo &info )
199 if (info.baseUrlsEmpty())
200 ZYPP_THROW(RepoNoUrlException());
203 ////////////////////////////////////////////////////////////////////////////
206 * \short Calculates the raw cache path for a repository
208 static Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
211 return opt.repoRawCachePath / info.escaped_alias();
215 * \short Calculates the packages cache path for a repository
217 static Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
220 return opt.repoPackagesCachePath / info.escaped_alias();
223 static Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
226 return opt.repoSolvCachePath / info.escaped_alias();
229 ///////////////////////////////////////////////////////////////////
231 // CLASS NAME : RepoManager::Impl
233 ///////////////////////////////////////////////////////////////////
236 * \short RepoManager implementation.
238 struct RepoManager::Impl
240 Impl( const RepoManagerOptions &opt )
253 RepoManagerOptions options;
260 /** Offer default Impl. */
261 static shared_ptr<Impl> nullimpl()
263 static shared_ptr<Impl> _nullimpl( new Impl );
267 void saveService( const Service& service ) const;
269 Pathname generateNonExistingName( const Pathname &dir,
270 const std::string &basefilename ) const;
272 std::string generateFilename( const RepoInfo &info ) const;
273 std::string generateFilename( const Service &info ) const;
275 struct ServiceCollector {
276 ServiceCollector(ServiceSet& services_) : services(services_) {}
277 bool collect(Service service) { services.insert(service); return true; }
279 ServiceSet& services;
282 void knownServices();
284 void knownRepositories();
287 friend Impl * rwcowClone<Impl>( const Impl * rhs );
288 /** clone for RWCOW_pointer */
290 { return new Impl( *this ); }
293 ///////////////////////////////////////////////////////////////////
295 /** \relates RepoManager::Impl Stream output */
296 inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
298 return str << "RepoManager::Impl";
301 ///////////////////////////////////////////////////////////////////
303 // CLASS NAME : RepoManager
305 ///////////////////////////////////////////////////////////////////
307 RepoManager::RepoManager( const RepoManagerOptions &opt )
308 : _pimpl( new Impl(opt) )
311 ////////////////////////////////////////////////////////////////////////////
313 RepoManager::~RepoManager()
316 ////////////////////////////////////////////////////////////////////////////
318 bool RepoManager::repoEmpty() const { return _pimpl->repos.empty(); }
319 RepoManager::RepoSizeType RepoManager::repoSize() const
320 { return _pimpl->repos.size(); }
321 RepoManager::RepoConstIterator RepoManager::repoBegin() const
322 { return _pimpl->repos.begin(); }
323 RepoManager::RepoConstIterator RepoManager::repoEnd() const
324 { return _pimpl->repos.end(); }
327 std::list<RepoInfo> RepoManager::knownRepositories() const
329 return std::list<RepoInfo>(repoBegin(),repoEnd());
332 void RepoManager::Impl::knownRepositories()
334 MIL << "start construct known repos" << endl;
336 if ( PathInfo(options.knownReposPath).isExist() )
338 RepoInfoList repol = repositories_in_dir(options.knownReposPath);
339 for ( RepoInfoList::iterator it = repol.begin();
343 // set the metadata path for the repo
344 Pathname metadata_path = rawcache_path_for_repoinfo(options, (*it));
345 (*it).setMetadataPath(metadata_path);
347 // set the downloaded packages path for the repo
348 Pathname packages_path = packagescache_path_for_repoinfo(options, (*it));
349 (*it).setPackagesPath(packages_path);
355 MIL << "end construct known repos" << endl;
358 ////////////////////////////////////////////////////////////////////////////
360 Pathname RepoManager::metadataPath( const RepoInfo &info ) const
362 return rawcache_path_for_repoinfo(_pimpl->options, info );
365 Pathname RepoManager::packagesPath( const RepoInfo &info ) const
367 return packagescache_path_for_repoinfo(_pimpl->options, info );
370 ////////////////////////////////////////////////////////////////////////////
372 RepoStatus RepoManager::metadataStatus( const RepoInfo &info ) const
374 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
375 RepoType repokind = info.type();
378 switch ( repokind.toEnum() )
380 case RepoType::NONE_e:
381 // unknown, probe the local metadata
382 repokind = probe(rawpath.asUrl());
388 switch ( repokind.toEnum() )
390 case RepoType::RPMMD_e :
392 status = RepoStatus( rawpath + "/repodata/repomd.xml");
396 case RepoType::YAST2_e :
398 status = RepoStatus( rawpath + "/content") && (RepoStatus( rawpath + "/media.1/media"));
402 case RepoType::RPMPLAINDIR_e :
404 if ( PathInfo(Pathname(rawpath + "/cookie")).isExist() )
405 status = RepoStatus( rawpath + "/cookie");
409 case RepoType::NONE_e :
410 // Return default RepoStatus in case of RepoType::NONE
411 // indicating it should be created?
412 // ZYPP_THROW(RepoUnknownTypeException());
418 void RepoManager::touchIndexFile(const RepoInfo & info)
420 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
422 RepoType repokind = info.type();
423 if ( repokind.toEnum() == RepoType::NONE_e )
424 // unknown, probe the local metadata
425 repokind = probe(rawpath.asUrl());
426 // if still unknown, just return
427 if (repokind == RepoType::NONE_e)
431 switch ( repokind.toEnum() )
433 case RepoType::RPMMD_e :
434 p = Pathname(rawpath + "/repodata/repomd.xml");
437 case RepoType::YAST2_e :
438 p = Pathname(rawpath + "/content");
441 case RepoType::RPMPLAINDIR_e :
442 p = Pathname(rawpath + "/cookie");
445 case RepoType::NONE_e :
450 // touch the file, ignore error (they are logged anyway)
451 filesystem::touch(p);
454 RepoManager::RefreshCheckStatus RepoManager::checkIfToRefreshMetadata(
455 const RepoInfo &info,
457 RawMetadataRefreshPolicy policy )
461 RepoStatus oldstatus;
462 RepoStatus newstatus;
466 MIL << "Going to try to check whether refresh is needed for " << url << endl;
468 repo::RepoType repokind = info.type();
470 // if the type is unknown, try probing.
471 switch ( repokind.toEnum() )
473 case RepoType::NONE_e:
475 repokind = probe(url);
481 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
482 filesystem::assert_dir(rawpath);
483 oldstatus = metadataStatus(info);
485 // now we've got the old (cached) status, we can decide repo.refresh.delay
486 if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
488 // difference in seconds
489 double diff = difftime(
490 (Date::ValueType)Date::now(),
491 (Date::ValueType)oldstatus.timestamp()) / 60;
493 DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
494 DBG << "current time: " << (Date::ValueType)Date::now() << endl;
495 DBG << "last refresh = " << diff << " minutes ago" << endl;
497 if (diff < ZConfig::instance().repo_refresh_delay())
499 MIL << "Repository '" << info.alias()
500 << "' has been refreshed less than repo.refresh.delay ("
501 << ZConfig::instance().repo_refresh_delay()
502 << ") minutes ago. Advising to skip refresh" << endl;
503 return REPO_CHECK_DELAYED;
507 // create temp dir as sibling of rawpath
508 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
510 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
511 ( repokind.toEnum() == RepoType::YAST2_e ) )
513 MediaSetAccess media(url);
514 shared_ptr<repo::Downloader> downloader_ptr;
516 if ( repokind.toEnum() == RepoType::RPMMD_e )
517 downloader_ptr.reset(new yum::Downloader(info.path()));
519 downloader_ptr.reset( new susetags::Downloader(info.path()));
521 RepoStatus newstatus = downloader_ptr->status(media);
522 bool refresh = false;
523 if ( oldstatus.checksum() == newstatus.checksum() )
525 MIL << "repo has not changed" << endl;
526 if ( policy == RefreshForced )
528 MIL << "refresh set to forced" << endl;
534 MIL << "repo has changed, going to refresh" << endl;
539 touchIndexFile(info);
541 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
543 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
545 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
546 bool refresh = false;
547 if ( oldstatus.checksum() == newstatus.checksum() )
549 MIL << "repo has not changed" << endl;
550 if ( policy == RefreshForced )
552 MIL << "refresh set to forced" << endl;
558 MIL << "repo has changed, going to refresh" << endl;
563 touchIndexFile(info);
565 return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
569 ZYPP_THROW(RepoUnknownTypeException(info));
572 catch ( const Exception &e )
575 ERR << "refresh check failed for " << url << endl;
579 return REFRESH_NEEDED; // default
582 void RepoManager::refreshMetadata( const RepoInfo &info,
583 RawMetadataRefreshPolicy policy,
584 const ProgressData::ReceiverFnc & progress )
589 // we will throw this later if no URL checks out fine
590 RepoException rexception(_("Valid metadata not found at specified URL(s)"));
592 // try urls one by one
593 for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
599 // check whether to refresh metadata
600 // if the check fails for this url, it throws, so another url will be checked
601 if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
604 MIL << "Going to refresh metadata from " << url << endl;
606 repo::RepoType repokind = info.type();
608 // if the type is unknown, try probing.
609 switch ( repokind.toEnum() )
611 case RepoType::NONE_e:
613 repokind = probe(*it);
615 if (repokind.toEnum() != RepoType::NONE_e)
617 // Adjust the probed type in RepoInfo
618 info.setProbedType( repokind ); // lazy init!
619 //save probed type only for repos in system
620 for_( it, repoBegin(), repoEnd() )
622 if ( info.alias() == (*it).alias() )
624 RepoInfo modifiedrepo = info;
625 modifiedrepo.setType(repokind);
626 modifyRepository(info.alias(),modifiedrepo);
635 Pathname rawpath = rawcache_path_for_repoinfo( _pimpl->options, info );
636 filesystem::assert_dir(rawpath);
638 // create temp dir as sibling of rawpath
639 filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( rawpath ) );
641 if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
642 ( repokind.toEnum() == RepoType::YAST2_e ) )
644 MediaSetAccess media(url);
645 shared_ptr<repo::Downloader> downloader_ptr;
647 if ( repokind.toEnum() == RepoType::RPMMD_e )
648 downloader_ptr.reset(new yum::Downloader(info.path()));
650 downloader_ptr.reset( new susetags::Downloader(info.path()));
653 * Given a downloader, sets the other repos raw metadata
654 * path as cache paths for the fetcher, so if another
655 * repo has the same file, it will not download it
656 * but copy it from the other repository
658 for_( it, repoBegin(), repoEnd() )
660 Pathname cachepath(rawcache_path_for_repoinfo( _pimpl->options, *it ));
661 if ( PathInfo(cachepath).isExist() )
662 downloader_ptr->addCachePath(cachepath);
665 downloader_ptr->download( media, tmpdir.path());
667 else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
669 RepoStatus newstatus = parser::plaindir::dirStatus(url.getPathName());
671 std::ofstream file(( tmpdir.path() + "/cookie").c_str());
673 ZYPP_THROW (Exception( "Can't open " + tmpdir.path().asString() + "/cookie" ) );
676 file << newstatus.checksum() << endl;
682 ZYPP_THROW(RepoUnknownTypeException());
685 // ok we have the metadata, now exchange
688 TmpDir oldmetadata( TmpDir::makeSibling( rawpath ) );
689 filesystem::rename( rawpath, oldmetadata.path() );
690 // move the just downloaded there
691 filesystem::rename( tmpdir.path(), rawpath );
696 catch ( const Exception &e )
699 ERR << "Trying another url..." << endl;
701 // remember the exception caught for the *first URL*
702 // if all other URLs fail, the rexception will be thrown with the
703 // cause of the problem of the first URL remembered
704 if (it == info.baseUrlsBegin())
705 rexception.remember(e);
708 ERR << "No more urls..." << endl;
709 ZYPP_THROW(rexception);
712 ////////////////////////////////////////////////////////////////////////////
714 void RepoManager::cleanMetadata( const RepoInfo &info,
715 const ProgressData::ReceiverFnc & progressfnc )
717 ProgressData progress(100);
718 progress.sendTo(progressfnc);
720 filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_pimpl->options, info));
724 void RepoManager::cleanPackages( const RepoInfo &info,
725 const ProgressData::ReceiverFnc & progressfnc )
727 ProgressData progress(100);
728 progress.sendTo(progressfnc);
730 filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_pimpl->options, info));
734 void RepoManager::buildCache( const RepoInfo &info,
735 CacheBuildPolicy policy,
736 const ProgressData::ReceiverFnc & progressrcv )
739 Pathname rawpath = rawcache_path_for_repoinfo(_pimpl->options, info);
741 filesystem::assert_dir(_pimpl->options.repoCachePath);
742 RepoStatus raw_metadata_status = metadataStatus(info);
743 if ( raw_metadata_status.empty() )
745 /* if there is no cache at this point, we refresh the raw
746 in case this is the first time - if it's !autorefresh,
747 we may still refresh */
748 refreshMetadata(info, RefreshIfNeeded, progressrcv );
749 raw_metadata_status = metadataStatus(info);
752 bool needs_cleaning = false;
753 if ( isCached( info ) )
755 MIL << info.alias() << " is already cached." << endl;
756 //data::RecordId id = store.lookupRepository(info.alias());
757 RepoStatus cache_status = cacheStatus(info);
759 if ( cache_status.checksum() == raw_metadata_status.checksum() )
761 MIL << info.alias() << " cache is up to date with metadata." << endl;
762 if ( policy == BuildIfNeeded ) {
766 MIL << info.alias() << " cache rebuild is forced" << endl;
770 needs_cleaning = true;
773 ProgressData progress(100);
774 callback::SendReport<ProgressReport> report;
775 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
776 progress.name(str::form(_("Building repository '%s' cache"), info.name().c_str()));
784 MIL << info.alias() << " building cache..." << endl;
786 Pathname base = solv_path_for_repoinfo( _pimpl->options, info);
787 filesystem::assert_dir(base);
788 Pathname solvfile = base / "solv";
791 repo::RepoType repokind = info.type();
793 // if the type is unknown, try probing.
794 switch ( repokind.toEnum() )
796 case RepoType::NONE_e:
797 // unknown, probe the local metadata
798 repokind = probe(rawpath.asUrl());
804 MIL << "repo type is " << repokind << endl;
806 switch ( repokind.toEnum() )
808 case RepoType::RPMMD_e :
809 case RepoType::YAST2_e :
810 case RepoType::RPMPLAINDIR_e :
812 // Take care we unlink the solvfile on exception
813 ManagedFile guard( solvfile, filesystem::unlink );
816 std::string toFile( str::gsub(solvfile.asString(),"\"","\\\"") );
817 if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
819 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"",
820 str::gsub( info.baseUrlsBegin()->getPathName(),"\"","\\\"" ).c_str(),
825 cmd << str::form( "repo2solv.sh \"%s\" > \"%s\"",
826 str::gsub( rawpath.asString(),"\"","\\\"" ).c_str(),
829 MIL << "Executing: " << cmd.str() << endl;
830 ExternalProgram prog( cmd.str(), ExternalProgram::Stderr_To_Stdout );
833 for ( string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
834 WAR << " " << output;
835 cmd << " " << output;
838 int ret = prog.close();
841 RepoException ex(str::form("Failed to cache repo (%d).", ret));
842 ex.remember( cmd.str() );
847 guard.resetDispose();
851 ZYPP_THROW(RepoUnknownTypeException("Unhandled repository type"));
855 switch ( repokind.toEnum() )
857 case RepoType::RPMMD_e :
860 CombinedProgressData subprogrcv( progress, 100);
861 parser::yum::RepoParser parser(id, store, parser::yum::RepoParserOpts(), subprogrcv);
862 parser.parse(rawpath);
866 case RepoType::YAST2_e :
869 CombinedProgressData subprogrcv( progress, 100);
870 parser::susetags::RepoParser parser(id, store, subprogrcv);
871 parser.parse(rawpath);
877 ZYPP_THROW(RepoUnknownTypeException());
880 // update timestamp and checksum
881 //store.updateRepositoryStatus(id, raw_metadata_status);
882 setCacheStatus(info, raw_metadata_status);
883 MIL << "Commit cache.." << endl;
888 ////////////////////////////////////////////////////////////////////////////
890 repo::RepoType RepoManager::probe( const Url &url ) const
892 if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName() ).isDir() )
894 // Handle non existing local directory in advance, as
895 // MediaSetAccess does not support it.
896 return repo::RepoType::NONE;
901 MediaSetAccess access(url);
902 if ( access.doesFileExist("/repodata/repomd.xml") )
903 return repo::RepoType::RPMMD;
904 if ( access.doesFileExist("/content") )
905 return repo::RepoType::YAST2;
907 // if it is a local url of type dir
908 if ( (! media::MediaManager::downloads(url)) && ( url.getScheme() == "dir" ) )
910 Pathname path = Pathname(url.getPathName());
911 if ( PathInfo(path).isDir() )
913 // allow empty dirs for now
914 return repo::RepoType::RPMPLAINDIR;
918 catch ( const media::MediaException &e )
921 RepoException enew("Error trying to read from " + url.asString());
925 catch ( const Exception &e )
928 Exception enew("Unknown error reading from " + url.asString());
933 return repo::RepoType::NONE;
936 ////////////////////////////////////////////////////////////////////////////
938 void RepoManager::cleanCache( const RepoInfo &info,
939 const ProgressData::ReceiverFnc & progressrcv )
941 ProgressData progress(100);
942 progress.sendTo(progressrcv);
945 filesystem::recursive_rmdir(solv_path_for_repoinfo(_pimpl->options, info));
950 ////////////////////////////////////////////////////////////////////////////
952 bool RepoManager::isCached( const RepoInfo &info ) const
954 return PathInfo(solv_path_for_repoinfo( _pimpl->options, info ) / "solv").isExist();
957 RepoStatus RepoManager::cacheStatus( const RepoInfo &info ) const
960 Pathname cookiefile = solv_path_for_repoinfo(_pimpl->options, info) / "cookie";
962 return RepoStatus::fromCookieFile(cookiefile);
965 void RepoManager::setCacheStatus( const RepoInfo &info, const RepoStatus &status )
967 Pathname base = solv_path_for_repoinfo(_pimpl->options, info);
968 filesystem::assert_dir(base);
969 Pathname cookiefile = base / "cookie";
971 status.saveToCookieFile(cookiefile);
974 void RepoManager::loadFromCache( const RepoInfo & info,
975 const ProgressData::ReceiverFnc & progressrcv )
978 Pathname solvfile = solv_path_for_repoinfo(_pimpl->options, info) / "solv";
980 if ( ! PathInfo(solvfile).isExist() )
981 ZYPP_THROW(RepoNotCachedException(info));
985 sat::Pool::instance().addRepoSolv( solvfile, info );
987 catch ( const Exception & exp )
990 MIL << "Try to handle exception by rebuilding the solv-file" << endl;
991 cleanCache( info, progressrcv );
992 buildCache( info, BuildIfNeeded, progressrcv );
994 sat::Pool::instance().addRepoSolv( solvfile, info );
998 ////////////////////////////////////////////////////////////////////////////
1001 * Generate a non existing filename in a directory, using a base
1002 * name. For example if a directory contains 3 files
1008 * If you try to generate a unique filename for this directory,
1009 * based on "ruu" you will get "ruu", but if you use the base
1010 * "foo" you will get "foo_1"
1012 * \param dir Directory where the file needs to be unique
1013 * \param basefilename string to base the filename on.
1015 Pathname RepoManager::Impl::generateNonExistingName( const Pathname &dir,
1016 const std::string &basefilename ) const
1018 string final_filename = basefilename;
1020 while ( PathInfo(dir + final_filename).isExist() )
1022 final_filename = basefilename + "_" + str::numstring(counter);
1025 return dir + Pathname(final_filename);
1028 ////////////////////////////////////////////////////////////////////////////
1031 * \short Generate a related filename from a repo info
1033 * From a repo info, it will try to use the alias as a filename
1034 * escaping it if necessary. Other fallbacks can be added to
1035 * this function in case there is no way to use the alias
1037 std::string RepoManager::Impl::generateFilename( const RepoInfo &info ) const
1039 std::string filename = info.alias();
1040 // replace slashes with underscores
1041 str::replaceAll( filename, "/", "_" );
1043 filename = Pathname(filename).extend(".repo").asString();
1044 MIL << "generating filename for repo [" << info.alias() << "] : '" << filename << "'" << endl;
1048 std::string RepoManager::Impl::generateFilename( const Service &info ) const
1050 std::string filename = info.name();
1051 // replace slashes with underscores
1052 str::replaceAll( filename, "/", "_" );
1054 filename = Pathname(filename).extend(".service").asString();
1055 MIL << "generating filename for service [" << info.name() << "] : '" << filename << "'" << endl;
1059 ////////////////////////////////////////////////////////////////////////////
1061 void RepoManager::addRepository( const RepoInfo &info,
1062 const ProgressData::ReceiverFnc & progressrcv )
1066 ProgressData progress(100);
1067 callback::SendReport<ProgressReport> report;
1068 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1069 progress.name(str::form(_("Adding repository '%s'"), info.name().c_str()));
1072 RepoInfo tosave = info;
1073 if(_pimpl->repos.find(tosave)!= _pimpl->repos.end())
1074 ZYPP_THROW(RepoAlreadyExistsException(info));
1077 // check the first url for now
1078 if ( _pimpl->options.probe )
1080 DBG << "unknown repository type, probing" << endl;
1082 RepoType probedtype;
1083 probedtype = probe(*tosave.baseUrlsBegin());
1084 if ( tosave.baseUrlsSize() > 0 )
1086 if ( probedtype == RepoType::NONE )
1087 ZYPP_THROW(RepoUnknownTypeException());
1089 tosave.setType(probedtype);
1095 // assert the directory exists
1096 filesystem::assert_dir(_pimpl->options.knownReposPath);
1098 Pathname repofile = _pimpl->generateNonExistingName(
1099 _pimpl->options.knownReposPath, _pimpl->generateFilename(tosave));
1100 // now we have a filename that does not exists
1101 MIL << "Saving repo in " << repofile << endl;
1103 std::ofstream file(repofile.c_str());
1105 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1108 tosave.dumpRepoOn(file);
1109 tosave.setFilepath(repofile);
1110 _pimpl->repos.insert(tosave);
1112 MIL << "done" << endl;
1115 void RepoManager::addRepositories( const Url &url,
1116 const ProgressData::ReceiverFnc & progressrcv )
1118 std::list<RepoInfo> repos = readRepoFile(url);
1119 for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1123 // look if the alias is in the known repos.
1124 for_ ( kit, repoBegin(), repoEnd() )
1126 if ( (*it).alias() == (*kit).alias() )
1128 ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1129 ZYPP_THROW(RepoAlreadyExistsException(*it));
1134 string filename = Pathname(url.getPathName()).basename();
1136 if ( filename == Pathname() )
1137 ZYPP_THROW(RepoException("Invalid repo file name at " + url.asString() ));
1139 // assert the directory exists
1140 filesystem::assert_dir(_pimpl->options.knownReposPath);
1142 Pathname repofile = _pimpl->generateNonExistingName(_pimpl->options.knownReposPath, filename);
1143 // now we have a filename that does not exists
1144 MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1146 std::ofstream file(repofile.c_str());
1148 ZYPP_THROW (Exception( "Can't open " + repofile.asString() ) );
1151 for ( std::list<RepoInfo>::iterator it = repos.begin();
1155 MIL << "Saving " << (*it).alias() << endl;
1156 it->setFilepath(repofile.asString());
1157 it->dumpRepoOn(file);
1158 _pimpl->repos.insert(*it);
1160 MIL << "done" << endl;
1163 ////////////////////////////////////////////////////////////////////////////
1165 void RepoManager::removeRepository( const RepoInfo & info,
1166 const ProgressData::ReceiverFnc & progressrcv)
1168 ProgressData progress;
1169 callback::SendReport<ProgressReport> report;
1170 progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1171 progress.name(str::form(_("Removing repository '%s'"), info.name().c_str()));
1173 MIL << "Going to delete repo " << info.alias() << endl;
1175 for_( it, repoBegin(), repoEnd() )
1177 // they can be the same only if the provided is empty, that means
1178 // the provided repo has no alias
1180 if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1183 // TODO match by url
1185 // we have a matcing repository, now we need to know
1186 // where it does come from.
1187 RepoInfo todelete = *it;
1188 if (todelete.filepath().empty())
1190 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1194 // figure how many repos are there in the file:
1195 std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1196 if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1198 // easy, only this one, just delete the file
1199 if ( filesystem::unlink(todelete.filepath()) != 0 )
1201 ZYPP_THROW(RepoException("Can't delete " + todelete.filepath().asString()));
1203 MIL << todelete.alias() << " sucessfully deleted." << endl;
1207 // there are more repos in the same file
1208 // write them back except the deleted one.
1210 //std::ofstream file(tmp.path().c_str());
1212 // assert the directory exists
1213 filesystem::assert_dir(todelete.filepath().dirname());
1215 std::ofstream file(todelete.filepath().c_str());
1217 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1218 ZYPP_THROW (Exception( "Can't open " + todelete.filepath().asString() ) );
1220 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1221 fit != filerepos.end();
1224 if ( (*fit).alias() != todelete.alias() )
1225 (*fit).dumpRepoOn(file);
1229 CombinedProgressData subprogrcv(progress, 70);
1230 CombinedProgressData cleansubprogrcv(progress, 30);
1231 // now delete it from cache
1232 if ( isCached(todelete) )
1233 cleanCache( todelete, subprogrcv);
1234 // now delete metadata (#301037)
1235 cleanMetadata( todelete, cleansubprogrcv);
1236 _pimpl->repos.erase(todelete);
1237 MIL << todelete.alias() << " sucessfully deleted." << endl;
1239 } // else filepath is empty
1242 // should not be reached on a sucess workflow
1243 ZYPP_THROW(RepoNotFoundException(info));
1246 ////////////////////////////////////////////////////////////////////////////
1248 void RepoManager::modifyRepository( const std::string &alias,
1249 const RepoInfo & newinfo,
1250 const ProgressData::ReceiverFnc & progressrcv )
1252 RepoInfo toedit = getRepositoryInfo(alias);
1254 // check if the new alias already exists when renaming the repo
1255 if (alias != newinfo.alias())
1257 for_( it, repoBegin(), repoEnd() )
1259 if ( newinfo.alias() == (*it).alias() )
1260 ZYPP_THROW(RepoAlreadyExistsException(newinfo));
1264 if (toedit.filepath().empty())
1266 ZYPP_THROW(RepoException("Can't figure where the repo is stored"));
1270 // figure how many repos are there in the file:
1271 std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1273 // there are more repos in the same file
1274 // write them back except the deleted one.
1276 //std::ofstream file(tmp.path().c_str());
1278 // assert the directory exists
1279 filesystem::assert_dir(toedit.filepath().dirname());
1281 std::ofstream file(toedit.filepath().c_str());
1283 //ZYPP_THROW (Exception( "Can't open " + tmp.path().asString() ) );
1284 ZYPP_THROW (Exception( "Can't open " + toedit.filepath().asString() ) );
1286 for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1287 fit != filerepos.end();
1290 // if the alias is different, dump the original
1291 // if it is the same, dump the provided one
1292 if ( (*fit).alias() != toedit.alias() )
1293 (*fit).dumpRepoOn(file);
1295 newinfo.dumpRepoOn(file);
1298 _pimpl->repos.erase(toedit);
1299 _pimpl->repos.insert(newinfo);
1303 ////////////////////////////////////////////////////////////////////////////
1305 RepoInfo RepoManager::getRepositoryInfo( const std::string &alias,
1306 const ProgressData::ReceiverFnc & progressrcv )
1309 info.setAlias(info.alias());
1310 RepoConstIterator it = _pimpl->repos.find( info );
1311 if( it == repoEnd() )
1312 ZYPP_THROW(RepoNotFoundException(info));
1317 ////////////////////////////////////////////////////////////////////////////
1319 RepoInfo RepoManager::getRepositoryInfo( const Url & url,
1320 const url::ViewOption & urlview,
1321 const ProgressData::ReceiverFnc & progressrcv )
1323 for_( it, repoBegin(), repoEnd() )
1325 for(RepoInfo::urls_const_iterator urlit = (*it).baseUrlsBegin();
1326 urlit != (*it).baseUrlsEnd();
1329 if ((*urlit).asString(urlview) == url.asString(urlview))
1334 info.setBaseUrl(url);
1335 ZYPP_THROW(RepoNotFoundException(info));
1338 void RepoManager::addService( const std::string& name, const Url& url )
1340 addService( Service(name,url) );
1343 void RepoManager::addService( const Service& service )
1345 //check if service isn't already exist
1346 if( _pimpl->services.find(service)!= _pimpl->services.end() )
1347 return; //TODO throw exception
1349 const Service& savedService = *(_pimpl->services.insert( service )).first;
1351 _pimpl->saveService( savedService );
1354 void RepoManager::removeService( const string& name)
1356 MIL << "Going to delete repo " << name << endl;
1358 const Service& service = getService( name );
1360 Pathname location = service.location();
1361 if( location.empty() )
1363 ZYPP_THROW(RepoException("Can't figure where the service is stored"));
1367 Impl::ServiceCollector collector(tmpSet);
1369 parser::ServiceFileReader reader( location,
1370 bind(&Impl::ServiceCollector::collect,collector,_1) );
1372 if ( tmpSet.size() == 1 ) //only one record
1374 if ( filesystem::unlink(location) != 0 )
1376 ZYPP_THROW(RepoException("Can't delete " + location.asString()));
1378 MIL << name << " sucessfully deleted." << endl;
1382 filesystem::assert_dir(location.dirname());
1384 std::ofstream file(location.c_str());
1386 for_(it, tmpSet.begin(), tmpSet.end())
1388 if( it->name() != name )
1389 it->dumpServiceOn(file);
1393 //now remove all repositories added by this service
1394 getRepositoriesInService( name,
1395 boost::make_function_output_iterator(bind(&RepoManager::removeRepository, this, _1, ProgressData::ReceiverFnc()) ) );
1399 void RepoManager::Impl::saveService( const Service& service ) const
1401 filesystem::assert_dir( options.knownServicesPath );
1403 Pathname servfile = generateNonExistingName( options.knownServicesPath,
1404 generateFilename( service ) );
1406 MIL << "saving service in " << servfile << endl;
1408 std::ofstream file(servfile.c_str());
1410 ZYPP_THROW (Exception( "Can't open " + servfile.asString() ) );
1413 service.dumpServiceOn( file );
1415 const_cast<Service&>(service).setLocation( servfile );
1416 MIL << "done" << endl;
1419 const Service& RepoManager::getService( const std::string& name ) const
1421 //little trick for Set, because it is sorted by Service name
1422 Service tmpServ(name);
1424 ServiceConstIterator it = _pimpl->services.find(name);
1425 if ( it == serviceEnd() )
1426 return Service::noService;
1431 bool RepoManager::serviceEmpty() const { return _pimpl->services.empty(); }
1433 RepoManager::ServiceSizeType RepoManager::serviceSize() const
1435 return _pimpl->services.size();
1438 RepoManager::ServiceConstIterator RepoManager::serviceBegin() const
1440 return _pimpl->services.begin();
1443 RepoManager::ServiceConstIterator RepoManager::serviceEnd() const
1445 return _pimpl->services.end();
1448 void RepoManager::refreshServices()
1450 //cannot user for_, because it uses const version
1451 for (std::set<Service>::iterator it = _pimpl->services.begin();
1452 it != _pimpl->services.end(); ++it)
1454 MIL << "refresh: "<<it->name() << " with url: "<< it->url().asString() << endl;
1455 refreshService(*it);
1459 void RepoManager::refreshService( const Service& service )
1461 //download index file
1462 media::MediaManager mediamanager;
1463 media::MediaAccessId mid = mediamanager.open( service.url() );
1464 mediamanager.attachDesiredMedia( mid );
1465 mediamanager.provideFile( mid, "repo/repoindex.xml" );
1466 Pathname path = mediamanager.localPath(mid, "repo/repoindex.xml" );
1469 RepoCollector collector;
1470 parser::RepoindexFileReader reader( path,
1471 bind( &RepoCollector::collect, &collector, _1 ) );
1472 mediamanager.release( mid );
1473 mediamanager.close( mid );
1475 // set base url for all collected repositories
1476 for_( it, collector.repos.begin(), collector.repos.end())
1478 it->setBaseUrl( service.url() );
1479 it->setService(service.name());
1482 //compare old and new repositories (hope not to much, if it change
1483 // then construct set and use set operation on it)
1485 std::list<RepoInfo> oldRepos;
1486 getRepositoriesInService(service.name(),
1487 insert_iterator<std::list<RepoInfo> >
1488 (oldRepos,oldRepos.begin()));
1490 //find old to remove
1491 for_( it, oldRepos.begin(), oldRepos.end() )
1495 for_( it2, collector.repos.begin(), collector.repos.end() )
1496 if ( it->alias() == it2->alias() )
1503 removeRepository( *it );
1507 for_( it, collector.repos.begin(), collector.repos.end() )
1511 for_( it2, oldRepos.begin(), oldRepos.end() )
1512 if( it->alias() == it2->alias() )
1519 addRepository( *it );
1524 void RepoManager::modifyService(const std::string& oldName, const Service& service)
1526 MIL << "Going to modify service " << oldName << endl;
1528 const Service& oldService = getService(oldName);
1530 Pathname location = oldService.location();
1531 if( location.empty() )
1533 ZYPP_THROW(RepoException("Can't figure where the service is stored"));
1537 Impl::ServiceCollector collector(tmpSet);
1539 parser::ServiceFileReader reader( location,
1540 bind(&Impl::ServiceCollector::collect,collector,_1) );
1542 filesystem::assert_dir(location.dirname());
1544 std::ofstream file(location.c_str());
1546 for_(it, tmpSet.begin(), tmpSet.end())
1548 if( *it != oldName )
1549 it->dumpServiceOn(file);
1552 service.dumpServiceOn(file);
1556 _pimpl->services.erase(oldName);
1557 _pimpl->services.insert(service);
1559 if( oldName != service.name() ) //changed name, must change also repository
1561 std::vector<RepoInfo> toModify;
1562 getRepositoriesInService(oldName,
1563 insert_iterator<std::vector<RepoInfo> >( toModify, toModify.begin() ));
1564 for_( it, toModify.begin(), toModify.end() )
1566 it->setService(service.name());
1567 modifyRepository(it->alias(), *it);
1573 void RepoManager::Impl::knownServices()
1575 ServiceCollector collector(services);
1576 Pathname dir = options.knownServicesPath;
1577 list<Pathname> entries;
1579 if ( filesystem::readdir( entries, Pathname(dir), false ) != 0 )
1580 ZYPP_THROW(Exception("failed to read directory"));
1582 str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
1583 for_(it, entries.begin(), entries.end() )
1585 parser::ServiceFileReader reader(*it,
1586 bind(&ServiceCollector::collect, collector, _1) );
1590 ////////////////////////////////////////////////////////////////////////////
1592 std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
1594 return str << *obj._pimpl;
1597 /////////////////////////////////////////////////////////////////
1599 ///////////////////////////////////////////////////////////////////