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