libzypp  16.6.1
RepoManager.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
13 #include <cstdlib>
14 #include <iostream>
15 #include <fstream>
16 #include <sstream>
17 #include <list>
18 #include <map>
19 #include <algorithm>
20 
21 #include <solv/solvversion.h>
22 
23 #include "zypp/base/InputStream.h"
24 #include "zypp/base/LogTools.h"
25 #include "zypp/base/Gettext.h"
27 #include "zypp/base/Function.h"
28 #include "zypp/base/Regex.h"
29 #include "zypp/PathInfo.h"
30 #include "zypp/TmpPath.h"
31 
32 #include "zypp/ServiceInfo.h"
34 #include "zypp/RepoManager.h"
35 
38 #include "zypp/MediaSetAccess.h"
39 #include "zypp/ExternalProgram.h"
40 #include "zypp/ManagedFile.h"
41 
44 #include "zypp/repo/ServiceRepos.h"
48 
49 #include "zypp/Target.h" // for Target::targetDistribution() for repo index services
50 #include "zypp/ZYppFactory.h" // to get the Target from ZYpp instance
51 #include "zypp/HistoryLog.h" // to write history :O)
52 
53 #include "zypp/ZYppCallbacks.h"
54 
55 #include "sat/Pool.h"
56 
57 using std::endl;
58 using std::string;
59 using namespace zypp::repo;
60 
61 #define OPT_PROGRESS const ProgressData::ReceiverFnc & = ProgressData::ReceiverFnc()
62 
64 namespace zypp
65 {
67  namespace
68  {
90  class UrlCredentialExtractor
91  {
92  public:
93  UrlCredentialExtractor( Pathname & root_r )
94  : _root( root_r )
95  {}
96 
97  ~UrlCredentialExtractor()
98  { if ( _cmPtr ) _cmPtr->save(); }
99 
101  bool collect( const Url & url_r )
102  {
103  bool ret = url_r.hasCredentialsInAuthority();
104  if ( ret )
105  {
106  if ( !_cmPtr ) _cmPtr.reset( new media::CredentialManager( _root ) );
107  _cmPtr->addUserCred( url_r );
108  }
109  return ret;
110  }
112  template<class TContainer>
113  bool collect( const TContainer & urls_r )
114  { bool ret = false; for ( const Url & url : urls_r ) { if ( collect( url ) && !ret ) ret = true; } return ret; }
115 
117  bool extract( Url & url_r )
118  {
119  bool ret = collect( url_r );
120  if ( ret )
121  url_r.setPassword( std::string() );
122  return ret;
123  }
125  template<class TContainer>
126  bool extract( TContainer & urls_r )
127  { bool ret = false; for ( Url & url : urls_r ) { if ( extract( url ) && !ret ) ret = true; } return ret; }
128 
129  private:
130  const Pathname & _root;
131  scoped_ptr<media::CredentialManager> _cmPtr;
132  };
133  } // namespace
135 
137  namespace
138  {
142  class MediaMounter
143  {
144  public:
146  MediaMounter( const Url & url_r )
147  {
148  media::MediaManager mediamanager;
149  _mid = mediamanager.open( url_r );
150  mediamanager.attach( _mid );
151  }
152 
154  ~MediaMounter()
155  {
156  media::MediaManager mediamanager;
157  mediamanager.release( _mid );
158  mediamanager.close( _mid );
159  }
160 
165  Pathname getPathName( const Pathname & path_r = Pathname() ) const
166  {
167  media::MediaManager mediamanager;
168  return mediamanager.localPath( _mid, path_r );
169  }
170 
171  private:
173  };
175 
177  template <class Iterator>
178  inline bool foundAliasIn( const std::string & alias_r, Iterator begin_r, Iterator end_r )
179  {
180  for_( it, begin_r, end_r )
181  if ( it->alias() == alias_r )
182  return true;
183  return false;
184  }
186  template <class Container>
187  inline bool foundAliasIn( const std::string & alias_r, const Container & cont_r )
188  { return foundAliasIn( alias_r, cont_r.begin(), cont_r.end() ); }
189 
191  template <class Iterator>
192  inline Iterator findAlias( const std::string & alias_r, Iterator begin_r, Iterator end_r )
193  {
194  for_( it, begin_r, end_r )
195  if ( it->alias() == alias_r )
196  return it;
197  return end_r;
198  }
200  template <class Container>
201  inline typename Container::iterator findAlias( const std::string & alias_r, Container & cont_r )
202  { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
204  template <class Container>
205  inline typename Container::const_iterator findAlias( const std::string & alias_r, const Container & cont_r )
206  { return findAlias( alias_r, cont_r.begin(), cont_r.end() ); }
207 
208 
210  inline std::string filenameFromAlias( const std::string & alias_r, const std::string & stem_r )
211  {
212  std::string filename( alias_r );
213  // replace slashes with underscores
214  str::replaceAll( filename, "/", "_" );
215 
216  filename = Pathname(filename).extend("."+stem_r).asString();
217  MIL << "generating filename for " << stem_r << " [" << alias_r << "] : '" << filename << "'" << endl;
218  return filename;
219  }
220 
236  struct RepoCollector : private base::NonCopyable
237  {
238  RepoCollector()
239  {}
240 
241  RepoCollector(const std::string & targetDistro_)
242  : targetDistro(targetDistro_)
243  {}
244 
245  bool collect( const RepoInfo &repo )
246  {
247  // skip repositories meant for other distros than specified
248  if (!targetDistro.empty()
249  && !repo.targetDistribution().empty()
250  && repo.targetDistribution() != targetDistro)
251  {
252  MIL
253  << "Skipping repository meant for '" << repo.targetDistribution()
254  << "' distribution (current distro is '"
255  << targetDistro << "')." << endl;
256 
257  return true;
258  }
259 
260  repos.push_back(repo);
261  return true;
262  }
263 
264  RepoInfoList repos;
265  std::string targetDistro;
266  };
268 
274  std::list<RepoInfo> repositories_in_file( const Pathname & file )
275  {
276  MIL << "repo file: " << file << endl;
277  RepoCollector collector;
278  parser::RepoFileReader parser( file, bind( &RepoCollector::collect, &collector, _1 ) );
279  return std::move(collector.repos);
280  }
281 
283 
292  std::list<RepoInfo> repositories_in_dir( const Pathname &dir )
293  {
294  MIL << "directory " << dir << endl;
295  std::list<RepoInfo> repos;
296  bool nonroot( geteuid() != 0 );
297  if ( nonroot && ! PathInfo(dir).userMayRX() )
298  {
299  JobReport::warning( str::FormatNAC(_("Cannot read repo directory '%1%': Permission denied")) % dir );
300  }
301  else
302  {
303  std::list<Pathname> entries;
304  if ( filesystem::readdir( entries, dir, false ) != 0 )
305  {
306  // TranslatorExplanation '%s' is a pathname
307  ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
308  }
309 
310  str::regex allowedRepoExt("^\\.repo(_[0-9]+)?$");
311  for ( std::list<Pathname>::const_iterator it = entries.begin(); it != entries.end(); ++it )
312  {
313  if ( str::regex_match(it->extension(), allowedRepoExt) )
314  {
315  if ( nonroot && ! PathInfo(*it).userMayR() )
316  {
317  JobReport::warning( str::FormatNAC(_("Cannot read repo file '%1%': Permission denied")) % *it );
318  }
319  else
320  {
321  const std::list<RepoInfo> & tmp( repositories_in_file( *it ) );
322  repos.insert( repos.end(), tmp.begin(), tmp.end() );
323  }
324  }
325  }
326  }
327  return repos;
328  }
329 
331 
332  inline void assert_alias( const RepoInfo & info )
333  {
334  if ( info.alias().empty() )
335  ZYPP_THROW( RepoNoAliasException( info ) );
336  // bnc #473834. Maybe we can match the alias against a regex to define
337  // and check for valid aliases
338  if ( info.alias()[0] == '.')
340  info, _("Repository alias cannot start with dot.")));
341  }
342 
343  inline void assert_alias( const ServiceInfo & info )
344  {
345  if ( info.alias().empty() )
347  // bnc #473834. Maybe we can match the alias against a regex to define
348  // and check for valid aliases
349  if ( info.alias()[0] == '.')
351  info, _("Service alias cannot start with dot.")));
352  }
353 
355 
356  inline void assert_urls( const RepoInfo & info )
357  {
358  if ( info.baseUrlsEmpty() )
359  ZYPP_THROW( RepoNoUrlException( info ) );
360  }
361 
362  inline void assert_url( const ServiceInfo & info )
363  {
364  if ( ! info.url().isValid() )
366  }
367 
369 
374  inline Pathname rawcache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
375  {
376  assert_alias(info);
377  return opt.repoRawCachePath / info.escaped_alias();
378  }
379 
388  inline Pathname rawproductdata_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
389  {
390  assert_alias(info);
391  return opt.repoRawCachePath / info.escaped_alias() / info.path();
392  }
393 
397  inline Pathname packagescache_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info )
398  {
399  assert_alias(info);
400  return opt.repoPackagesCachePath / info.escaped_alias();
401  }
402 
406  inline Pathname solv_path_for_repoinfo( const RepoManagerOptions &opt, const RepoInfo &info)
407  {
408  assert_alias(info);
409  return opt.repoSolvCachePath / info.escaped_alias();
410  }
411 
413 
415  class ServiceCollector
416  {
417  public:
418  typedef std::set<ServiceInfo> ServiceSet;
419 
420  ServiceCollector( ServiceSet & services_r )
421  : _services( services_r )
422  {}
423 
424  bool operator()( const ServiceInfo & service_r ) const
425  {
426  _services.insert( service_r );
427  return true;
428  }
429 
430  private:
431  ServiceSet & _services;
432  };
434 
435  } // namespace
437 
438  std::list<RepoInfo> readRepoFile( const Url & repo_file )
439  {
440  // no interface to download a specific file, using workaround:
442  Url url(repo_file);
443  Pathname path(url.getPathName());
444  url.setPathName ("/");
445  MediaSetAccess access(url);
446  Pathname local = access.provideFile(path);
447 
448  DBG << "reading repo file " << repo_file << ", local path: " << local << endl;
449 
450  return repositories_in_file(local);
451  }
452 
454  //
455  // class RepoManagerOptions
456  //
458 
460  {
461  repoCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoCachePath() );
462  repoRawCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoMetadataPath() );
463  repoSolvCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoSolvfilesPath() );
464  repoPackagesCachePath = Pathname::assertprefix( root_r, ZConfig::instance().repoPackagesPath() );
465  knownReposPath = Pathname::assertprefix( root_r, ZConfig::instance().knownReposPath() );
466  knownServicesPath = Pathname::assertprefix( root_r, ZConfig::instance().knownServicesPath() );
467  pluginsPath = Pathname::assertprefix( root_r, ZConfig::instance().pluginsPath() );
468  probe = ZConfig::instance().repo_add_probe();
469 
470  rootDir = root_r;
471  }
472 
474  {
475  RepoManagerOptions ret;
476  ret.repoCachePath = root_r;
477  ret.repoRawCachePath = root_r/"raw";
478  ret.repoSolvCachePath = root_r/"solv";
479  ret.repoPackagesCachePath = root_r/"packages";
480  ret.knownReposPath = root_r/"repos.d";
481  ret.knownServicesPath = root_r/"services.d";
482  ret.pluginsPath = root_r/"plugins";
483  ret.rootDir = root_r;
484  return ret;
485  }
486 
487  std:: ostream & operator<<( std::ostream & str, const RepoManagerOptions & obj )
488  {
489 #define OUTS(X) str << " " #X "\t" << obj.X << endl
490  str << "RepoManagerOptions (" << obj.rootDir << ") {" << endl;
491  OUTS( repoRawCachePath );
492  OUTS( repoSolvCachePath );
493  OUTS( repoPackagesCachePath );
494  OUTS( knownReposPath );
495  OUTS( knownServicesPath );
496  OUTS( pluginsPath );
497  str << "}" << endl;
498 #undef OUTS
499  return str;
500  }
501 
508  {
509  public:
510  Impl( const RepoManagerOptions &opt )
511  : _options(opt)
512  {
513  init_knownServices();
514  init_knownRepositories();
515  }
516 
518  {
519  // trigger appdata refresh if some repos change
520  if ( _reposDirty && geteuid() == 0 && ( _options.rootDir.empty() || _options.rootDir == "/" ) )
521  {
522  try {
523  std::list<Pathname> entries;
524  filesystem::readdir( entries, _options.pluginsPath/"appdata", false );
525  if ( ! entries.empty() )
526  {
528  cmd.push_back( "<" ); // discard stdin
529  cmd.push_back( ">" ); // discard stdout
530  cmd.push_back( "PROGRAM" ); // [2] - fix index below if changing!
531  for ( const auto & rinfo : repos() )
532  {
533  if ( ! rinfo.enabled() )
534  continue;
535  cmd.push_back( "-R" );
536  cmd.push_back( rinfo.alias() );
537  cmd.push_back( "-t" );
538  cmd.push_back( rinfo.type().asString() );
539  cmd.push_back( "-p" );
540  cmd.push_back( rinfo.metadataPath().asString() );
541  }
542 
543  for_( it, entries.begin(), entries.end() )
544  {
545  PathInfo pi( *it );
546  //DBG << "/tmp/xx ->" << pi << endl;
547  if ( pi.isFile() && pi.userMayRX() )
548  {
549  // trigger plugin
550  cmd[2] = pi.asString(); // [2] - PROGRAM
552  }
553  }
554  }
555  }
556  catch (...) {} // no throw in dtor
557  }
558  }
559 
560  public:
561  bool repoEmpty() const { return repos().empty(); }
562  RepoSizeType repoSize() const { return repos().size(); }
563  RepoConstIterator repoBegin() const { return repos().begin(); }
564  RepoConstIterator repoEnd() const { return repos().end(); }
565 
566  bool hasRepo( const std::string & alias ) const
567  { return foundAliasIn( alias, repos() ); }
568 
569  RepoInfo getRepo( const std::string & alias ) const
570  {
571  RepoConstIterator it( findAlias( alias, repos() ) );
572  return it == repos().end() ? RepoInfo::noRepo : *it;
573  }
574 
575  public:
576  Pathname metadataPath( const RepoInfo & info ) const
577  { return rawcache_path_for_repoinfo( _options, info ); }
578 
579  Pathname packagesPath( const RepoInfo & info ) const
580  { return packagescache_path_for_repoinfo( _options, info ); }
581 
582  RepoStatus metadataStatus( const RepoInfo & info ) const;
583 
584  RefreshCheckStatus checkIfToRefreshMetadata( const RepoInfo & info, const Url & url, RawMetadataRefreshPolicy policy );
585 
586  void refreshMetadata( const RepoInfo & info, RawMetadataRefreshPolicy policy, OPT_PROGRESS );
587 
588  void cleanMetadata( const RepoInfo & info, OPT_PROGRESS );
589 
590  void cleanPackages( const RepoInfo & info, OPT_PROGRESS );
591 
592  void buildCache( const RepoInfo & info, CacheBuildPolicy policy, OPT_PROGRESS );
593 
594  repo::RepoType probe( const Url & url, const Pathname & path = Pathname() ) const;
595  repo::RepoType probeCache( const Pathname & path_r ) const;
596 
597  void cleanCacheDirGarbage( OPT_PROGRESS );
598 
599  void cleanCache( const RepoInfo & info, OPT_PROGRESS );
600 
601  bool isCached( const RepoInfo & info ) const
602  { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
603 
604  RepoStatus cacheStatus( const RepoInfo & info ) const
605  { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
606 
607  void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
608 
609  void addRepository( const RepoInfo & info, OPT_PROGRESS );
610 
611  void addRepositories( const Url & url, OPT_PROGRESS );
612 
613  void removeRepository( const RepoInfo & info, OPT_PROGRESS );
614 
615  void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
616 
617  RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
618  RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
619 
620  public:
621  bool serviceEmpty() const { return _services.empty(); }
622  ServiceSizeType serviceSize() const { return _services.size(); }
623  ServiceConstIterator serviceBegin() const { return _services.begin(); }
624  ServiceConstIterator serviceEnd() const { return _services.end(); }
625 
626  bool hasService( const std::string & alias ) const
627  { return foundAliasIn( alias, _services ); }
628 
629  ServiceInfo getService( const std::string & alias ) const
630  {
631  ServiceConstIterator it( findAlias( alias, _services ) );
632  return it == _services.end() ? ServiceInfo::noService : *it;
633  }
634 
635  public:
636  void addService( const ServiceInfo & service );
637  void addService( const std::string & alias, const Url & url )
638  { addService( ServiceInfo( alias, url ) ); }
639 
640  void removeService( const std::string & alias );
641  void removeService( const ServiceInfo & service )
642  { removeService( service.alias() ); }
643 
644  void refreshServices( const RefreshServiceOptions & options_r );
645 
646  void refreshService( const std::string & alias, const RefreshServiceOptions & options_r );
647  void refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
648  { refreshService( service.alias(), options_r ); }
649 
650  void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
651 
652  repo::ServiceType probeService( const Url & url ) const;
653 
654  private:
655  void saveService( ServiceInfo & service ) const;
656 
657  Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
658 
659  std::string generateFilename( const RepoInfo & info ) const
660  { return filenameFromAlias( info.alias(), "repo" ); }
661 
662  std::string generateFilename( const ServiceInfo & info ) const
663  { return filenameFromAlias( info.alias(), "service" ); }
664 
665  void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
666  {
667  Pathname base = solv_path_for_repoinfo( _options, info );
669  status.saveToCookieFile( base / "cookie" );
670  }
671 
672  void touchIndexFile( const RepoInfo & info );
673 
674  template<typename OutputIterator>
675  void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
676  {
677  MatchServiceAlias filter( alias );
678  std::copy( boost::make_filter_iterator( filter, repos().begin(), repos().end() ),
679  boost::make_filter_iterator( filter, repos().end(), repos().end() ),
680  out);
681  }
682 
683  private:
684  void init_knownServices();
685  void init_knownRepositories();
686 
687  const RepoSet & repos() const { return _reposX; }
688  RepoSet & reposManip() { if ( ! _reposDirty ) _reposDirty = true; return _reposX; }
689 
690  private:
694 
696 
697  private:
698  friend Impl * rwcowClone<Impl>( const Impl * rhs );
700  Impl * clone() const
701  { return new Impl( *this ); }
702  };
704 
706  inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
707  { return str << "RepoManager::Impl"; }
708 
710 
712  {
713  filesystem::assert_dir( _options.knownServicesPath );
714  Pathname servfile = generateNonExistingName( _options.knownServicesPath,
715  generateFilename( service ) );
716  service.setFilepath( servfile );
717 
718  MIL << "saving service in " << servfile << endl;
719 
720  std::ofstream file( servfile.c_str() );
721  if ( !file )
722  {
723  // TranslatorExplanation '%s' is a filename
724  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
725  }
726  service.dumpAsIniOn( file );
727  MIL << "done" << endl;
728  }
729 
746  const std::string & basefilename ) const
747  {
748  std::string final_filename = basefilename;
749  int counter = 1;
750  while ( PathInfo(dir + final_filename).isExist() )
751  {
752  final_filename = basefilename + "_" + str::numstring(counter);
753  ++counter;
754  }
755  return dir + Pathname(final_filename);
756  }
757 
759 
761  {
762  Pathname dir = _options.knownServicesPath;
763  std::list<Pathname> entries;
764  if (PathInfo(dir).isExist())
765  {
766  if ( filesystem::readdir( entries, dir, false ) != 0 )
767  {
768  // TranslatorExplanation '%s' is a pathname
769  ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
770  }
771 
772  //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
773  for_(it, entries.begin(), entries.end() )
774  {
775  parser::ServiceFileReader(*it, ServiceCollector(_services));
776  }
777  }
778 
779  repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
780  }
781 
783  namespace {
789  inline void cleanupNonRepoMetadtaFolders( const Pathname & cachePath_r,
790  const Pathname & defaultCachePath_r,
791  const std::list<std::string> & repoEscAliases_r )
792  {
793  if ( cachePath_r != defaultCachePath_r )
794  return;
795 
796  std::list<std::string> entries;
797  if ( filesystem::readdir( entries, cachePath_r, false ) == 0 )
798  {
799  entries.sort();
800  std::set<std::string> oldfiles;
801  set_difference( entries.begin(), entries.end(), repoEscAliases_r.begin(), repoEscAliases_r.end(),
802  std::inserter( oldfiles, oldfiles.end() ) );
803  for ( const std::string & old : oldfiles )
804  {
805  if ( old == Repository::systemRepoAlias() ) // don't remove the @System solv file
806  continue;
807  filesystem::recursive_rmdir( cachePath_r / old );
808  }
809  }
810  }
811  } // namespace
814  {
815  MIL << "start construct known repos" << endl;
816 
817  if ( PathInfo(_options.knownReposPath).isExist() )
818  {
819  std::list<std::string> repoEscAliases;
820  std::list<RepoInfo> orphanedRepos;
821  for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
822  {
823  // set the metadata path for the repo
824  repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
825  // set the downloaded packages path for the repo
826  repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
827  // remember it
828  _reposX.insert( repoInfo ); // direct access via _reposX in ctor! no reposManip.
829 
830  // detect orphaned repos belonging to a deleted service
831  const std::string & serviceAlias( repoInfo.service() );
832  if ( ! ( serviceAlias.empty() || hasService( serviceAlias ) ) )
833  {
834  WAR << "Schedule orphaned service repo for deletion: " << repoInfo << endl;
835  orphanedRepos.push_back( repoInfo );
836  continue; // don't remember it in repoEscAliases
837  }
838 
839  repoEscAliases.push_back(repoInfo.escaped_alias());
840  }
841 
842  // Cleanup orphanded service repos:
843  if ( ! orphanedRepos.empty() )
844  {
845  for ( const auto & repoInfo : orphanedRepos )
846  {
847  MIL << "Delete orphaned service repo " << repoInfo.alias() << endl;
848  // translators: Cleanup a repository previously owned by a meanwhile unknown (deleted) service.
849  // %1% = service name
850  // %2% = repository name
851  JobReport::warning( str::FormatNAC(_("Unknown service '%1%': Removing orphaned service repository '%2%'"))
852  % repoInfo.service()
853  % repoInfo.alias() );
854  try {
855  removeRepository( repoInfo );
856  }
857  catch ( const Exception & caugth )
858  {
859  JobReport::error( caugth.asUserHistory() );
860  }
861  }
862  }
863 
864  // delete metadata folders without corresponding repo (e.g. old tmp directories)
865  //
866  // bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
867  // we'd need somemagic file to identify zypp cache directories. Without this
868  // we may easily remove user data (zypper --pkg-cache-dir . download ...)
869  repoEscAliases.sort();
870  RepoManagerOptions defaultCache( _options.rootDir );
871  cleanupNonRepoMetadtaFolders( _options.repoRawCachePath, defaultCache.repoRawCachePath, repoEscAliases );
872  cleanupNonRepoMetadtaFolders( _options.repoSolvCachePath, defaultCache.repoSolvCachePath, repoEscAliases );
873  cleanupNonRepoMetadtaFolders( _options.repoPackagesCachePath, defaultCache.repoPackagesCachePath, repoEscAliases );
874  }
875  MIL << "end construct known repos" << endl;
876  }
877 
879 
881  {
882  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
883  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
884 
885  RepoType repokind = info.type();
886  // If unknown, probe the local metadata
887  if ( repokind == RepoType::NONE )
888  repokind = probeCache( productdatapath );
889 
890  RepoStatus status;
891  switch ( repokind.toEnum() )
892  {
893  case RepoType::RPMMD_e :
894  status = RepoStatus( productdatapath/"repodata/repomd.xml") && RepoStatus( mediarootpath/"media.1/media" );
895  break;
896 
897  case RepoType::YAST2_e :
898  status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
899  break;
900 
902  status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
903  break;
904 
905  case RepoType::NONE_e :
906  // Return default RepoStatus in case of RepoType::NONE
907  // indicating it should be created?
908  // ZYPP_THROW(RepoUnknownTypeException());
909  break;
910  }
911  return status;
912  }
913 
914 
916  {
917  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
918 
919  RepoType repokind = info.type();
920  if ( repokind.toEnum() == RepoType::NONE_e )
921  // unknown, probe the local metadata
922  repokind = probeCache( productdatapath );
923  // if still unknown, just return
924  if (repokind == RepoType::NONE_e)
925  return;
926 
927  Pathname p;
928  switch ( repokind.toEnum() )
929  {
930  case RepoType::RPMMD_e :
931  p = Pathname(productdatapath + "/repodata/repomd.xml");
932  break;
933 
934  case RepoType::YAST2_e :
935  p = Pathname(productdatapath + "/content");
936  break;
937 
939  p = Pathname(productdatapath + "/cookie");
940  break;
941 
942  case RepoType::NONE_e :
943  default:
944  break;
945  }
946 
947  // touch the file, ignore error (they are logged anyway)
949  }
950 
951 
953  {
954  assert_alias(info);
955  try
956  {
957  MIL << "Going to try to check whether refresh is needed for " << url << endl;
958 
959  // first check old (cached) metadata
960  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
961  filesystem::assert_dir( mediarootpath );
962  RepoStatus oldstatus = metadataStatus( info );
963  if ( oldstatus.empty() )
964  {
965  MIL << "No cached metadata, going to refresh" << endl;
966  return REFRESH_NEEDED;
967  }
968 
969  if ( url.schemeIsVolatile() )
970  {
971  MIL << "Never refresh CD/DVD" << endl;
972  return REPO_UP_TO_DATE;
973  }
974 
975  if ( policy == RefreshForced )
976  {
977  MIL << "Forced refresh!" << endl;
978  return REFRESH_NEEDED;
979  }
980 
981  if ( url.schemeIsLocal() )
982  {
983  policy = RefreshIfNeededIgnoreDelay;
984  }
985 
986  // now we've got the old (cached) status, we can decide repo.refresh.delay
987  if ( policy != RefreshIfNeededIgnoreDelay )
988  {
989  // difference in seconds
990  double diff = difftime(
992  (Date::ValueType)oldstatus.timestamp()) / 60;
993 
994  DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
995  DBG << "current time: " << (Date::ValueType)Date::now() << endl;
996  DBG << "last refresh = " << diff << " minutes ago" << endl;
997 
998  if ( diff < ZConfig::instance().repo_refresh_delay() )
999  {
1000  if ( diff < 0 )
1001  {
1002  WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
1003  }
1004  else
1005  {
1006  MIL << "Repository '" << info.alias()
1007  << "' has been refreshed less than repo.refresh.delay ("
1009  << ") minutes ago. Advising to skip refresh" << endl;
1010  return REPO_CHECK_DELAYED;
1011  }
1012  }
1013  }
1014 
1015  repo::RepoType repokind = info.type();
1016  // if unknown: probe it
1017  if ( repokind == RepoType::NONE )
1018  repokind = probe( url, info.path() );
1019 
1020  // retrieve newstatus
1021  RepoStatus newstatus;
1022  switch ( repokind.toEnum() )
1023  {
1024  case RepoType::RPMMD_e:
1025  {
1026  MediaSetAccess media( url );
1027  newstatus = yum::Downloader( info, mediarootpath ).status( media );
1028  }
1029  break;
1030 
1031  case RepoType::YAST2_e:
1032  {
1033  MediaSetAccess media( url );
1034  newstatus = susetags::Downloader( info, mediarootpath ).status( media );
1035  }
1036  break;
1037 
1039  newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
1040  break;
1041 
1042  default:
1043  case RepoType::NONE_e:
1045  break;
1046  }
1047 
1048  // check status
1049  if ( oldstatus == newstatus )
1050  {
1051  MIL << "repo has not changed" << endl;
1052  touchIndexFile( info );
1053  return REPO_UP_TO_DATE;
1054  }
1055  else
1056  {
1057  MIL << "repo has changed, going to refresh" << endl;
1058  return REFRESH_NEEDED;
1059  }
1060  }
1061  catch ( const Exception &e )
1062  {
1063  ZYPP_CAUGHT(e);
1064  ERR << "refresh check failed for " << url << endl;
1065  ZYPP_RETHROW(e);
1066  }
1067 
1068  return REFRESH_NEEDED; // default
1069  }
1070 
1071 
1073  {
1074  assert_alias(info);
1075  assert_urls(info);
1076 
1077  // we will throw this later if no URL checks out fine
1078  RepoException rexception( info, PL_("Valid metadata not found at specified URL",
1079  "Valid metadata not found at specified URLs",
1080  info.baseUrlsSize() ) );
1081 
1082  // Suppress (interactive) media::MediaChangeReport if we in have multiple basurls (>1)
1084 
1085  // try urls one by one
1086  for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
1087  {
1088  try
1089  {
1090  Url url(*it);
1091 
1092  // check whether to refresh metadata
1093  // if the check fails for this url, it throws, so another url will be checked
1094  if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
1095  return;
1096 
1097  MIL << "Going to refresh metadata from " << url << endl;
1098 
1099  repo::RepoType repokind = info.type();
1100 
1101  // if the type is unknown, try probing.
1102  if ( repokind == RepoType::NONE )
1103  {
1104  // unknown, probe it
1105  repokind = probe( *it, info.path() );
1106 
1107  if (repokind.toEnum() != RepoType::NONE_e)
1108  {
1109  // Adjust the probed type in RepoInfo
1110  info.setProbedType( repokind ); // lazy init!
1111  //save probed type only for repos in system
1112  for_( it, repoBegin(), repoEnd() )
1113  {
1114  if ( info.alias() == (*it).alias() )
1115  {
1116  RepoInfo modifiedrepo = info;
1117  modifiedrepo.setType( repokind );
1118  modifyRepository( info.alias(), modifiedrepo );
1119  break;
1120  }
1121  }
1122  }
1123  }
1124 
1125  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1126  if( filesystem::assert_dir(mediarootpath) )
1127  {
1128  Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
1129  ZYPP_THROW(ex);
1130  }
1131 
1132  // create temp dir as sibling of mediarootpath
1133  filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
1134  if( tmpdir.path().empty() )
1135  {
1136  Exception ex(_("Can't create metadata cache directory."));
1137  ZYPP_THROW(ex);
1138  }
1139 
1140  if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
1141  ( repokind.toEnum() == RepoType::YAST2_e ) )
1142  {
1143  MediaSetAccess media(url);
1144  shared_ptr<repo::Downloader> downloader_ptr;
1145 
1146  MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
1147 
1148  if ( repokind.toEnum() == RepoType::RPMMD_e )
1149  downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
1150  else
1151  downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
1152 
1159  for_( it, repoBegin(), repoEnd() )
1160  {
1161  Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1162  if ( PathInfo(cachepath).isExist() )
1163  downloader_ptr->addCachePath(cachepath);
1164  }
1165 
1166  downloader_ptr->download( media, tmpdir.path() );
1167  }
1168  else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1169  {
1170  MediaMounter media( url );
1171  RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) ); // dir status
1172 
1173  Pathname productpath( tmpdir.path() / info.path() );
1174  filesystem::assert_dir( productpath );
1175  newstatus.saveToCookieFile( productpath/"cookie" );
1176  }
1177  else
1178  {
1180  }
1181 
1182  // ok we have the metadata, now exchange
1183  // the contents
1184  filesystem::exchange( tmpdir.path(), mediarootpath );
1185  reposManip(); // remember to trigger appdata refresh
1186 
1187  // we are done.
1188  return;
1189  }
1190  catch ( const Exception &e )
1191  {
1192  ZYPP_CAUGHT(e);
1193  ERR << "Trying another url..." << endl;
1194 
1195  // remember the exception caught for the *first URL*
1196  // if all other URLs fail, the rexception will be thrown with the
1197  // cause of the problem of the first URL remembered
1198  if (it == info.baseUrlsBegin())
1199  rexception.remember(e);
1200  else
1201  rexception.addHistory( e.asUserString() );
1202 
1203  }
1204  } // for every url
1205  ERR << "No more urls..." << endl;
1206  ZYPP_THROW(rexception);
1207  }
1208 
1210 
1211  void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1212  {
1213  ProgressData progress(100);
1214  progress.sendTo(progressfnc);
1215 
1216  filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1217  progress.toMax();
1218  }
1219 
1220 
1221  void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1222  {
1223  ProgressData progress(100);
1224  progress.sendTo(progressfnc);
1225 
1226  filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1227  progress.toMax();
1228  }
1229 
1230 
1231  void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1232  {
1233  assert_alias(info);
1234  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1235  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1236 
1237  if( filesystem::assert_dir(_options.repoCachePath) )
1238  {
1239  Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1240  ZYPP_THROW(ex);
1241  }
1242  RepoStatus raw_metadata_status = metadataStatus(info);
1243  if ( raw_metadata_status.empty() )
1244  {
1245  /* if there is no cache at this point, we refresh the raw
1246  in case this is the first time - if it's !autorefresh,
1247  we may still refresh */
1248  refreshMetadata(info, RefreshIfNeeded, progressrcv );
1249  raw_metadata_status = metadataStatus(info);
1250  }
1251 
1252  bool needs_cleaning = false;
1253  if ( isCached( info ) )
1254  {
1255  MIL << info.alias() << " is already cached." << endl;
1256  RepoStatus cache_status = cacheStatus(info);
1257 
1258  if ( cache_status == raw_metadata_status )
1259  {
1260  MIL << info.alias() << " cache is up to date with metadata." << endl;
1261  if ( policy == BuildIfNeeded )
1262  {
1263  // On the fly add missing solv.idx files for bash completion.
1264  const Pathname & base = solv_path_for_repoinfo( _options, info);
1265  if ( ! PathInfo(base/"solv.idx").isExist() )
1266  sat::updateSolvFileIndex( base/"solv" );
1267 
1268  return;
1269  }
1270  else {
1271  MIL << info.alias() << " cache rebuild is forced" << endl;
1272  }
1273  }
1274 
1275  needs_cleaning = true;
1276  }
1277 
1278  ProgressData progress(100);
1280  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1281  progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1282  progress.toMin();
1283 
1284  if (needs_cleaning)
1285  {
1286  cleanCache(info);
1287  }
1288 
1289  MIL << info.alias() << " building cache..." << info.type() << endl;
1290 
1291  Pathname base = solv_path_for_repoinfo( _options, info);
1292 
1293  if( filesystem::assert_dir(base) )
1294  {
1295  Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1296  ZYPP_THROW(ex);
1297  }
1298 
1299  if( ! PathInfo(base).userMayW() )
1300  {
1301  Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1302  ZYPP_THROW(ex);
1303  }
1304  Pathname solvfile = base / "solv";
1305 
1306  // do we have type?
1307  repo::RepoType repokind = info.type();
1308 
1309  // if the type is unknown, try probing.
1310  switch ( repokind.toEnum() )
1311  {
1312  case RepoType::NONE_e:
1313  // unknown, probe the local metadata
1314  repokind = probeCache( productdatapath );
1315  break;
1316  default:
1317  break;
1318  }
1319 
1320  MIL << "repo type is " << repokind << endl;
1321 
1322  switch ( repokind.toEnum() )
1323  {
1324  case RepoType::RPMMD_e :
1325  case RepoType::YAST2_e :
1327  {
1328  // Take care we unlink the solvfile on exception
1329  ManagedFile guard( solvfile, filesystem::unlink );
1330  scoped_ptr<MediaMounter> forPlainDirs;
1331 
1333  cmd.push_back( PathInfo( "/usr/bin/repo2solv" ).isFile() ? "repo2solv" : "repo2solv.sh" );
1334  // repo2solv expects -o as 1st arg!
1335  cmd.push_back( "-o" );
1336  cmd.push_back( solvfile.asString() );
1337  cmd.push_back( "-X" ); // autogenerate pattern from pattern-package
1338 
1339  if ( repokind == RepoType::RPMPLAINDIR )
1340  {
1341  forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1342  // recusive for plaindir as 2nd arg!
1343  cmd.push_back( "-R" );
1344  // FIXME this does only work form dir: URLs
1345  cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1346  }
1347  else
1348  cmd.push_back( productdatapath.asString() );
1349 
1351  std::string errdetail;
1352 
1353  for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1354  WAR << " " << output;
1355  if ( errdetail.empty() ) {
1356  errdetail = prog.command();
1357  errdetail += '\n';
1358  }
1359  errdetail += output;
1360  }
1361 
1362  int ret = prog.close();
1363  if ( ret != 0 )
1364  {
1365  RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1366  ex.remember( errdetail );
1367  ZYPP_THROW(ex);
1368  }
1369 
1370  // We keep it.
1371  guard.resetDispose();
1372  sat::updateSolvFileIndex( solvfile ); // content digest for zypper bash completion
1373  }
1374  break;
1375  default:
1376  ZYPP_THROW(RepoUnknownTypeException( info, _("Unhandled repository type") ));
1377  break;
1378  }
1379  // update timestamp and checksum
1380  setCacheStatus(info, raw_metadata_status);
1381  MIL << "Commit cache.." << endl;
1382  progress.toMax();
1383  }
1384 
1386 
1387 
1394  repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1395  {
1396  MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1397 
1398  if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1399  {
1400  // Handle non existing local directory in advance, as
1401  // MediaSetAccess does not support it.
1402  MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1403  return repo::RepoType::NONE;
1404  }
1405 
1406  // prepare exception to be thrown if the type could not be determined
1407  // due to a media exception. We can't throw right away, because of some
1408  // problems with proxy servers returning an incorrect error
1409  // on ftp file-not-found(bnc #335906). Instead we'll check another types
1410  // before throwing.
1411 
1412  // TranslatorExplanation '%s' is an URL
1413  RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1414  bool gotMediaException = false;
1415  try
1416  {
1417  MediaSetAccess access(url);
1418  try
1419  {
1420  if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1421  {
1422  MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1423  return repo::RepoType::RPMMD;
1424  }
1425  }
1426  catch ( const media::MediaException &e )
1427  {
1428  ZYPP_CAUGHT(e);
1429  DBG << "problem checking for repodata/repomd.xml file" << endl;
1430  enew.remember(e);
1431  gotMediaException = true;
1432  }
1433 
1434  try
1435  {
1436  if ( access.doesFileExist(path/"/content") )
1437  {
1438  MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1439  return repo::RepoType::YAST2;
1440  }
1441  }
1442  catch ( const media::MediaException &e )
1443  {
1444  ZYPP_CAUGHT(e);
1445  DBG << "problem checking for content file" << endl;
1446  enew.remember(e);
1447  gotMediaException = true;
1448  }
1449 
1450  // if it is a non-downloading URL denoting a directory
1451  if ( ! url.schemeIsDownloading() )
1452  {
1453  MediaMounter media( url );
1454  if ( PathInfo(media.getPathName()/path).isDir() )
1455  {
1456  // allow empty dirs for now
1457  MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1459  }
1460  }
1461  }
1462  catch ( const Exception &e )
1463  {
1464  ZYPP_CAUGHT(e);
1465  // TranslatorExplanation '%s' is an URL
1466  Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1467  enew.remember(e);
1468  ZYPP_THROW(enew);
1469  }
1470 
1471  if (gotMediaException)
1472  ZYPP_THROW(enew);
1473 
1474  MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1475  return repo::RepoType::NONE;
1476  }
1477 
1484  {
1485  MIL << "going to probe the cached repo at " << path_r << endl;
1486 
1488 
1489  if ( PathInfo(path_r/"/repodata/repomd.xml").isFile() )
1490  { ret = repo::RepoType::RPMMD; }
1491  else if ( PathInfo(path_r/"/content").isFile() )
1492  { ret = repo::RepoType::YAST2; }
1493  else if ( PathInfo(path_r).isDir() )
1494  { ret = repo::RepoType::RPMPLAINDIR; }
1495 
1496  MIL << "Probed cached type " << ret << " at " << path_r << endl;
1497  return ret;
1498  }
1499 
1501 
1503  {
1504  MIL << "Going to clean up garbage in cache dirs" << endl;
1505 
1506  ProgressData progress(300);
1507  progress.sendTo(progressrcv);
1508  progress.toMin();
1509 
1510  std::list<Pathname> cachedirs;
1511  cachedirs.push_back(_options.repoRawCachePath);
1512  cachedirs.push_back(_options.repoPackagesCachePath);
1513  cachedirs.push_back(_options.repoSolvCachePath);
1514 
1515  for_( dir, cachedirs.begin(), cachedirs.end() )
1516  {
1517  if ( PathInfo(*dir).isExist() )
1518  {
1519  std::list<Pathname> entries;
1520  if ( filesystem::readdir( entries, *dir, false ) != 0 )
1521  // TranslatorExplanation '%s' is a pathname
1522  ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1523 
1524  unsigned sdircount = entries.size();
1525  unsigned sdircurrent = 1;
1526  for_( subdir, entries.begin(), entries.end() )
1527  {
1528  // if it does not belong known repo, make it disappear
1529  bool found = false;
1530  for_( r, repoBegin(), repoEnd() )
1531  if ( subdir->basename() == r->escaped_alias() )
1532  { found = true; break; }
1533 
1534  if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1535  filesystem::recursive_rmdir( *subdir );
1536 
1537  progress.set( progress.val() + sdircurrent * 100 / sdircount );
1538  ++sdircurrent;
1539  }
1540  }
1541  else
1542  progress.set( progress.val() + 100 );
1543  }
1544  progress.toMax();
1545  }
1546 
1548 
1549  void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1550  {
1551  ProgressData progress(100);
1552  progress.sendTo(progressrcv);
1553  progress.toMin();
1554 
1555  MIL << "Removing raw metadata cache for " << info.alias() << endl;
1556  filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1557 
1558  progress.toMax();
1559  }
1560 
1562 
1563  void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1564  {
1565  assert_alias(info);
1566  Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1567 
1568  if ( ! PathInfo(solvfile).isExist() )
1570 
1571  sat::Pool::instance().reposErase( info.alias() );
1572  try
1573  {
1574  Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1575  // test toolversion in order to rebuild solv file in case
1576  // it was written by a different libsolv-tool parser.
1577  const std::string & toolversion( sat::LookupRepoAttr( sat::SolvAttr::repositoryToolVersion, repo ).begin().asString() );
1578  if ( toolversion != LIBSOLV_TOOLVERSION )
1579  {
1580  repo.eraseFromPool();
1581  ZYPP_THROW(Exception(str::Str() << "Solv-file was created by '"<<toolversion<<"'-parser (want "<<LIBSOLV_TOOLVERSION<<")."));
1582  }
1583  }
1584  catch ( const Exception & exp )
1585  {
1586  ZYPP_CAUGHT( exp );
1587  MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1588  cleanCache( info, progressrcv );
1589  buildCache( info, BuildIfNeeded, progressrcv );
1590 
1591  sat::Pool::instance().addRepoSolv( solvfile, info );
1592  }
1593  }
1594 
1596 
1597  void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1598  {
1599  assert_alias(info);
1600 
1601  ProgressData progress(100);
1603  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1604  progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1605  progress.toMin();
1606 
1607  MIL << "Try adding repo " << info << endl;
1608 
1609  RepoInfo tosave = info;
1610  if ( repos().find(tosave) != repos().end() )
1612 
1613  // check the first url for now
1614  if ( _options.probe )
1615  {
1616  DBG << "unknown repository type, probing" << endl;
1617 
1618  RepoType probedtype;
1619  probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1620  if ( tosave.baseUrlsSize() > 0 )
1621  {
1622  if ( probedtype == RepoType::NONE )
1624  else
1625  tosave.setType(probedtype);
1626  }
1627  }
1628 
1629  progress.set(50);
1630 
1631  // assert the directory exists
1632  filesystem::assert_dir(_options.knownReposPath);
1633 
1634  Pathname repofile = generateNonExistingName(
1635  _options.knownReposPath, generateFilename(tosave));
1636  // now we have a filename that does not exists
1637  MIL << "Saving repo in " << repofile << endl;
1638 
1639  std::ofstream file(repofile.c_str());
1640  if (!file)
1641  {
1642  // TranslatorExplanation '%s' is a filename
1643  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1644  }
1645 
1646  tosave.dumpAsIniOn(file);
1647  tosave.setFilepath(repofile);
1648  tosave.setMetadataPath( metadataPath( tosave ) );
1649  tosave.setPackagesPath( packagesPath( tosave ) );
1650  {
1651  // We chould fix the API as we must injet those paths
1652  // into the repoinfo in order to keep it usable.
1653  RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1654  oinfo.setMetadataPath( metadataPath( tosave ) );
1655  oinfo.setPackagesPath( packagesPath( tosave ) );
1656  }
1657  reposManip().insert(tosave);
1658 
1659  progress.set(90);
1660 
1661  // check for credentials in Urls
1662  UrlCredentialExtractor( _options.rootDir ).collect( tosave.baseUrls() );
1663 
1664  HistoryLog(_options.rootDir).addRepository(tosave);
1665 
1666  progress.toMax();
1667  MIL << "done" << endl;
1668  }
1669 
1670 
1672  {
1673  std::list<RepoInfo> repos = readRepoFile(url);
1674  for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1675  it != repos.end();
1676  ++it )
1677  {
1678  // look if the alias is in the known repos.
1679  for_ ( kit, repoBegin(), repoEnd() )
1680  {
1681  if ( (*it).alias() == (*kit).alias() )
1682  {
1683  ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1685  }
1686  }
1687  }
1688 
1689  std::string filename = Pathname(url.getPathName()).basename();
1690 
1691  if ( filename == Pathname() )
1692  {
1693  // TranslatorExplanation '%s' is an URL
1694  ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1695  }
1696 
1697  // assert the directory exists
1698  filesystem::assert_dir(_options.knownReposPath);
1699 
1700  Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1701  // now we have a filename that does not exists
1702  MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1703 
1704  std::ofstream file(repofile.c_str());
1705  if (!file)
1706  {
1707  // TranslatorExplanation '%s' is a filename
1708  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1709  }
1710 
1711  for ( std::list<RepoInfo>::iterator it = repos.begin();
1712  it != repos.end();
1713  ++it )
1714  {
1715  MIL << "Saving " << (*it).alias() << endl;
1716  it->setFilepath(repofile.asString());
1717  it->dumpAsIniOn(file);
1718  reposManip().insert(*it);
1719 
1720  HistoryLog(_options.rootDir).addRepository(*it);
1721  }
1722 
1723  MIL << "done" << endl;
1724  }
1725 
1727 
1729  {
1730  ProgressData progress;
1732  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1733  progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1734 
1735  MIL << "Going to delete repo " << info.alias() << endl;
1736 
1737  for_( it, repoBegin(), repoEnd() )
1738  {
1739  // they can be the same only if the provided is empty, that means
1740  // the provided repo has no alias
1741  // then skip
1742  if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1743  continue;
1744 
1745  // TODO match by url
1746 
1747  // we have a matcing repository, now we need to know
1748  // where it does come from.
1749  RepoInfo todelete = *it;
1750  if (todelete.filepath().empty())
1751  {
1752  ZYPP_THROW(RepoException( todelete, _("Can't figure out where the repo is stored.") ));
1753  }
1754  else
1755  {
1756  // figure how many repos are there in the file:
1757  std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1758  if ( filerepos.size() == 0 // bsc#984494: file may have already been deleted
1759  ||(filerepos.size() == 1 && filerepos.front().alias() == todelete.alias() ) )
1760  {
1761  // easy: file does not exist, contains no or only the repo to delete: delete the file
1762  int ret = filesystem::unlink( todelete.filepath() );
1763  if ( ! ( ret == 0 || ret == ENOENT ) )
1764  {
1765  // TranslatorExplanation '%s' is a filename
1766  ZYPP_THROW(RepoException( todelete, str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1767  }
1768  MIL << todelete.alias() << " successfully deleted." << endl;
1769  }
1770  else
1771  {
1772  // there are more repos in the same file
1773  // write them back except the deleted one.
1774  //TmpFile tmp;
1775  //std::ofstream file(tmp.path().c_str());
1776 
1777  // assert the directory exists
1778  filesystem::assert_dir(todelete.filepath().dirname());
1779 
1780  std::ofstream file(todelete.filepath().c_str());
1781  if (!file)
1782  {
1783  // TranslatorExplanation '%s' is a filename
1784  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1785  }
1786  for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1787  fit != filerepos.end();
1788  ++fit )
1789  {
1790  if ( (*fit).alias() != todelete.alias() )
1791  (*fit).dumpAsIniOn(file);
1792  }
1793  }
1794 
1795  CombinedProgressData cSubprogrcv(progress, 20);
1796  CombinedProgressData mSubprogrcv(progress, 40);
1797  CombinedProgressData pSubprogrcv(progress, 40);
1798  // now delete it from cache
1799  if ( isCached(todelete) )
1800  cleanCache( todelete, cSubprogrcv);
1801  // now delete metadata (#301037)
1802  cleanMetadata( todelete, mSubprogrcv );
1803  cleanPackages( todelete, pSubprogrcv );
1804  reposManip().erase(todelete);
1805  MIL << todelete.alias() << " successfully deleted." << endl;
1806  HistoryLog(_options.rootDir).removeRepository(todelete);
1807  return;
1808  } // else filepath is empty
1809 
1810  }
1811  // should not be reached on a sucess workflow
1813  }
1814 
1816 
1817  void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1818  {
1819  RepoInfo toedit = getRepositoryInfo(alias);
1820  RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1821 
1822  // check if the new alias already exists when renaming the repo
1823  if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1824  {
1826  }
1827 
1828  if (toedit.filepath().empty())
1829  {
1830  ZYPP_THROW(RepoException( toedit, _("Can't figure out where the repo is stored.") ));
1831  }
1832  else
1833  {
1834  // figure how many repos are there in the file:
1835  std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1836 
1837  // there are more repos in the same file
1838  // write them back except the deleted one.
1839  //TmpFile tmp;
1840  //std::ofstream file(tmp.path().c_str());
1841 
1842  // assert the directory exists
1844 
1845  std::ofstream file(toedit.filepath().c_str());
1846  if (!file)
1847  {
1848  // TranslatorExplanation '%s' is a filename
1849  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1850  }
1851  for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1852  fit != filerepos.end();
1853  ++fit )
1854  {
1855  // if the alias is different, dump the original
1856  // if it is the same, dump the provided one
1857  if ( (*fit).alias() != toedit.alias() )
1858  (*fit).dumpAsIniOn(file);
1859  else
1860  newinfo.dumpAsIniOn(file);
1861  }
1862 
1863  if ( toedit.enabled() && !newinfo.enabled() )
1864  {
1865  // On the fly remove solv.idx files for bash completion if a repo gets disabled.
1866  const Pathname & solvidx = solv_path_for_repoinfo(_options, newinfo)/"solv.idx";
1867  if ( PathInfo(solvidx).isExist() )
1868  filesystem::unlink( solvidx );
1869  }
1870 
1871  newinfo.setFilepath(toedit.filepath());
1872  reposManip().erase(toedit);
1873  reposManip().insert(newinfo);
1874  // check for credentials in Urls
1875  UrlCredentialExtractor( _options.rootDir ).collect( newinfo.baseUrls() );
1876  HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1877  MIL << "repo " << alias << " modified" << endl;
1878  }
1879  }
1880 
1882 
1883  RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1884  {
1885  RepoConstIterator it( findAlias( alias, repos() ) );
1886  if ( it != repos().end() )
1887  return *it;
1888  RepoInfo info;
1889  info.setAlias( alias );
1891  }
1892 
1893 
1894  RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1895  {
1896  for_( it, repoBegin(), repoEnd() )
1897  {
1898  for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1899  {
1900  if ( (*urlit).asString(urlview) == url.asString(urlview) )
1901  return *it;
1902  }
1903  }
1904  RepoInfo info;
1905  info.setBaseUrl( url );
1907  }
1908 
1910  //
1911  // Services
1912  //
1914 
1916  {
1917  assert_alias( service );
1918 
1919  // check if service already exists
1920  if ( hasService( service.alias() ) )
1922 
1923  // Writable ServiceInfo is needed to save the location
1924  // of the .service file. Finaly insert into the service list.
1925  ServiceInfo toSave( service );
1926  saveService( toSave );
1927  _services.insert( toSave );
1928 
1929  // check for credentials in Url
1930  UrlCredentialExtractor( _options.rootDir ).collect( toSave.url() );
1931 
1932  MIL << "added service " << toSave.alias() << endl;
1933  }
1934 
1936 
1937  void RepoManager::Impl::removeService( const std::string & alias )
1938  {
1939  MIL << "Going to delete service " << alias << endl;
1940 
1941  const ServiceInfo & service = getService( alias );
1942 
1943  Pathname location = service.filepath();
1944  if( location.empty() )
1945  {
1946  ZYPP_THROW(ServiceException( service, _("Can't figure out where the service is stored.") ));
1947  }
1948 
1949  ServiceSet tmpSet;
1950  parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1951 
1952  // only one service definition in the file
1953  if ( tmpSet.size() == 1 )
1954  {
1955  if ( filesystem::unlink(location) != 0 )
1956  {
1957  // TranslatorExplanation '%s' is a filename
1958  ZYPP_THROW(ServiceException( service, str::form( _("Can't delete '%s'"), location.c_str() ) ));
1959  }
1960  MIL << alias << " successfully deleted." << endl;
1961  }
1962  else
1963  {
1964  filesystem::assert_dir(location.dirname());
1965 
1966  std::ofstream file(location.c_str());
1967  if( !file )
1968  {
1969  // TranslatorExplanation '%s' is a filename
1970  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1971  }
1972 
1973  for_(it, tmpSet.begin(), tmpSet.end())
1974  {
1975  if( it->alias() != alias )
1976  it->dumpAsIniOn(file);
1977  }
1978 
1979  MIL << alias << " successfully deleted from file " << location << endl;
1980  }
1981 
1982  // now remove all repositories added by this service
1983  RepoCollector rcollector;
1984  getRepositoriesInService( alias,
1985  boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1986  // cannot do this directly in getRepositoriesInService - would invalidate iterators
1987  for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1988  removeRepository(*rit);
1989  }
1990 
1992 
1994  {
1995  // copy the set of services since refreshService
1996  // can eventually invalidate the iterator
1997  ServiceSet services( serviceBegin(), serviceEnd() );
1998  for_( it, services.begin(), services.end() )
1999  {
2000  if ( !it->enabled() )
2001  continue;
2002 
2003  try {
2004  refreshService(*it, options_r);
2005  }
2006  catch ( const repo::ServicePluginInformalException & e )
2007  { ;/* ignore ServicePluginInformalException */ }
2008  }
2009  }
2010 
2011  void RepoManager::Impl::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2012  {
2013  ServiceInfo service( getService( alias ) );
2014  assert_alias( service );
2015  assert_url( service );
2016  MIL << "Going to refresh service '" << service.alias() << "', url: " << service.url() << ", opts: " << options_r << endl;
2017 
2018  if ( service.ttl() && !( options_r.testFlag( RefreshService_forceRefresh) || options_r.testFlag( RefreshService_restoreStatus ) ) )
2019  {
2020  // Service defines a TTL; maybe we can re-use existing data without refresh.
2021  Date lrf = service.lrf();
2022  if ( lrf )
2023  {
2024  Date now( Date::now() );
2025  if ( lrf <= now )
2026  {
2027  if ( (lrf+=service.ttl()) > now ) // lrf+= !
2028  {
2029  MIL << "Skip: '" << service.alias() << "' metadata valid until " << lrf << endl;
2030  return;
2031  }
2032  }
2033  else
2034  WAR << "Force: '" << service.alias() << "' metadata last refresh in the future: " << lrf << endl;
2035  }
2036  }
2037 
2038  // NOTE: It might be necessary to modify and rewrite the service info.
2039  // Either when probing the type, or when adjusting the repositories
2040  // enable/disable state.:
2041  bool serviceModified = false;
2042 
2044 
2045  // if the type is unknown, try probing.
2046  if ( service.type() == repo::ServiceType::NONE )
2047  {
2048  repo::ServiceType type = probeService( service.url() );
2049  if ( type != ServiceType::NONE )
2050  {
2051  service.setProbedType( type ); // lazy init!
2052  serviceModified = true;
2053  }
2054  }
2055 
2056  // get target distro identifier
2057  std::string servicesTargetDistro = _options.servicesTargetDistro;
2058  if ( servicesTargetDistro.empty() )
2059  {
2060  servicesTargetDistro = Target::targetDistribution( Pathname() );
2061  }
2062  DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
2063 
2064  // parse it
2065  Date::Duration origTtl = service.ttl(); // FIXME Ugly hack: const service.ttl modified when parsing
2066  RepoCollector collector(servicesTargetDistro);
2067  // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
2068  // which is actually a notification. Using an exception for this
2069  // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
2070  // and in zypper.
2071  std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
2072  try {
2073  ServiceRepos( service, bind( &RepoCollector::collect, &collector, _1 ) );
2074  }
2075  catch ( const repo::ServicePluginInformalException & e )
2076  {
2077  /* ignore ServicePluginInformalException and throw later */
2078  uglyHack.first = true;
2079  uglyHack.second = e;
2080  }
2081  if ( service.ttl() != origTtl ) // repoindex.xml changed ttl
2082  {
2083  if ( !service.ttl() )
2084  service.setLrf( Date() ); // don't need lrf when zero ttl
2085  serviceModified = true;
2086  }
2088  // On the fly remember the new repo states as defined the reopoindex.xml.
2089  // Move into ServiceInfo later.
2090  ServiceInfo::RepoStates newRepoStates;
2091 
2092  // set service alias and base url for all collected repositories
2093  for_( it, collector.repos.begin(), collector.repos.end() )
2094  {
2095  // First of all: Prepend service alias:
2096  it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
2097  // set reference to the parent service
2098  it->setService( service.alias() );
2099 
2100  // remember the new parsed repo state
2101  newRepoStates[it->alias()] = *it;
2102 
2103  // - If the repo url was not set by the repoindex parser, set service's url.
2104  // - Libzypp currently has problem with separate url + path handling so just
2105  // append a path, if set, to the baseurls
2106  // - Credentials in the url authority will be extracted later, either if the
2107  // repository is added or if we check for changed urls.
2108  Pathname path;
2109  if ( !it->path().empty() )
2110  {
2111  if ( it->path() != "/" )
2112  path = it->path();
2113  it->setPath("");
2114  }
2115 
2116  if ( it->baseUrlsEmpty() )
2117  {
2118  Url url( service.rawUrl() );
2119  if ( !path.empty() )
2120  url.setPathName( url.getPathName() / path );
2121  it->setBaseUrl( std::move(url) );
2122  }
2123  else if ( !path.empty() )
2124  {
2125  RepoInfo::url_set urls( it->rawBaseUrls() );
2126  for ( Url & url : urls )
2127  {
2128  url.setPathName( url.getPathName() / path );
2129  }
2130  it->setBaseUrls( std::move(urls) );
2131  }
2132  }
2133 
2135  // Now compare collected repos with the ones in the system...
2136  //
2137  RepoInfoList oldRepos;
2138  getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
2139 
2141  // find old repositories to remove...
2142  for_( oldRepo, oldRepos.begin(), oldRepos.end() )
2143  {
2144  if ( ! foundAliasIn( oldRepo->alias(), collector.repos ) )
2145  {
2146  if ( oldRepo->enabled() )
2147  {
2148  // Currently enabled. If this was a user modification remember the state.
2149  const auto & last = service.repoStates().find( oldRepo->alias() );
2150  if ( last != service.repoStates().end() && ! last->second.enabled )
2151  {
2152  DBG << "Service removes user enabled repo " << oldRepo->alias() << endl;
2153  service.addRepoToEnable( oldRepo->alias() );
2154  serviceModified = true;
2155  }
2156  else
2157  DBG << "Service removes enabled repo " << oldRepo->alias() << endl;
2158  }
2159  else
2160  DBG << "Service removes disabled repo " << oldRepo->alias() << endl;
2161 
2162  removeRepository( *oldRepo );
2163  }
2164  }
2165 
2167  // create missing repositories and modify existing ones if needed...
2168  UrlCredentialExtractor urlCredentialExtractor( _options.rootDir ); // To collect any credentials stored in repo URLs
2169  for_( it, collector.repos.begin(), collector.repos.end() )
2170  {
2171  // User explicitly requested the repo being enabled?
2172  // User explicitly requested the repo being disabled?
2173  // And hopefully not both ;) If so, enable wins.
2174 
2175  TriBool toBeEnabled( indeterminate ); // indeterminate - follow the service request
2176  DBG << "Service request to " << (it->enabled()?"enable":"disable") << " service repo " << it->alias() << endl;
2177 
2178  if ( options_r.testFlag( RefreshService_restoreStatus ) )
2179  {
2180  DBG << "Opt RefreshService_restoreStatus " << it->alias() << endl;
2181  // this overrides any pending request!
2182  // Remove from enable request list.
2183  // NOTE: repoToDisable is handled differently.
2184  // It gets cleared on each refresh.
2185  service.delRepoToEnable( it->alias() );
2186  // toBeEnabled stays indeterminate!
2187  }
2188  else
2189  {
2190  if ( service.repoToEnableFind( it->alias() ) )
2191  {
2192  DBG << "User request to enable service repo " << it->alias() << endl;
2193  toBeEnabled = true;
2194  // Remove from enable request list.
2195  // NOTE: repoToDisable is handled differently.
2196  // It gets cleared on each refresh.
2197  service.delRepoToEnable( it->alias() );
2198  serviceModified = true;
2199  }
2200  else if ( service.repoToDisableFind( it->alias() ) )
2201  {
2202  DBG << "User request to disable service repo " << it->alias() << endl;
2203  toBeEnabled = false;
2204  }
2205  }
2206 
2207  RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
2208  if ( oldRepo == oldRepos.end() )
2209  {
2210  // Not found in oldRepos ==> a new repo to add
2211 
2212  // Make sure the service repo is created with the appropriate enablement
2213  if ( ! indeterminate(toBeEnabled) )
2214  it->setEnabled( toBeEnabled );
2215 
2216  DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
2217  addRepository( *it );
2218  }
2219  else
2220  {
2221  // ==> an exising repo to check
2222  bool oldRepoModified = false;
2223 
2224  if ( indeterminate(toBeEnabled) )
2225  {
2226  // No user request: check for an old user modificaton otherwise follow service request.
2227  // NOTE: Assert toBeEnabled is boolean afterwards!
2228  if ( oldRepo->enabled() == it->enabled() )
2229  toBeEnabled = it->enabled(); // service requests no change to the system
2230  else if (options_r.testFlag( RefreshService_restoreStatus ) )
2231  {
2232  toBeEnabled = it->enabled(); // RefreshService_restoreStatus forced
2233  DBG << "Opt RefreshService_restoreStatus " << it->alias() << " forces " << (toBeEnabled?"enabled":"disabled") << endl;
2234  }
2235  else
2236  {
2237  const auto & last = service.repoStates().find( oldRepo->alias() );
2238  if ( last == service.repoStates().end() || last->second.enabled != it->enabled() )
2239  toBeEnabled = it->enabled(); // service request has changed since last refresh -> follow
2240  else
2241  {
2242  toBeEnabled = oldRepo->enabled(); // service request unchaned since last refresh -> keep user modification
2243  DBG << "User modified service repo " << it->alias() << " may stay " << (toBeEnabled?"enabled":"disabled") << endl;
2244  }
2245  }
2246  }
2247 
2248  // changed enable?
2249  if ( toBeEnabled == oldRepo->enabled() )
2250  {
2251  DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
2252  }
2253  else if ( toBeEnabled )
2254  {
2255  DBG << "Service repo " << it->alias() << " gets enabled" << endl;
2256  oldRepo->setEnabled( true );
2257  oldRepoModified = true;
2258  }
2259  else
2260  {
2261  DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2262  oldRepo->setEnabled( false );
2263  oldRepoModified = true;
2264  }
2265 
2266  // all other attributes follow the service request:
2267 
2268  // changed name (raw!)
2269  if ( oldRepo->rawName() != it->rawName() )
2270  {
2271  DBG << "Service repo " << it->alias() << " gets new NAME " << it->rawName() << endl;
2272  oldRepo->setName( it->rawName() );
2273  oldRepoModified = true;
2274  }
2275 
2276  // changed autorefresh
2277  if ( oldRepo->autorefresh() != it->autorefresh() )
2278  {
2279  DBG << "Service repo " << it->alias() << " gets new AUTOREFRESH " << it->autorefresh() << endl;
2280  oldRepo->setAutorefresh( it->autorefresh() );
2281  oldRepoModified = true;
2282  }
2283 
2284  // changed priority?
2285  if ( oldRepo->priority() != it->priority() )
2286  {
2287  DBG << "Service repo " << it->alias() << " gets new PRIORITY " << it->priority() << endl;
2288  oldRepo->setPriority( it->priority() );
2289  oldRepoModified = true;
2290  }
2291 
2292  // changed url?
2293  {
2294  RepoInfo::url_set newUrls( it->rawBaseUrls() );
2295  urlCredentialExtractor.extract( newUrls ); // Extract! to prevent passwds from disturbing the comparison below
2296  if ( oldRepo->rawBaseUrls() != newUrls )
2297  {
2298  DBG << "Service repo " << it->alias() << " gets new URLs " << newUrls << endl;
2299  oldRepo->setBaseUrls( std::move(newUrls) );
2300  oldRepoModified = true;
2301  }
2302  }
2303 
2304  // changed gpg check settings?
2305  // ATM only plugin services can set GPG values.
2306  if ( service.type() == ServiceType::PLUGIN )
2307  {
2308  TriBool ogpg[3]; // Gpg RepoGpg PkgGpg
2309  TriBool ngpg[3];
2310  oldRepo->getRawGpgChecks( ogpg[0], ogpg[1], ogpg[2] );
2311  it-> getRawGpgChecks( ngpg[0], ngpg[1], ngpg[2] );
2312 #define Z_CHKGPG(I,N) \
2313  if ( ! sameTriboolState( ogpg[I], ngpg[I] ) ) \
2314  { \
2315  DBG << "Service repo " << it->alias() << " gets new "#N"Check " << ngpg[I] << endl; \
2316  oldRepo->set##N##Check( ngpg[I] ); \
2317  oldRepoModified = true; \
2318  }
2319  Z_CHKGPG( 0, Gpg );
2320  Z_CHKGPG( 1, RepoGpg );
2321  Z_CHKGPG( 2, PkgGpg );
2322 #undef Z_CHKGPG
2323  }
2324 
2325  // save if modified:
2326  if ( oldRepoModified )
2327  {
2328  modifyRepository( oldRepo->alias(), *oldRepo );
2329  }
2330  }
2331  }
2332 
2333  // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2334  if ( ! service.reposToDisableEmpty() )
2335  {
2336  service.clearReposToDisable();
2337  serviceModified = true;
2338  }
2339 
2340  // Remember original service request for next refresh
2341  if ( service.repoStates() != newRepoStates )
2342  {
2343  service.setRepoStates( std::move(newRepoStates) );
2344  serviceModified = true;
2345  }
2346 
2348  // save service if modified: (unless a plugin service)
2349  if ( service.type() != ServiceType::PLUGIN )
2350  {
2351  if ( service.ttl() )
2352  {
2353  service.setLrf( Date::now() ); // remember last refresh
2354  serviceModified = true; // or use a cookie file
2355  }
2356 
2357  if ( serviceModified )
2358  {
2359  // write out modified service file.
2360  modifyService( service.alias(), service );
2361  }
2362  }
2363 
2364  if ( uglyHack.first )
2365  {
2366  throw( uglyHack.second ); // intentionally not ZYPP_THROW
2367  }
2368  }
2369 
2371 
2372  void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2373  {
2374  MIL << "Going to modify service " << oldAlias << endl;
2375 
2376  // we need a writable copy to link it to the file where
2377  // it is saved if we modify it
2378  ServiceInfo service(newService);
2379 
2380  if ( service.type() == ServiceType::PLUGIN )
2381  {
2383  }
2384 
2385  const ServiceInfo & oldService = getService(oldAlias);
2386 
2387  Pathname location = oldService.filepath();
2388  if( location.empty() )
2389  {
2390  ZYPP_THROW(ServiceException( oldService, _("Can't figure out where the service is stored.") ));
2391  }
2392 
2393  // remember: there may multiple services being defined in one file:
2394  ServiceSet tmpSet;
2395  parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2396 
2397  filesystem::assert_dir(location.dirname());
2398  std::ofstream file(location.c_str());
2399  for_(it, tmpSet.begin(), tmpSet.end())
2400  {
2401  if( *it != oldAlias )
2402  it->dumpAsIniOn(file);
2403  }
2404  service.dumpAsIniOn(file);
2405  file.close();
2406  service.setFilepath(location);
2407 
2408  _services.erase(oldAlias);
2409  _services.insert(service);
2410  // check for credentials in Urls
2411  UrlCredentialExtractor( _options.rootDir ).collect( service.url() );
2412 
2413 
2414  // changed properties affecting also repositories
2415  if ( oldAlias != service.alias() // changed alias
2416  || oldService.enabled() != service.enabled() ) // changed enabled status
2417  {
2418  std::vector<RepoInfo> toModify;
2419  getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2420  for_( it, toModify.begin(), toModify.end() )
2421  {
2422  if ( oldService.enabled() != service.enabled() )
2423  {
2424  if ( service.enabled() )
2425  {
2426  // reset to last refreshs state
2427  const auto & last = service.repoStates().find( it->alias() );
2428  if ( last != service.repoStates().end() )
2429  it->setEnabled( last->second.enabled );
2430  }
2431  else
2432  it->setEnabled( false );
2433  }
2434 
2435  if ( oldAlias != service.alias() )
2436  it->setService(service.alias());
2437 
2438  modifyRepository(it->alias(), *it);
2439  }
2440  }
2441 
2443  }
2444 
2446 
2448  {
2449  try
2450  {
2451  MediaSetAccess access(url);
2452  if ( access.doesFileExist("/repo/repoindex.xml") )
2453  return repo::ServiceType::RIS;
2454  }
2455  catch ( const media::MediaException &e )
2456  {
2457  ZYPP_CAUGHT(e);
2458  // TranslatorExplanation '%s' is an URL
2459  RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2460  enew.remember(e);
2461  ZYPP_THROW(enew);
2462  }
2463  catch ( const Exception &e )
2464  {
2465  ZYPP_CAUGHT(e);
2466  // TranslatorExplanation '%s' is an URL
2467  Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2468  enew.remember(e);
2469  ZYPP_THROW(enew);
2470  }
2471 
2472  return repo::ServiceType::NONE;
2473  }
2474 
2476  //
2477  // CLASS NAME : RepoManager
2478  //
2480 
2482  : _pimpl( new Impl(opt) )
2483  {}
2484 
2486  {}
2487 
2489  { return _pimpl->repoEmpty(); }
2490 
2492  { return _pimpl->repoSize(); }
2493 
2495  { return _pimpl->repoBegin(); }
2496 
2498  { return _pimpl->repoEnd(); }
2499 
2500  RepoInfo RepoManager::getRepo( const std::string & alias ) const
2501  { return _pimpl->getRepo( alias ); }
2502 
2503  bool RepoManager::hasRepo( const std::string & alias ) const
2504  { return _pimpl->hasRepo( alias ); }
2505 
2506  std::string RepoManager::makeStupidAlias( const Url & url_r )
2507  {
2508  std::string ret( url_r.getScheme() );
2509  if ( ret.empty() )
2510  ret = "repo-";
2511  else
2512  ret += "-";
2513 
2514  std::string host( url_r.getHost() );
2515  if ( ! host.empty() )
2516  {
2517  ret += host;
2518  ret += "-";
2519  }
2520 
2521  static Date::ValueType serial = Date::now();
2522  ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2523  return ret;
2524  }
2525 
2527  { return _pimpl->metadataStatus( info ); }
2528 
2530  { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2531 
2533  { return _pimpl->metadataPath( info ); }
2534 
2536  { return _pimpl->packagesPath( info ); }
2537 
2539  { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2540 
2541  void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2542  { return _pimpl->cleanMetadata( info, progressrcv ); }
2543 
2544  void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2545  { return _pimpl->cleanPackages( info, progressrcv ); }
2546 
2548  { return _pimpl->cacheStatus( info ); }
2549 
2550  void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2551  { return _pimpl->buildCache( info, policy, progressrcv ); }
2552 
2553  void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2554  { return _pimpl->cleanCache( info, progressrcv ); }
2555 
2556  bool RepoManager::isCached( const RepoInfo &info ) const
2557  { return _pimpl->isCached( info ); }
2558 
2559  void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2560  { return _pimpl->loadFromCache( info, progressrcv ); }
2561 
2563  { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2564 
2565  repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2566  { return _pimpl->probe( url, path ); }
2567 
2569  { return _pimpl->probe( url ); }
2570 
2571  void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2572  { return _pimpl->addRepository( info, progressrcv ); }
2573 
2574  void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2575  { return _pimpl->addRepositories( url, progressrcv ); }
2576 
2577  void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2578  { return _pimpl->removeRepository( info, progressrcv ); }
2579 
2580  void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2581  { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2582 
2583  RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2584  { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2585 
2586  RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2587  { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2588 
2590  { return _pimpl->serviceEmpty(); }
2591 
2593  { return _pimpl->serviceSize(); }
2594 
2596  { return _pimpl->serviceBegin(); }
2597 
2599  { return _pimpl->serviceEnd(); }
2600 
2601  ServiceInfo RepoManager::getService( const std::string & alias ) const
2602  { return _pimpl->getService( alias ); }
2603 
2604  bool RepoManager::hasService( const std::string & alias ) const
2605  { return _pimpl->hasService( alias ); }
2606 
2608  { return _pimpl->probeService( url ); }
2609 
2610  void RepoManager::addService( const std::string & alias, const Url& url )
2611  { return _pimpl->addService( alias, url ); }
2612 
2613  void RepoManager::addService( const ServiceInfo & service )
2614  { return _pimpl->addService( service ); }
2615 
2616  void RepoManager::removeService( const std::string & alias )
2617  { return _pimpl->removeService( alias ); }
2618 
2619  void RepoManager::removeService( const ServiceInfo & service )
2620  { return _pimpl->removeService( service ); }
2621 
2623  { return _pimpl->refreshServices( options_r ); }
2624 
2625  void RepoManager::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2626  { return _pimpl->refreshService( alias, options_r ); }
2627 
2628  void RepoManager::refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
2629  { return _pimpl->refreshService( service, options_r ); }
2630 
2631  void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2632  { return _pimpl->modifyService( oldAlias, service ); }
2633 
2635 
2636  std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2637  { return str << *obj._pimpl; }
2638 
2640 } // namespace zypp
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:527
RepoManager(const RepoManagerOptions &options=RepoManagerOptions())
Pathname filepath() const
File where this repo was read from.
static const ValueType day
Definition: Date.h:44
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:320
void removeService(const std::string &alias)
Removes service specified by its name.
Service data.
Definition: ServiceInfo.h:36
Pathname path() const
Repository path.
Definition: RepoInfo.cc:449
RepoStatus cacheStatus(const RepoInfo &info) const
Definition: RepoManager.cc:604
thrown when it was impossible to match a repository
Thrown when the repo alias is found to be invalid.
std::string targetDistribution() const
This is register.target attribute of the installed base product.
Definition: Target.cc:105
Interface to gettext.
RepoManagerOptions(const Pathname &root_r=Pathname())
Default ctor following ZConfig global settings.
Definition: RepoManager.cc:459
#define MIL
Definition: Logger.h:64
const std::string & command() const
The command we&#39;re executing.
bool empty() const
Whether the status is empty (default constucted)
Definition: RepoStatus.cc:136
static const std::string & sha1()
sha1
Definition: Digest.cc:46
int exchange(const Pathname &lpath, const Pathname &rpath)
Exchanges two files or directories.
Definition: PathInfo.cc:681
static bool error(const std::string &msg_r, const UserData &userData_r=UserData())
send error text
RepoStatus status(MediaSetAccess &media)
Status of the remote repository.
Definition: Downloader.cc:38
RepoConstIterator repoEnd() const
Definition: RepoManager.cc:564
void setCacheStatus(const RepoInfo &info, const RepoStatus &status)
Definition: RepoManager.cc:665
thrown when it was impossible to determine this repo type.
std::string digest()
get hex string representation of the digest
Definition: Digest.cc:191
Retrieval of repository list for a service.
Definition: ServiceRepos.h:25
void refreshServices(const RefreshServiceOptions &options_r)
RepoStatus cacheStatus(const RepoInfo &info) const
Status of metadata cache.
bool hasRepo(const std::string &alias) const
Return whether there is a known repository for alias.
void modifyService(const std::string &oldAlias, const ServiceInfo &service)
Modifies service file (rewrites it with new values) and underlying repositories if needed...
std::string asString(const DefaultIntegral< Tp, TInitial > &obj)
Read service data from a .service file.
void sendTo(const ReceiverFnc &fnc_r)
Set ReceiverFnc.
Definition: ProgressData.h:226
ServiceConstIterator serviceBegin() const
Definition: RepoManager.cc:623
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:321
Type toEnum() const
Definition: RepoType.h:48
ServiceInfo getService(const std::string &alias) const
Finds ServiceInfo by alias or return ServiceInfo::noService.
static ZConfig & instance()
Singleton ctor.
Definition: Resolver.cc:121
static TmpDir makeSibling(const Pathname &sibling_r)
Provide a new empty temporary directory as sibling.
Definition: TmpPath.cc:287
#define OPT_PROGRESS
Definition: RepoManager.cc:61
void refreshService(const std::string &alias, const RefreshServiceOptions &options_r)
void setProbedType(const repo::RepoType &t) const
This allows to adjust the RepoType lazy, from NONE to some probed value, even for const objects...
Definition: RepoInfo.cc:388
scoped_ptr< media::CredentialManager > _cmPtr
Definition: RepoManager.cc:131
Date lrf() const
Date of last refresh (if known).
Definition: ServiceInfo.cc:116
RWCOW_pointer< Impl > _pimpl
Pointer to implementation.
Definition: RepoManager.h:694
repo::RepoType probeCache(const Pathname &path_r) const
Probe Metadata in a local cache directory.
RepoStatus metadataStatus(const RepoInfo &info) const
Definition: RepoManager.cc:880
void cleanCacheDirGarbage(const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Remove any subdirectories of cache directories which no longer belong to any of known repositories...
bool hasService(const std::string &alias) const
Return whether there is a known service for alias.
const RepoSet & repos() const
Definition: RepoManager.cc:687
void refreshServices(const RefreshServiceOptions &options_r=RefreshServiceOptions())
Refreshes all enabled services.
RefreshCheckStatus
Possibly return state of checkIfRefreshMEtadata function.
Definition: RepoManager.h:195
Url rawUrl() const
The service raw url (no variables replaced)
Definition: ServiceInfo.cc:102
RepoSet::size_type RepoSizeType
Definition: RepoManager.h:121
void loadFromCache(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Load resolvables into the pool.
bool repo_add_probe() const
Whether repository urls should be probed.
Definition: ZConfig.cc:951
repo::ServiceType probeService(const Url &url) const
time_t mtime() const
Definition: PathInfo.h:376
const char * c_str() const
String representation.
Definition: Pathname.h:109
void addHistory(const std::string &msg_r)
Add some message text to the history.
Definition: Exception.cc:99
void refreshMetadata(const RepoInfo &info, RawMetadataRefreshPolicy policy=RefreshIfNeeded, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Refresh local raw cache.
void addService(const std::string &alias, const Url &url)
Definition: RepoManager.cc:637
void touchIndexFile(const RepoInfo &info)
Definition: RepoManager.cc:915
void setAlias(const std::string &alias)
set the repository alias
Definition: RepoInfoBase.cc:94
String related utilities and Regular expression matching.
void addRepoToEnable(const std::string &alias_r)
Add alias_r to the set of ReposToEnable.
Definition: ServiceInfo.cc:127
void removeRepository(const RepoInfo &info, OPT_PROGRESS)
RefreshServiceFlags RefreshServiceOptions
Options tuning RefreshService.
Definition: RepoManager.h:150
std::list< Url > url_set
Definition: RepoInfo.h:103
void modifyService(const std::string &oldAlias, const ServiceInfo &newService)
bool toMax()
Set counter value to current max value (unless no range).
Definition: ProgressData.h:273
bool serviceEmpty() const
Gets true if no service is in RepoManager (so no one in specified location)
void refreshService(const std::string &alias, const RefreshServiceOptions &options_r=RefreshServiceOptions())
Refresh specific service.
bool doesFileExist(const Pathname &file, unsigned media_nr=1)
Checks if a file exists on the specified media, with user callbacks.
void setFilepath(const Pathname &filename)
set the path to the .repo file
What is known about a repository.
Definition: RepoInfo.h:71
bool isCached(const RepoInfo &info) const
Definition: RepoManager.cc:601
static bool warning(const std::string &msg_r, const UserData &userData_r=UserData())
send warning text
Service plugin has trouble providing the metadata but this should not be treated as error...
void removeRepository(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Remove the best matching repository from known repos list.
Url url
Definition: MediaCurl.cc:196
#define for_(IT, BEG, END)
Convenient for-loops using iterator.
Definition: Easy.h:27
Pathname path() const
Definition: TmpPath.cc:146
void setBaseUrl(const Url &url)
Clears current base URL list and adds url.
Definition: RepoInfo.cc:373
std::string targetDistro
Definition: RepoManager.cc:265
ServiceConstIterator serviceEnd() const
Iterator to place behind last service in internal storage.
void reposErase(const std::string &alias_r)
Remove a Repository named alias_r.
Definition: Pool.h:110
Service already exists and some unique attribute can&#39;t be duplicated.
void refreshService(const ServiceInfo &service, const RefreshServiceOptions &options_r)
Definition: RepoManager.cc:647
repo::ServiceType probeService(const Url &url) const
Probe the type or the service.
std::string form(const char *format,...) __attribute__((format(printf
Printf style construction of std::string.
Definition: String.cc:36
bool enabled() const
If enabled is false, then this repository must be ignored as if does not exists, except when checking...
static RepoStatus fromCookieFile(const Pathname &path)
Reads the status from a cookie file.
Definition: RepoStatus.cc:108
void setProbedType(const repo::ServiceType &t) const
Lazy init service type.
Definition: ServiceInfo.cc:110
Service without alias was used in an operation.
RepoSet::const_iterator RepoConstIterator
Definition: RepoManager.h:120
function< bool(const ProgressData &)> ReceiverFnc
Most simple version of progress reporting The percentage in most cases.
Definition: ProgressData.h:139
RepoConstIterator repoBegin() const
Definition: RepoManager.cc:563
Url::asString() view options.
Definition: UrlBase.h:39
Pathname metadataPath(const RepoInfo &info) const
Path where the metadata is downloaded and kept.
void cleanMetadata(const RepoInfo &info, OPT_PROGRESS)
#define ERR
Definition: Logger.h:66
unsigned int MediaAccessId
Media manager access Id type.
Definition: MediaSource.h:29
#define PL_(MSG1, MSG2, N)
Definition: Gettext.h:30
void modifyRepository(const std::string &alias, const RepoInfo &newinfo, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Modify repository attributes.
std::vector< std::string > Arguments
urls_const_iterator baseUrlsBegin() const
iterator that points at begin of repository urls
Definition: RepoInfo.cc:461
RepoManagerOptions _options
Definition: RepoManager.cc:691
Repo manager settings.
Definition: RepoManager.h:53
boost::logic::tribool TriBool
3-state boolean logic (true, false and indeterminate).
Definition: String.h:30
void remember(const Exception &old_r)
Store an other Exception as history.
Definition: Exception.cc:89
std::string & replaceAll(std::string &str_r, const std::string &from_r, const std::string &to_r)
Replace all occurrences of from_r with to_r in str_r (inplace).
Definition: String.cc:328
void removeService(const ServiceInfo &service)
Definition: RepoManager.cc:641
transform_iterator< repo::RepoVariablesUrlReplacer, url_set::const_iterator > urls_const_iterator
Definition: RepoInfo.h:105
Progress callback from another progress.
Definition: ProgressData.h:390
std::map< std::string, RepoState > RepoStates
Definition: ServiceInfo.h:185
void addRepository(const RepoInfo &info, OPT_PROGRESS)
bool repoToEnableFind(const std::string &alias_r) const
Whether alias_r is mentioned in ReposToEnable.
Definition: ServiceInfo.cc:124
static const ServiceType RIS
Repository Index Service (RIS) (formerly known as &#39;Novell Update&#39; (NU) service)
Definition: ServiceType.h:32
void saveToCookieFile(const Pathname &path_r) const
Save the status information to a cookie file.
Definition: RepoStatus.cc:126
RepoStatus metadataStatus(const RepoInfo &info) const
Status of local metadata.
RepoManager implementation.
Definition: RepoManager.cc:507
bool empty() const
Test for an empty path.
Definition: Pathname.h:113
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:329
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Definition: Url.cc:758
std::set< RepoInfo > RepoSet
RepoInfo typedefs.
Definition: RepoManager.h:119
bool toMin()
Set counter value to current min value.
Definition: ProgressData.h:269
RepoInfo getRepositoryInfo(const std::string &alias, OPT_PROGRESS)
Downloader for SUSETags (YaST2) repositories Encapsulates all the knowledge of which files have to be...
Definition: Downloader.h:34
boost::noncopyable NonCopyable
Ensure derived classes cannot be copied.
Definition: NonCopyable.h:26
RepoConstIterator repoBegin() const
Store and operate on date (time_t).
Definition: Date.h:32
std::string asString() const
Returns a default string representation of the Url object.
Definition: Url.cc:491
static Pool instance()
Singleton ctor.
Definition: Pool.h:53
ServiceSizeType serviceSize() const
Definition: RepoManager.cc:622
static RepoManagerOptions makeTestSetup(const Pathname &root_r)
Test setup adjusting all paths to be located below one root_r directory.
Definition: RepoManager.cc:473
Pathname rootDir
remembers root_r value for later use
Definition: RepoManager.h:96
Pathname packagesPath(const RepoInfo &info) const
Definition: RepoManager.cc:579
void removeRepository(const RepoInfo &repo)
Log recently removed repository.
Definition: HistoryLog.cc:301
Provide a new empty temporary directory and recursively delete it when no longer needed.
Definition: TmpPath.h:170
Convenient building of std::string via std::ostringstream Basically a std::ostringstream autoconverti...
Definition: String.h:210
RepoSizeType repoSize() const
Definition: RepoManager.cc:562
Impl * clone() const
clone for RWCOW_pointer
Definition: RepoManager.cc:700
void clearReposToDisable()
Clear the set of ReposToDisable.
Definition: ServiceInfo.cc:157
Lightweight repository attribute value lookup.
Definition: LookupAttr.h:257
Execute a program and give access to its io An object of this class encapsulates the execution of an ...
void cleanCacheDirGarbage(OPT_PROGRESS)
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:653
thrown when it was impossible to determine one url for this repo.
Definition: RepoException.h:78
const std::string & asString() const
String representation.
Definition: Pathname.h:90
std::string alias() const
unique identifier for this source.
bool isExist() const
Return whether valid stat info exists.
Definition: PathInfo.h:281
unsigned repo_refresh_delay() const
Amount of time in minutes that must pass before another refresh.
Definition: ZConfig.cc:954
Just inherits Exception to separate media exceptions.
static const ServiceType NONE
No service set.
Definition: ServiceType.h:34
ServiceConstIterator serviceBegin() const
Iterator to first service in internal storage.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:75
static const SolvAttr repositoryToolVersion
Definition: SolvAttr.h:173
Service type enumeration.
Definition: ServiceType.h:26
void modifyRepository(const std::string &alias, const RepoInfo &newinfo_r, OPT_PROGRESS)
std::string asUserString() const
Translated error message as string suitable for the user.
Definition: Exception.cc:66
ServiceSet::const_iterator ServiceConstIterator
Definition: RepoManager.h:115
void setRepoStates(RepoStates newStates_r)
Remember a new set of repository states.
Definition: ServiceInfo.cc:162
std::ostream & operator<<(std::ostream &str, const DeltaCandidates &obj)
Pathname dirname() const
Return all but the last component od this path.
Definition: Pathname.h:120
bool reposToDisableEmpty() const
Definition: ServiceInfo.cc:140
static Pathname assertprefix(const Pathname &root_r, const Pathname &path_r)
Return path_r prefixed with root_r, unless it is already prefixed.
Definition: Pathname.cc:235
int recursive_rmdir(const Pathname &path)
Like &#39;rm -r DIR&#39;.
Definition: PathInfo.cc:413
#define WAR
Definition: Logger.h:65
#define OUTS(X)
void setMetadataPath(const Pathname &path)
set the path where the local metadata is stored
Definition: RepoInfo.cc:392
std::string asCompleteString() const
Returns a complete string representation of the Url object.
Definition: Url.cc:499
time_t Duration
Definition: Date.h:39
void setType(const repo::RepoType &t)
set the repository type
Definition: RepoInfo.cc:385
Maintain [min,max] and counter (value) for progress counting.
Definition: ProgressData.h:130
RepoInfoList repos
Definition: RepoManager.cc:264
void addRepository(const RepoInfo &repo)
Log a newly added repository.
Definition: HistoryLog.cc:289
void updateSolvFileIndex(const Pathname &solvfile_r)
Create solv file content digest for zypper bash completion.
Definition: Pool.cc:263
Writing the zypp history fileReference counted signleton for writhing the zypp history file...
Definition: HistoryLog.h:55
RepoConstIterator repoEnd() const
static bool schemeIsVolatile(const std::string &scheme_r)
cd dvd
Definition: Url.cc:468
repo::RepoType probe(const Url &url, const Pathname &path=Pathname()) const
Probe the metadata type of a repository located at url.
void addRepository(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Adds a repository to the list of known repositories.
RepoInfo getRepositoryInfo(const std::string &alias, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Find a matching repository info.
#define _(MSG)
Definition: Gettext.h:29
static const ServiceType PLUGIN
Plugin services are scripts installed on your system that provide the package manager with repositori...
Definition: ServiceType.h:43
Base Exception for service handling.
std::string receiveLine()
Read one line from the input stream.
RepoInfo getRepo(const std::string &alias) const
Definition: RepoManager.cc:569
const Pathname & _root
Definition: RepoManager.cc:130
void delRepoToEnable(const std::string &alias_r)
Remove alias_r from the set of ReposToEnable.
Definition: ServiceInfo.cc:133
static std::string makeStupidAlias(const Url &url_r=Url())
Some stupid string but suitable as alias for your url if nothing better is available.
RefreshCheckStatus checkIfToRefreshMetadata(const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy=RefreshIfNeeded)
Checks whether to refresh metadata for specified repository and url.
void cleanCache(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
clean local cache
const std::string & asString() const
Return current Pathname as String.
Definition: PathInfo.h:248
void cleanCache(const RepoInfo &info, OPT_PROGRESS)
std::string numstring(char n, int w=0)
Definition: String.h:305
ServiceSet::size_type ServiceSizeType
Definition: RepoManager.h:116
Date::Duration ttl() const
Sugested TTL between two metadata auto-refreshs.
Definition: ServiceInfo.cc:112
static const RepoType NONE
Definition: RepoType.h:32
bool hasService(const std::string &alias) const
Definition: RepoManager.cc:626
int touch(const Pathname &path)
Change file&#39;s modification and access times.
Definition: PathInfo.cc:1127
value_type val() const
Definition: ProgressData.h:295
void resetDispose()
Set no dispose function.
Definition: AutoDispose.h:162
Url url() const
The service url.
Definition: ServiceInfo.cc:99
RepoSizeType repoSize() const
void setPackagesPath(const Pathname &path)
set the path where the local packages are stored
Definition: RepoInfo.cc:395
bool repoEmpty() const
ServiceSizeType serviceSize() const
Gets count of service in RepoManager (in specified location)
std::ostream & copy(std::istream &from_r, std::ostream &to_r)
Copy istream to ostream.
Definition: IOStream.h:50
bool userMayRX() const
Definition: PathInfo.h:350
Temporarily disable MediaChangeReport Sometimes helpful to suppress interactive messages connected to...
int close()
Wait for the progamm to complete.
void setLrf(Date lrf_r)
Set date of last refresh.
Definition: ServiceInfo.cc:117
static const RepoType RPMMD
Definition: RepoType.h:29
creates and provides information about known sources.
Definition: RepoManager.h:105
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:325
int readdir(std::list< std::string > &retlist_r, const Pathname &path_r, bool dots_r)
Return content of directory via retlist.
Definition: PathInfo.cc:589
void addService(const ServiceInfo &service)
std::list< RepoInfo > readRepoFile(const Url &repo_file)
Parses repo_file and returns a list of RepoInfo objects corresponding to repositories found within th...
Definition: RepoManager.cc:438
static const RepoType YAST2
Definition: RepoType.h:30
ServiceSet & _services
Definition: RepoManager.cc:431
thrown when it was impossible to determine an alias for this repo.
Definition: RepoException.h:91
std::string generateFilename(const RepoInfo &info) const
Definition: RepoManager.cc:659
RepoStatus status(MediaSetAccess &media)
Status of the remote repository.
Definition: Downloader.cc:36
void buildCache(const RepoInfo &info, CacheBuildPolicy policy=BuildIfNeeded, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Refresh local cache.
const RepoStates & repoStates() const
Access the remembered repository states.
Definition: ServiceInfo.cc:161
Base class for Exception.
Definition: Exception.h:143
void addRepositories(const Url &url, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Adds repositores from a repo file to the list of known repositories.
Date timestamp() const
The time the data were changed the last time.
Definition: RepoStatus.cc:139
std::set< ServiceInfo > ServiceSet
ServiceInfo typedefs.
Definition: RepoManager.h:111
Exception for repository handling.
Definition: RepoException.h:37
virtual std::ostream & dumpAsIniOn(std::ostream &str) const
Write this RepoInfo object into str in a .repo file format.
Definition: RepoInfo.cc:646
virtual std::ostream & dumpAsIniOn(std::ostream &str) const
Writes ServiceInfo to stream in ".service" format.
Definition: ServiceInfo.cc:173
Impl(const RepoManagerOptions &opt)
Definition: RepoManager.cc:510
Pathname packagesPath(const RepoInfo &info) const
Path where the rpm packages are downloaded and kept.
media::MediaAccessId _mid
Definition: RepoManager.cc:172
static Date now()
Return the current time.
Definition: Date.h:78
bool repoToDisableFind(const std::string &alias_r) const
Whether alias_r is mentioned in ReposToDisable.
Definition: ServiceInfo.cc:145
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:199
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:598
DefaultIntegral< bool, false > _reposDirty
Definition: RepoManager.cc:695
std::string getHost(EEncoding eflag=zypp::url::E_DECODED) const
Returns the hostname or IP from the URL authority.
Definition: Url.cc:582
Functor thats filter RepoInfo by service which it belongs to.
Definition: RepoManager.h:637
bool serviceEmpty() const
Definition: RepoManager.cc:621
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
The repository cache is not built yet so you can&#39;t create the repostories from the cache...
Definition: RepoException.h:65
time_t ValueType
Definition: Date.h:38
void eraseFromPool()
Remove this Repository from it&#39;s Pool.
Definition: Repository.cc:297
Pathname repoPackagesCachePath
Definition: RepoManager.h:82
repo::RepoType probe(const Url &url, const Pathname &path) const
Probe repo metadata type.
bool hasRepo(const std::string &alias) const
Definition: RepoManager.cc:566
static const ServiceInfo noService
Represents an empty service.
Definition: ServiceInfo.h:61
void saveService(ServiceInfo &service) const
Definition: RepoManager.cc:711
Wrapper class for ::stat/::lstat.
Definition: PathInfo.h:220
void removeService(const std::string &alias)
void buildCache(const RepoInfo &info, CacheBuildPolicy policy, OPT_PROGRESS)
static const RepoInfo noRepo
Represents no Repository (one with an empty alias).
Definition: RepoInfo.h:80
bool regex_match(const std::string &s, smatch &matches, const regex &regex)
regex ZYPP_STR_REGEX regex ZYPP_STR_REGEX
Definition: Regex.h:70
Thrown when the repo alias is found to be invalid.
urls_const_iterator baseUrlsEnd() const
iterator that points at end of repository urls
Definition: RepoInfo.cc:464
friend std::ostream & operator<<(std::ostream &str, const RepoManager &obj)
static const RepoType RPMPLAINDIR
Definition: RepoType.h:31
static const std::string & systemRepoAlias()
Reserved system repository alias .
Definition: Repository.cc:37
ServiceInfo getService(const std::string &alias) const
Definition: RepoManager.cc:629
Track changing files or directories.
Definition: RepoStatus.h:38
void cleanPackages(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Clean local package cache.
Repository already exists and some unique attribute can&#39;t be duplicated.
bool set(value_type val_r)
Set new counter value.
Definition: ProgressData.h:246
urls_size_type baseUrlsSize() const
number of repository urls
Definition: RepoInfo.cc:467
static bool schemeIsDownloading(const std::string &scheme_r)
http https ftp sftp tftp
Definition: Url.cc:474
void getRepositoriesInService(const std::string &alias, OutputIterator out) const
Definition: RepoManager.cc:675
void modifyRepository(const RepoInfo &oldrepo, const RepoInfo &newrepo)
Log certain modifications to a repository.
Definition: HistoryLog.cc:312
std::ostream & operator<<(std::ostream &str, const RepoManager::Impl &obj)
Definition: RepoManager.cc:706
ServiceConstIterator serviceEnd() const
Definition: RepoManager.cc:624
Repository addRepoSolv(const Pathname &file_r, const std::string &name_r)
Load Solvables from a solv-file into a Repository named name_r.
Definition: Pool.cc:164
void name(const std::string &name_r)
Set counter name.
Definition: ProgressData.h:222
Downloader for YUM (rpm-nmd) repositories Encapsulates all the knowledge of which files have to be do...
Definition: Downloader.h:41
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
Pathname metadataPath(const RepoInfo &info) const
Definition: RepoManager.cc:576
void cleanPackages(const RepoInfo &info, OPT_PROGRESS)
std::string generateFilename(const ServiceInfo &info) const
Definition: RepoManager.cc:662
Pathname provideFile(const OnMediaLocation &resource, ProvideFileOptions options=PROVIDE_DEFAULT, const Pathname &deltafile=Pathname())
Provides a file from a media location.
RepoInfo getRepo(const std::string &alias) const
Find RepoInfo by alias or return RepoInfo::noRepo.
void loadFromCache(const RepoInfo &info, OPT_PROGRESS)
Format with (N)o (A)rgument (C)heck.
Definition: String.h:279
std::string hexstring(char n, int w=4)
Definition: String.h:340
bool isCached(const RepoInfo &info) const
Whether a repository exists in cache.
void addService(const std::string &alias, const Url &url)
Adds new service by it&#39;s alias and url.
repo::ServiceType type() const
Service type.
Definition: ServiceInfo.cc:108
void refreshMetadata(const RepoInfo &info, RawMetadataRefreshPolicy policy, OPT_PROGRESS)
std::string label() const
Label for use in messages for the user interface.
url_set baseUrls() const
The complete set of repository urls.
Definition: RepoInfo.cc:443
Service has no or invalid url defined.
repo::RepoType type() const
Type of repository,.
Definition: RepoInfo.cc:416
static bool schemeIsLocal(const std::string &scheme_r)
hd cd dvd dir file iso
Definition: Url.cc:456
Url manipulation class.
Definition: Url.h:87
void addRepositories(const Url &url, OPT_PROGRESS)
Media access layer responsible for handling files distributed on a set of media with media change and...
Pathname generateNonExistingName(const Pathname &dir, const std::string &basefilename) const
Generate a non existing filename in a directory, using a base name.
Definition: RepoManager.cc:745
void cleanMetadata(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Clean local metadata.
#define Z_CHKGPG(I, N)
#define DBG
Definition: Logger.h:63
Repository type enumeration.
Definition: RepoType.h:27
RefreshCheckStatus checkIfToRefreshMetadata(const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy)
Definition: RepoManager.cc:952