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