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