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