libzypp  14.42.0
RepoManager.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
13 #include <cstdlib>
14 #include <iostream>
15 #include <fstream>
16 #include <sstream>
17 #include <list>
18 #include <map>
19 #include <algorithm>
20 
21 #include "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  repo::RepoType probeCache( const Pathname & path_r ) const;
524 
525  void cleanCacheDirGarbage( OPT_PROGRESS );
526 
527  void cleanCache( const RepoInfo & info, OPT_PROGRESS );
528 
529  bool isCached( const RepoInfo & info ) const
530  { return PathInfo(solv_path_for_repoinfo( _options, info ) / "solv").isExist(); }
531 
532  RepoStatus cacheStatus( const RepoInfo & info ) const
533  { return RepoStatus::fromCookieFile(solv_path_for_repoinfo(_options, info) / "cookie"); }
534 
535  void loadFromCache( const RepoInfo & info, OPT_PROGRESS );
536 
537  void addRepository( const RepoInfo & info, OPT_PROGRESS );
538 
539  void addRepositories( const Url & url, OPT_PROGRESS );
540 
541  void removeRepository( const RepoInfo & info, OPT_PROGRESS );
542 
543  void modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, OPT_PROGRESS );
544 
545  RepoInfo getRepositoryInfo( const std::string & alias, OPT_PROGRESS );
546  RepoInfo getRepositoryInfo( const Url & url, const url::ViewOption & urlview, OPT_PROGRESS );
547 
548  public:
549  bool serviceEmpty() const { return _services.empty(); }
550  ServiceSizeType serviceSize() const { return _services.size(); }
551  ServiceConstIterator serviceBegin() const { return _services.begin(); }
552  ServiceConstIterator serviceEnd() const { return _services.end(); }
553 
554  bool hasService( const std::string & alias ) const
555  { return foundAliasIn( alias, _services ); }
556 
557  ServiceInfo getService( const std::string & alias ) const
558  {
559  ServiceConstIterator it( findAlias( alias, _services ) );
560  return it == _services.end() ? ServiceInfo::noService : *it;
561  }
562 
563  public:
564  void addService( const ServiceInfo & service );
565  void addService( const std::string & alias, const Url & url )
566  { addService( ServiceInfo( alias, url ) ); }
567 
568  void removeService( const std::string & alias );
569  void removeService( const ServiceInfo & service )
570  { removeService( service.alias() ); }
571 
572  void refreshServices( const RefreshServiceOptions & options_r );
573 
574  void refreshService( const std::string & alias, const RefreshServiceOptions & options_r );
575  void refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
576  { refreshService( service.alias(), options_r ); }
577 
578  void modifyService( const std::string & oldAlias, const ServiceInfo & newService );
579 
580  repo::ServiceType probeService( const Url & url ) const;
581 
582  private:
583  void saveService( ServiceInfo & service ) const;
584 
585  Pathname generateNonExistingName( const Pathname & dir, const std::string & basefilename ) const;
586 
587  std::string generateFilename( const RepoInfo & info ) const
588  { return filenameFromAlias( info.alias(), "repo" ); }
589 
590  std::string generateFilename( const ServiceInfo & info ) const
591  { return filenameFromAlias( info.alias(), "service" ); }
592 
593  void setCacheStatus( const RepoInfo & info, const RepoStatus & status )
594  {
595  Pathname base = solv_path_for_repoinfo( _options, info );
597  status.saveToCookieFile( base / "cookie" );
598  }
599 
600  void touchIndexFile( const RepoInfo & info );
601 
602  template<typename OutputIterator>
603  void getRepositoriesInService( const std::string & alias, OutputIterator out ) const
604  {
605  MatchServiceAlias filter( alias );
606  std::copy( boost::make_filter_iterator( filter, repos().begin(), repos().end() ),
607  boost::make_filter_iterator( filter, repos().end(), repos().end() ),
608  out);
609  }
610 
611  private:
612  void init_knownServices();
613  void init_knownRepositories();
614 
615  const RepoSet & repos() const { return _reposX; }
616  RepoSet & reposManip() { if ( ! _reposDirty ) _reposDirty = true; return _reposX; }
617 
618  private:
622 
624 
625  private:
626  friend Impl * rwcowClone<Impl>( const Impl * rhs );
628  Impl * clone() const
629  { return new Impl( *this ); }
630  };
632 
634  inline std::ostream & operator<<( std::ostream & str, const RepoManager::Impl & obj )
635  { return str << "RepoManager::Impl"; }
636 
638 
640  {
641  filesystem::assert_dir( _options.knownServicesPath );
642  Pathname servfile = generateNonExistingName( _options.knownServicesPath,
643  generateFilename( service ) );
644  service.setFilepath( servfile );
645 
646  MIL << "saving service in " << servfile << endl;
647 
648  std::ofstream file( servfile.c_str() );
649  if ( !file )
650  {
651  // TranslatorExplanation '%s' is a filename
652  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), servfile.c_str() )));
653  }
654  service.dumpAsIniOn( file );
655  MIL << "done" << endl;
656  }
657 
673  Pathname RepoManager::Impl::generateNonExistingName( const Pathname & dir,
674  const std::string & basefilename ) const
675  {
676  std::string final_filename = basefilename;
677  int counter = 1;
678  while ( PathInfo(dir + final_filename).isExist() )
679  {
680  final_filename = basefilename + "_" + str::numstring(counter);
681  ++counter;
682  }
683  return dir + Pathname(final_filename);
684  }
685 
687 
689  {
690  Pathname dir = _options.knownServicesPath;
691  std::list<Pathname> entries;
692  if (PathInfo(dir).isExist())
693  {
694  if ( filesystem::readdir( entries, dir, false ) != 0 )
695  {
696  // TranslatorExplanation '%s' is a pathname
697  ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir.c_str())));
698  }
699 
700  //str::regex allowedServiceExt("^\\.service(_[0-9]+)?$");
701  for_(it, entries.begin(), entries.end() )
702  {
703  parser::ServiceFileReader(*it, ServiceCollector(_services));
704  }
705  }
706 
707  repo::PluginServices(_options.pluginsPath/"services", ServiceCollector(_services));
708  }
709 
711  namespace {
717  inline void cleanupNonRepoMetadtaFolders( const Pathname & cachePath_r,
718  const Pathname & defaultCachePath_r,
719  const std::list<std::string> & repoEscAliases_r )
720  {
721  if ( cachePath_r != defaultCachePath_r )
722  return;
723 
724  std::list<std::string> entries;
725  if ( filesystem::readdir( entries, cachePath_r, false ) == 0 )
726  {
727  entries.sort();
728  std::set<std::string> oldfiles;
729  set_difference( entries.begin(), entries.end(), repoEscAliases_r.begin(), repoEscAliases_r.end(),
730  std::inserter( oldfiles, oldfiles.end() ) );
731  for ( const std::string & old : oldfiles )
732  {
733  if ( old == Repository::systemRepoAlias() ) // don't remove the @System solv file
734  continue;
735  filesystem::recursive_rmdir( cachePath_r / old );
736  }
737  }
738  }
739  } // namespace
742  {
743  MIL << "start construct known repos" << endl;
744 
745  if ( PathInfo(_options.knownReposPath).isExist() )
746  {
747  std::list<std::string> repoEscAliases;
748  std::list<RepoInfo> orphanedRepos;
749  for ( RepoInfo & repoInfo : repositories_in_dir(_options.knownReposPath) )
750  {
751  // set the metadata path for the repo
752  repoInfo.setMetadataPath( rawcache_path_for_repoinfo(_options, repoInfo) );
753  // set the downloaded packages path for the repo
754  repoInfo.setPackagesPath( packagescache_path_for_repoinfo(_options, repoInfo) );
755  // remember it
756  _reposX.insert( repoInfo ); // direct access via _reposX in ctor! no reposManip.
757 
758  // detect orphaned repos belonging to a deleted service
759  const std::string & serviceAlias( repoInfo.service() );
760  if ( ! ( serviceAlias.empty() || hasService( serviceAlias ) ) )
761  {
762  WAR << "Schedule orphaned service repo for deletion: " << repoInfo << endl;
763  orphanedRepos.push_back( repoInfo );
764  continue; // don't remember it in repoEscAliases
765  }
766 
767  repoEscAliases.push_back(repoInfo.escaped_alias());
768  }
769 
770  // Cleanup orphanded service repos:
771  if ( ! orphanedRepos.empty() )
772  {
773  for ( auto & repoInfo : orphanedRepos )
774  {
775  MIL << "Delete orphaned service repo " << repoInfo.alias() << endl;
776  // translators: Cleanup a repository previously owned by a meanwhile unknown (deleted) service.
777  // %1% = service name
778  // %2% = repository name
779  JobReport::warning( formatNAC(_("Unknown service '%1%': Removing orphaned service repository '%2%'" ))
780  % repoInfo.service()
781  % repoInfo.alias() );
782  try {
783  removeRepository( repoInfo );
784  }
785  catch ( const Exception & caugth )
786  {
787  JobReport::error( caugth.asUserHistory() );
788  }
789  }
790  }
791 
792  // delete metadata folders without corresponding repo (e.g. old tmp directories)
793  //
794  // bnc#891515: Auto-cleanup only zypp.conf default locations. Otherwise
795  // we'd need somemagic file to identify zypp cache directories. Without this
796  // we may easily remove user data (zypper --pkg-cache-dir . download ...)
797  repoEscAliases.sort();
798  RepoManagerOptions defaultCache( _options.rootDir );
799  cleanupNonRepoMetadtaFolders( _options.repoRawCachePath, defaultCache.repoRawCachePath, repoEscAliases );
800  cleanupNonRepoMetadtaFolders( _options.repoSolvCachePath, defaultCache.repoSolvCachePath, repoEscAliases );
801  cleanupNonRepoMetadtaFolders( _options.repoPackagesCachePath, defaultCache.repoPackagesCachePath, repoEscAliases );
802  }
803  MIL << "end construct known repos" << endl;
804  }
805 
807 
809  {
810  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
811  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
812 
813  RepoType repokind = info.type();
814  // If unknown, probe the local metadata
815  if ( repokind == RepoType::NONE )
816  repokind = probeCache( productdatapath );
817 
818  RepoStatus status;
819  switch ( repokind.toEnum() )
820  {
821  case RepoType::RPMMD_e :
822  status = RepoStatus( productdatapath/"repodata/repomd.xml");
823  break;
824 
825  case RepoType::YAST2_e :
826  status = RepoStatus( productdatapath/"content" ) && RepoStatus( mediarootpath/"media.1/media" );
827  break;
828 
830  status = RepoStatus::fromCookieFile( productdatapath/"cookie" );
831  break;
832 
833  case RepoType::NONE_e :
834  // Return default RepoStatus in case of RepoType::NONE
835  // indicating it should be created?
836  // ZYPP_THROW(RepoUnknownTypeException());
837  break;
838  }
839  return status;
840  }
841 
842 
844  {
845  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
846 
847  RepoType repokind = info.type();
848  if ( repokind.toEnum() == RepoType::NONE_e )
849  // unknown, probe the local metadata
850  repokind = probeCache( productdatapath );
851  // if still unknown, just return
852  if (repokind == RepoType::NONE_e)
853  return;
854 
855  Pathname p;
856  switch ( repokind.toEnum() )
857  {
858  case RepoType::RPMMD_e :
859  p = Pathname(productdatapath + "/repodata/repomd.xml");
860  break;
861 
862  case RepoType::YAST2_e :
863  p = Pathname(productdatapath + "/content");
864  break;
865 
867  p = Pathname(productdatapath + "/cookie");
868  break;
869 
870  case RepoType::NONE_e :
871  default:
872  break;
873  }
874 
875  // touch the file, ignore error (they are logged anyway)
877  }
878 
879 
881  {
882  assert_alias(info);
883  try
884  {
885  MIL << "Going to try to check whether refresh is needed for " << url << endl;
886 
887  // first check old (cached) metadata
888  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
889  filesystem::assert_dir( mediarootpath );
890  RepoStatus oldstatus = metadataStatus( info );
891 
892  if ( oldstatus.empty() )
893  {
894  MIL << "No cached metadata, going to refresh" << endl;
895  return REFRESH_NEEDED;
896  }
897 
898  {
899  if ( url.schemeIsVolatile() )
900  {
901  MIL << "never refresh CD/DVD" << endl;
902  return REPO_UP_TO_DATE;
903  }
904  if ( url.schemeIsLocal() )
905  {
906  policy = RefreshIfNeededIgnoreDelay;
907  }
908  }
909 
910  // now we've got the old (cached) status, we can decide repo.refresh.delay
911  if (policy != RefreshForced && policy != RefreshIfNeededIgnoreDelay)
912  {
913  // difference in seconds
914  double diff = difftime(
916  (Date::ValueType)oldstatus.timestamp()) / 60;
917 
918  DBG << "oldstatus: " << (Date::ValueType)oldstatus.timestamp() << endl;
919  DBG << "current time: " << (Date::ValueType)Date::now() << endl;
920  DBG << "last refresh = " << diff << " minutes ago" << endl;
921 
922  if ( diff < ZConfig::instance().repo_refresh_delay() )
923  {
924  if ( diff < 0 )
925  {
926  WAR << "Repository '" << info.alias() << "' was refreshed in the future!" << endl;
927  }
928  else
929  {
930  MIL << "Repository '" << info.alias()
931  << "' has been refreshed less than repo.refresh.delay ("
933  << ") minutes ago. Advising to skip refresh" << endl;
934  return REPO_CHECK_DELAYED;
935  }
936  }
937  }
938 
939  repo::RepoType repokind = info.type();
940  // if unknown: probe it
941  if ( repokind == RepoType::NONE )
942  repokind = probe( url, info.path() );
943 
944  // retrieve newstatus
945  RepoStatus newstatus;
946  switch ( repokind.toEnum() )
947  {
948  case RepoType::RPMMD_e:
949  {
950  MediaSetAccess media( url );
951  newstatus = yum::Downloader( info, mediarootpath ).status( media );
952  }
953  break;
954 
955  case RepoType::YAST2_e:
956  {
957  MediaSetAccess media( url );
958  newstatus = susetags::Downloader( info, mediarootpath ).status( media );
959  }
960  break;
961 
963  newstatus = RepoStatus( MediaMounter(url).getPathName(info.path()) ); // dir status
964  break;
965 
966  default:
967  case RepoType::NONE_e:
969  break;
970  }
971 
972  // check status
973  bool refresh = false;
974  if ( oldstatus == newstatus )
975  {
976  MIL << "repo has not changed" << endl;
977  if ( policy == RefreshForced )
978  {
979  MIL << "refresh set to forced" << endl;
980  refresh = true;
981  }
982  }
983  else
984  {
985  MIL << "repo has changed, going to refresh" << endl;
986  refresh = true;
987  }
988 
989  if (!refresh)
990  touchIndexFile(info);
991 
992  return refresh ? REFRESH_NEEDED : REPO_UP_TO_DATE;
993 
994  }
995  catch ( const Exception &e )
996  {
997  ZYPP_CAUGHT(e);
998  ERR << "refresh check failed for " << url << endl;
999  ZYPP_RETHROW(e);
1000  }
1001 
1002  return REFRESH_NEEDED; // default
1003  }
1004 
1005 
1007  {
1008  assert_alias(info);
1009  assert_urls(info);
1010 
1011  // we will throw this later if no URL checks out fine
1012  RepoException rexception( info, _PL("Valid metadata not found at specified URL",
1013  "Valid metadata not found at specified URLs",
1014  info.baseUrlsSize() ) );
1015 
1016  // Suppress (interactive) media::MediaChangeReport if we in have multiple basurls (>1)
1018 
1019  // try urls one by one
1020  for ( RepoInfo::urls_const_iterator it = info.baseUrlsBegin(); it != info.baseUrlsEnd(); ++it )
1021  {
1022  try
1023  {
1024  Url url(*it);
1025 
1026  // check whether to refresh metadata
1027  // if the check fails for this url, it throws, so another url will be checked
1028  if (checkIfToRefreshMetadata(info, url, policy)!=REFRESH_NEEDED)
1029  return;
1030 
1031  MIL << "Going to refresh metadata from " << url << endl;
1032 
1033  repo::RepoType repokind = info.type();
1034 
1035  // if the type is unknown, try probing.
1036  if ( repokind == RepoType::NONE )
1037  {
1038  // unknown, probe it
1039  repokind = probe( *it, info.path() );
1040 
1041  if (repokind.toEnum() != RepoType::NONE_e)
1042  {
1043  // Adjust the probed type in RepoInfo
1044  info.setProbedType( repokind ); // lazy init!
1045  //save probed type only for repos in system
1046  for_( it, repoBegin(), repoEnd() )
1047  {
1048  if ( info.alias() == (*it).alias() )
1049  {
1050  RepoInfo modifiedrepo = info;
1051  modifiedrepo.setType( repokind );
1052  modifyRepository( info.alias(), modifiedrepo );
1053  break;
1054  }
1055  }
1056  }
1057  }
1058 
1059  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1060  if( filesystem::assert_dir(mediarootpath) )
1061  {
1062  Exception ex(str::form( _("Can't create %s"), mediarootpath.c_str()) );
1063  ZYPP_THROW(ex);
1064  }
1065 
1066  // create temp dir as sibling of mediarootpath
1067  filesystem::TmpDir tmpdir( filesystem::TmpDir::makeSibling( mediarootpath ) );
1068  if( tmpdir.path().empty() )
1069  {
1070  Exception ex(_("Can't create metadata cache directory."));
1071  ZYPP_THROW(ex);
1072  }
1073 
1074  if ( ( repokind.toEnum() == RepoType::RPMMD_e ) ||
1075  ( repokind.toEnum() == RepoType::YAST2_e ) )
1076  {
1077  MediaSetAccess media(url);
1078  shared_ptr<repo::Downloader> downloader_ptr;
1079 
1080  MIL << "Creating downloader for [ " << info.alias() << " ]" << endl;
1081 
1082  if ( repokind.toEnum() == RepoType::RPMMD_e )
1083  downloader_ptr.reset(new yum::Downloader(info, mediarootpath));
1084  else
1085  downloader_ptr.reset( new susetags::Downloader(info, mediarootpath) );
1086 
1093  for_( it, repoBegin(), repoEnd() )
1094  {
1095  Pathname cachepath(rawcache_path_for_repoinfo( _options, *it ));
1096  if ( PathInfo(cachepath).isExist() )
1097  downloader_ptr->addCachePath(cachepath);
1098  }
1099 
1100  downloader_ptr->download( media, tmpdir.path() );
1101  }
1102  else if ( repokind.toEnum() == RepoType::RPMPLAINDIR_e )
1103  {
1104  MediaMounter media( url );
1105  RepoStatus newstatus = RepoStatus( media.getPathName( info.path() ) ); // dir status
1106 
1107  Pathname productpath( tmpdir.path() / info.path() );
1108  filesystem::assert_dir( productpath );
1109  newstatus.saveToCookieFile( productpath/"cookie" );
1110  }
1111  else
1112  {
1114  }
1115 
1116  // ok we have the metadata, now exchange
1117  // the contents
1118  filesystem::exchange( tmpdir.path(), mediarootpath );
1119  reposManip(); // remember to trigger appdata refresh
1120 
1121  // we are done.
1122  return;
1123  }
1124  catch ( const Exception &e )
1125  {
1126  ZYPP_CAUGHT(e);
1127  ERR << "Trying another url..." << endl;
1128 
1129  // remember the exception caught for the *first URL*
1130  // if all other URLs fail, the rexception will be thrown with the
1131  // cause of the problem of the first URL remembered
1132  if (it == info.baseUrlsBegin())
1133  rexception.remember(e);
1134  }
1135  } // for every url
1136  ERR << "No more urls..." << endl;
1137  ZYPP_THROW(rexception);
1138  }
1139 
1141 
1142  void RepoManager::Impl::cleanMetadata( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1143  {
1144  ProgressData progress(100);
1145  progress.sendTo(progressfnc);
1146 
1147  filesystem::recursive_rmdir(rawcache_path_for_repoinfo(_options, info));
1148  progress.toMax();
1149  }
1150 
1151 
1152  void RepoManager::Impl::cleanPackages( const RepoInfo & info, const ProgressData::ReceiverFnc & progressfnc )
1153  {
1154  ProgressData progress(100);
1155  progress.sendTo(progressfnc);
1156 
1157  filesystem::recursive_rmdir(packagescache_path_for_repoinfo(_options, info));
1158  progress.toMax();
1159  }
1160 
1161 
1162  void RepoManager::Impl::buildCache( const RepoInfo & info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
1163  {
1164  assert_alias(info);
1165  Pathname mediarootpath = rawcache_path_for_repoinfo( _options, info );
1166  Pathname productdatapath = rawproductdata_path_for_repoinfo( _options, info );
1167 
1168  if( filesystem::assert_dir(_options.repoCachePath) )
1169  {
1170  Exception ex(str::form( _("Can't create %s"), _options.repoCachePath.c_str()) );
1171  ZYPP_THROW(ex);
1172  }
1173  RepoStatus raw_metadata_status = metadataStatus(info);
1174  if ( raw_metadata_status.empty() )
1175  {
1176  /* if there is no cache at this point, we refresh the raw
1177  in case this is the first time - if it's !autorefresh,
1178  we may still refresh */
1179  refreshMetadata(info, RefreshIfNeeded, progressrcv );
1180  raw_metadata_status = metadataStatus(info);
1181  }
1182 
1183  bool needs_cleaning = false;
1184  if ( isCached( info ) )
1185  {
1186  MIL << info.alias() << " is already cached." << endl;
1187  RepoStatus cache_status = cacheStatus(info);
1188 
1189  if ( cache_status == raw_metadata_status )
1190  {
1191  MIL << info.alias() << " cache is up to date with metadata." << endl;
1192  if ( policy == BuildIfNeeded ) {
1193  return;
1194  }
1195  else {
1196  MIL << info.alias() << " cache rebuild is forced" << endl;
1197  }
1198  }
1199 
1200  needs_cleaning = true;
1201  }
1202 
1203  ProgressData progress(100);
1205  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1206  progress.name(str::form(_("Building repository '%s' cache"), info.label().c_str()));
1207  progress.toMin();
1208 
1209  if (needs_cleaning)
1210  {
1211  cleanCache(info);
1212  }
1213 
1214  MIL << info.alias() << " building cache..." << info.type() << endl;
1215 
1216  Pathname base = solv_path_for_repoinfo( _options, info);
1217 
1218  if( filesystem::assert_dir(base) )
1219  {
1220  Exception ex(str::form( _("Can't create %s"), base.c_str()) );
1221  ZYPP_THROW(ex);
1222  }
1223 
1224  if( ! PathInfo(base).userMayW() )
1225  {
1226  Exception ex(str::form( _("Can't create cache at %s - no writing permissions."), base.c_str()) );
1227  ZYPP_THROW(ex);
1228  }
1229  Pathname solvfile = base / "solv";
1230 
1231  // do we have type?
1232  repo::RepoType repokind = info.type();
1233 
1234  // if the type is unknown, try probing.
1235  switch ( repokind.toEnum() )
1236  {
1237  case RepoType::NONE_e:
1238  // unknown, probe the local metadata
1239  repokind = probeCache( productdatapath );
1240  break;
1241  default:
1242  break;
1243  }
1244 
1245  MIL << "repo type is " << repokind << endl;
1246 
1247  switch ( repokind.toEnum() )
1248  {
1249  case RepoType::RPMMD_e :
1250  case RepoType::YAST2_e :
1252  {
1253  // Take care we unlink the solvfile on exception
1254  ManagedFile guard( solvfile, filesystem::unlink );
1255  scoped_ptr<MediaMounter> forPlainDirs;
1256 
1258  cmd.push_back( "repo2solv.sh" );
1259  // repo2solv expects -o as 1st arg!
1260  cmd.push_back( "-o" );
1261  cmd.push_back( solvfile.asString() );
1262  cmd.push_back( "-X" ); // autogenerate pattern from pattern-package
1263 
1264  if ( repokind == RepoType::RPMPLAINDIR )
1265  {
1266  forPlainDirs.reset( new MediaMounter( *info.baseUrlsBegin() ) );
1267  // recusive for plaindir as 2nd arg!
1268  cmd.push_back( "-R" );
1269  // FIXME this does only work form dir: URLs
1270  cmd.push_back( forPlainDirs->getPathName( info.path() ).c_str() );
1271  }
1272  else
1273  cmd.push_back( productdatapath.asString() );
1274 
1276  std::string errdetail;
1277 
1278  for ( std::string output( prog.receiveLine() ); output.length(); output = prog.receiveLine() ) {
1279  WAR << " " << output;
1280  if ( errdetail.empty() ) {
1281  errdetail = prog.command();
1282  errdetail += '\n';
1283  }
1284  errdetail += output;
1285  }
1286 
1287  int ret = prog.close();
1288  if ( ret != 0 )
1289  {
1290  RepoException ex(str::form( _("Failed to cache repo (%d)."), ret ));
1291  ex.remember( errdetail );
1292  ZYPP_THROW(ex);
1293  }
1294 
1295  // We keep it.
1296  guard.resetDispose();
1297  }
1298  break;
1299  default:
1300  ZYPP_THROW(RepoUnknownTypeException( info, _("Unhandled repository type") ));
1301  break;
1302  }
1303  // update timestamp and checksum
1304  setCacheStatus(info, raw_metadata_status);
1305  MIL << "Commit cache.." << endl;
1306  progress.toMax();
1307  }
1308 
1310 
1311 
1318  repo::RepoType RepoManager::Impl::probe( const Url & url, const Pathname & path ) const
1319  {
1320  MIL << "going to probe the repo type at " << url << " (" << path << ")" << endl;
1321 
1322  if ( url.getScheme() == "dir" && ! PathInfo( url.getPathName()/path ).isDir() )
1323  {
1324  // Handle non existing local directory in advance, as
1325  // MediaSetAccess does not support it.
1326  MIL << "Probed type NONE (not exists) at " << url << " (" << path << ")" << endl;
1327  return repo::RepoType::NONE;
1328  }
1329 
1330  // prepare exception to be thrown if the type could not be determined
1331  // due to a media exception. We can't throw right away, because of some
1332  // problems with proxy servers returning an incorrect error
1333  // on ftp file-not-found(bnc #335906). Instead we'll check another types
1334  // before throwing.
1335 
1336  // TranslatorExplanation '%s' is an URL
1337  RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
1338  bool gotMediaException = false;
1339  try
1340  {
1341  MediaSetAccess access(url);
1342  try
1343  {
1344  if ( access.doesFileExist(path/"/repodata/repomd.xml") )
1345  {
1346  MIL << "Probed type RPMMD at " << url << " (" << path << ")" << endl;
1347  return repo::RepoType::RPMMD;
1348  }
1349  }
1350  catch ( const media::MediaException &e )
1351  {
1352  ZYPP_CAUGHT(e);
1353  DBG << "problem checking for repodata/repomd.xml file" << endl;
1354  enew.remember(e);
1355  gotMediaException = true;
1356  }
1357 
1358  try
1359  {
1360  if ( access.doesFileExist(path/"/content") )
1361  {
1362  MIL << "Probed type YAST2 at " << url << " (" << path << ")" << endl;
1363  return repo::RepoType::YAST2;
1364  }
1365  }
1366  catch ( const media::MediaException &e )
1367  {
1368  ZYPP_CAUGHT(e);
1369  DBG << "problem checking for content file" << endl;
1370  enew.remember(e);
1371  gotMediaException = true;
1372  }
1373 
1374  // if it is a non-downloading URL denoting a directory
1375  if ( ! url.schemeIsDownloading() )
1376  {
1377  MediaMounter media( url );
1378  if ( PathInfo(media.getPathName()/path).isDir() )
1379  {
1380  // allow empty dirs for now
1381  MIL << "Probed type RPMPLAINDIR at " << url << " (" << path << ")" << endl;
1383  }
1384  }
1385  }
1386  catch ( const Exception &e )
1387  {
1388  ZYPP_CAUGHT(e);
1389  // TranslatorExplanation '%s' is an URL
1390  Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
1391  enew.remember(e);
1392  ZYPP_THROW(enew);
1393  }
1394 
1395  if (gotMediaException)
1396  ZYPP_THROW(enew);
1397 
1398  MIL << "Probed type NONE at " << url << " (" << path << ")" << endl;
1399  return repo::RepoType::NONE;
1400  }
1401 
1407  repo::RepoType RepoManager::Impl::probeCache( const Pathname & path_r ) const
1408  {
1409  MIL << "going to probe the cached repo at " << path_r << endl;
1410 
1412 
1413  if ( PathInfo(path_r/"/repodata/repomd.xml").isFile() )
1414  { ret = repo::RepoType::RPMMD; }
1415  else if ( PathInfo(path_r/"/content").isFile() )
1416  { ret = repo::RepoType::YAST2; }
1417  else if ( PathInfo(path_r).isDir() )
1418  { ret = repo::RepoType::RPMPLAINDIR; }
1419 
1420  MIL << "Probed cached type " << ret << " at " << path_r << endl;
1421  return ret;
1422  }
1423 
1425 
1427  {
1428  MIL << "Going to clean up garbage in cache dirs" << endl;
1429 
1430  ProgressData progress(300);
1431  progress.sendTo(progressrcv);
1432  progress.toMin();
1433 
1434  std::list<Pathname> cachedirs;
1435  cachedirs.push_back(_options.repoRawCachePath);
1436  cachedirs.push_back(_options.repoPackagesCachePath);
1437  cachedirs.push_back(_options.repoSolvCachePath);
1438 
1439  for_( dir, cachedirs.begin(), cachedirs.end() )
1440  {
1441  if ( PathInfo(*dir).isExist() )
1442  {
1443  std::list<Pathname> entries;
1444  if ( filesystem::readdir( entries, *dir, false ) != 0 )
1445  // TranslatorExplanation '%s' is a pathname
1446  ZYPP_THROW(Exception(str::form(_("Failed to read directory '%s'"), dir->c_str())));
1447 
1448  unsigned sdircount = entries.size();
1449  unsigned sdircurrent = 1;
1450  for_( subdir, entries.begin(), entries.end() )
1451  {
1452  // if it does not belong known repo, make it disappear
1453  bool found = false;
1454  for_( r, repoBegin(), repoEnd() )
1455  if ( subdir->basename() == r->escaped_alias() )
1456  { found = true; break; }
1457 
1458  if ( ! found && ( Date::now()-PathInfo(*subdir).mtime() > Date::day ) )
1459  filesystem::recursive_rmdir( *subdir );
1460 
1461  progress.set( progress.val() + sdircurrent * 100 / sdircount );
1462  ++sdircurrent;
1463  }
1464  }
1465  else
1466  progress.set( progress.val() + 100 );
1467  }
1468  progress.toMax();
1469  }
1470 
1472 
1473  void RepoManager::Impl::cleanCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1474  {
1475  ProgressData progress(100);
1476  progress.sendTo(progressrcv);
1477  progress.toMin();
1478 
1479  MIL << "Removing raw metadata cache for " << info.alias() << endl;
1480  filesystem::recursive_rmdir(solv_path_for_repoinfo(_options, info));
1481 
1482  progress.toMax();
1483  }
1484 
1486 
1487  void RepoManager::Impl::loadFromCache( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1488  {
1489  assert_alias(info);
1490  Pathname solvfile = solv_path_for_repoinfo(_options, info) / "solv";
1491 
1492  if ( ! PathInfo(solvfile).isExist() )
1494 
1495  sat::Pool::instance().reposErase( info.alias() );
1496  try
1497  {
1498  Repository repo = sat::Pool::instance().addRepoSolv( solvfile, info );
1499  // test toolversion in order to rebuild solv file in case
1500  // it was written by an old libsolv-tool parser.
1501  //
1502  // Known version strings used:
1503  // - <no string>
1504  // - "1.0"
1505  //
1507  if ( toolversion.begin().asString().empty() )
1508  {
1509  repo.eraseFromPool();
1510  ZYPP_THROW(Exception("Solv-file was created by old parser."));
1511  }
1512  // else: up-to-date (or even newer).
1513  }
1514  catch ( const Exception & exp )
1515  {
1516  ZYPP_CAUGHT( exp );
1517  MIL << "Try to handle exception by rebuilding the solv-file" << endl;
1518  cleanCache( info, progressrcv );
1519  buildCache( info, BuildIfNeeded, progressrcv );
1520 
1521  sat::Pool::instance().addRepoSolv( solvfile, info );
1522  }
1523  }
1524 
1526 
1527  void RepoManager::Impl::addRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
1528  {
1529  assert_alias(info);
1530 
1531  ProgressData progress(100);
1533  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1534  progress.name(str::form(_("Adding repository '%s'"), info.label().c_str()));
1535  progress.toMin();
1536 
1537  MIL << "Try adding repo " << info << endl;
1538 
1539  RepoInfo tosave = info;
1540  if ( repos().find(tosave) != repos().end() )
1542 
1543  // check the first url for now
1544  if ( _options.probe )
1545  {
1546  DBG << "unknown repository type, probing" << endl;
1547 
1548  RepoType probedtype;
1549  probedtype = probe( *tosave.baseUrlsBegin(), info.path() );
1550  if ( tosave.baseUrlsSize() > 0 )
1551  {
1552  if ( probedtype == RepoType::NONE )
1554  else
1555  tosave.setType(probedtype);
1556  }
1557  }
1558 
1559  progress.set(50);
1560 
1561  // assert the directory exists
1562  filesystem::assert_dir(_options.knownReposPath);
1563 
1564  Pathname repofile = generateNonExistingName(
1565  _options.knownReposPath, generateFilename(tosave));
1566  // now we have a filename that does not exists
1567  MIL << "Saving repo in " << repofile << endl;
1568 
1569  std::ofstream file(repofile.c_str());
1570  if (!file)
1571  {
1572  // TranslatorExplanation '%s' is a filename
1573  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1574  }
1575 
1576  tosave.dumpAsIniOn(file);
1577  tosave.setFilepath(repofile);
1578  tosave.setMetadataPath( metadataPath( tosave ) );
1579  tosave.setPackagesPath( packagesPath( tosave ) );
1580  {
1581  // We chould fix the API as we must injet those paths
1582  // into the repoinfo in order to keep it usable.
1583  RepoInfo & oinfo( const_cast<RepoInfo &>(info) );
1584  oinfo.setMetadataPath( metadataPath( tosave ) );
1585  oinfo.setPackagesPath( packagesPath( tosave ) );
1586  }
1587  reposManip().insert(tosave);
1588 
1589  progress.set(90);
1590 
1591  // check for credentials in Urls
1592  bool havePasswords = false;
1593  for_( urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd() )
1594  if ( urlit->hasCredentialsInAuthority() )
1595  {
1596  havePasswords = true;
1597  break;
1598  }
1599  // save the credentials
1600  if ( havePasswords )
1601  {
1603  media::CredManagerOptions(_options.rootDir) );
1604 
1605  for_(urlit, tosave.baseUrlsBegin(), tosave.baseUrlsEnd())
1606  if (urlit->hasCredentialsInAuthority())
1608  cm.saveInUser(media::AuthData(*urlit));
1609  }
1610 
1611  HistoryLog().addRepository(tosave);
1612 
1613  progress.toMax();
1614  MIL << "done" << endl;
1615  }
1616 
1617 
1619  {
1620  std::list<RepoInfo> repos = readRepoFile(url);
1621  for ( std::list<RepoInfo>::const_iterator it = repos.begin();
1622  it != repos.end();
1623  ++it )
1624  {
1625  // look if the alias is in the known repos.
1626  for_ ( kit, repoBegin(), repoEnd() )
1627  {
1628  if ( (*it).alias() == (*kit).alias() )
1629  {
1630  ERR << "To be added repo " << (*it).alias() << " conflicts with existing repo " << (*kit).alias() << endl;
1632  }
1633  }
1634  }
1635 
1636  std::string filename = Pathname(url.getPathName()).basename();
1637 
1638  if ( filename == Pathname() )
1639  {
1640  // TranslatorExplanation '%s' is an URL
1641  ZYPP_THROW(RepoException(str::form( _("Invalid repo file name at '%s'"), url.asString().c_str() )));
1642  }
1643 
1644  // assert the directory exists
1645  filesystem::assert_dir(_options.knownReposPath);
1646 
1647  Pathname repofile = generateNonExistingName(_options.knownReposPath, filename);
1648  // now we have a filename that does not exists
1649  MIL << "Saving " << repos.size() << " repo" << ( repos.size() ? "s" : "" ) << " in " << repofile << endl;
1650 
1651  std::ofstream file(repofile.c_str());
1652  if (!file)
1653  {
1654  // TranslatorExplanation '%s' is a filename
1655  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), repofile.c_str() )));
1656  }
1657 
1658  for ( std::list<RepoInfo>::iterator it = repos.begin();
1659  it != repos.end();
1660  ++it )
1661  {
1662  MIL << "Saving " << (*it).alias() << endl;
1663  it->setFilepath(repofile.asString());
1664  it->dumpAsIniOn(file);
1665  reposManip().insert(*it);
1666 
1667  HistoryLog(_options.rootDir).addRepository(*it);
1668  }
1669 
1670  MIL << "done" << endl;
1671  }
1672 
1674 
1676  {
1677  ProgressData progress;
1679  progress.sendTo( ProgressReportAdaptor( progressrcv, report ) );
1680  progress.name(str::form(_("Removing repository '%s'"), info.label().c_str()));
1681 
1682  MIL << "Going to delete repo " << info.alias() << endl;
1683 
1684  for_( it, repoBegin(), repoEnd() )
1685  {
1686  // they can be the same only if the provided is empty, that means
1687  // the provided repo has no alias
1688  // then skip
1689  if ( (!info.alias().empty()) && ( info.alias() != (*it).alias() ) )
1690  continue;
1691 
1692  // TODO match by url
1693 
1694  // we have a matcing repository, now we need to know
1695  // where it does come from.
1696  RepoInfo todelete = *it;
1697  if (todelete.filepath().empty())
1698  {
1699  ZYPP_THROW(RepoException( todelete, _("Can't figure out where the repo is stored.") ));
1700  }
1701  else
1702  {
1703  // figure how many repos are there in the file:
1704  std::list<RepoInfo> filerepos = repositories_in_file(todelete.filepath());
1705  if ( (filerepos.size() == 1) && ( filerepos.front().alias() == todelete.alias() ) )
1706  {
1707  // easy, only this one, just delete the file
1708  if ( filesystem::unlink(todelete.filepath()) != 0 )
1709  {
1710  // TranslatorExplanation '%s' is a filename
1711  ZYPP_THROW(RepoException( todelete, str::form( _("Can't delete '%s'"), todelete.filepath().c_str() )));
1712  }
1713  MIL << todelete.alias() << " successfully deleted." << endl;
1714  }
1715  else
1716  {
1717  // there are more repos in the same file
1718  // write them back except the deleted one.
1719  //TmpFile tmp;
1720  //std::ofstream file(tmp.path().c_str());
1721 
1722  // assert the directory exists
1723  filesystem::assert_dir(todelete.filepath().dirname());
1724 
1725  std::ofstream file(todelete.filepath().c_str());
1726  if (!file)
1727  {
1728  // TranslatorExplanation '%s' is a filename
1729  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), todelete.filepath().c_str() )));
1730  }
1731  for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1732  fit != filerepos.end();
1733  ++fit )
1734  {
1735  if ( (*fit).alias() != todelete.alias() )
1736  (*fit).dumpAsIniOn(file);
1737  }
1738  }
1739 
1740  CombinedProgressData cSubprogrcv(progress, 20);
1741  CombinedProgressData mSubprogrcv(progress, 40);
1742  CombinedProgressData pSubprogrcv(progress, 40);
1743  // now delete it from cache
1744  if ( isCached(todelete) )
1745  cleanCache( todelete, cSubprogrcv);
1746  // now delete metadata (#301037)
1747  cleanMetadata( todelete, mSubprogrcv );
1748  cleanPackages( todelete, pSubprogrcv );
1749  reposManip().erase(todelete);
1750  MIL << todelete.alias() << " successfully deleted." << endl;
1751  HistoryLog(_options.rootDir).removeRepository(todelete);
1752  return;
1753  } // else filepath is empty
1754 
1755  }
1756  // should not be reached on a sucess workflow
1758  }
1759 
1761 
1762  void RepoManager::Impl::modifyRepository( const std::string & alias, const RepoInfo & newinfo_r, const ProgressData::ReceiverFnc & progressrcv )
1763  {
1764  RepoInfo toedit = getRepositoryInfo(alias);
1765  RepoInfo newinfo( newinfo_r ); // need writable copy to upadte housekeeping data
1766 
1767  // check if the new alias already exists when renaming the repo
1768  if ( alias != newinfo.alias() && hasRepo( newinfo.alias() ) )
1769  {
1771  }
1772 
1773  if (toedit.filepath().empty())
1774  {
1775  ZYPP_THROW(RepoException( toedit, _("Can't figure out where the repo is stored.") ));
1776  }
1777  else
1778  {
1779  // figure how many repos are there in the file:
1780  std::list<RepoInfo> filerepos = repositories_in_file(toedit.filepath());
1781 
1782  // there are more repos in the same file
1783  // write them back except the deleted one.
1784  //TmpFile tmp;
1785  //std::ofstream file(tmp.path().c_str());
1786 
1787  // assert the directory exists
1788  filesystem::assert_dir(toedit.filepath().dirname());
1789 
1790  std::ofstream file(toedit.filepath().c_str());
1791  if (!file)
1792  {
1793  // TranslatorExplanation '%s' is a filename
1794  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), toedit.filepath().c_str() )));
1795  }
1796  for ( std::list<RepoInfo>::const_iterator fit = filerepos.begin();
1797  fit != filerepos.end();
1798  ++fit )
1799  {
1800  // if the alias is different, dump the original
1801  // if it is the same, dump the provided one
1802  if ( (*fit).alias() != toedit.alias() )
1803  (*fit).dumpAsIniOn(file);
1804  else
1805  newinfo.dumpAsIniOn(file);
1806  }
1807 
1808  newinfo.setFilepath(toedit.filepath());
1809  reposManip().erase(toedit);
1810  reposManip().insert(newinfo);
1811  HistoryLog(_options.rootDir).modifyRepository(toedit, newinfo);
1812  MIL << "repo " << alias << " modified" << endl;
1813  }
1814  }
1815 
1817 
1818  RepoInfo RepoManager::Impl::getRepositoryInfo( const std::string & alias, const ProgressData::ReceiverFnc & progressrcv )
1819  {
1820  RepoConstIterator it( findAlias( alias, repos() ) );
1821  if ( it != repos().end() )
1822  return *it;
1823  RepoInfo info;
1824  info.setAlias( alias );
1826  }
1827 
1828 
1829  RepoInfo RepoManager::Impl::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
1830  {
1831  for_( it, repoBegin(), repoEnd() )
1832  {
1833  for_( urlit, (*it).baseUrlsBegin(), (*it).baseUrlsEnd() )
1834  {
1835  if ( (*urlit).asString(urlview) == url.asString(urlview) )
1836  return *it;
1837  }
1838  }
1839  RepoInfo info;
1840  info.setBaseUrl( url );
1842  }
1843 
1845  //
1846  // Services
1847  //
1849 
1851  {
1852  assert_alias( service );
1853 
1854  // check if service already exists
1855  if ( hasService( service.alias() ) )
1857 
1858  // Writable ServiceInfo is needed to save the location
1859  // of the .service file. Finaly insert into the service list.
1860  ServiceInfo toSave( service );
1861  saveService( toSave );
1862  _services.insert( toSave );
1863 
1864  // check for credentials in Url (username:password, not ?credentials param)
1865  if ( toSave.url().hasCredentialsInAuthority() )
1866  {
1868  media::CredManagerOptions(_options.rootDir) );
1869 
1871  cm.saveInUser(media::AuthData(toSave.url()));
1872  }
1873 
1874  MIL << "added service " << toSave.alias() << endl;
1875  }
1876 
1878 
1879  void RepoManager::Impl::removeService( const std::string & alias )
1880  {
1881  MIL << "Going to delete service " << alias << endl;
1882 
1883  const ServiceInfo & service = getService( alias );
1884 
1885  Pathname location = service.filepath();
1886  if( location.empty() )
1887  {
1888  ZYPP_THROW(ServiceException( service, _("Can't figure out where the service is stored.") ));
1889  }
1890 
1891  ServiceSet tmpSet;
1892  parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
1893 
1894  // only one service definition in the file
1895  if ( tmpSet.size() == 1 )
1896  {
1897  if ( filesystem::unlink(location) != 0 )
1898  {
1899  // TranslatorExplanation '%s' is a filename
1900  ZYPP_THROW(ServiceException( service, str::form( _("Can't delete '%s'"), location.c_str() ) ));
1901  }
1902  MIL << alias << " successfully deleted." << endl;
1903  }
1904  else
1905  {
1906  filesystem::assert_dir(location.dirname());
1907 
1908  std::ofstream file(location.c_str());
1909  if( !file )
1910  {
1911  // TranslatorExplanation '%s' is a filename
1912  ZYPP_THROW( Exception(str::form( _("Can't open file '%s' for writing."), location.c_str() )));
1913  }
1914 
1915  for_(it, tmpSet.begin(), tmpSet.end())
1916  {
1917  if( it->alias() != alias )
1918  it->dumpAsIniOn(file);
1919  }
1920 
1921  MIL << alias << " successfully deleted from file " << location << endl;
1922  }
1923 
1924  // now remove all repositories added by this service
1925  RepoCollector rcollector;
1926  getRepositoriesInService( alias,
1927  boost::make_function_output_iterator( bind( &RepoCollector::collect, &rcollector, _1 ) ) );
1928  // cannot do this directly in getRepositoriesInService - would invalidate iterators
1929  for_(rit, rcollector.repos.begin(), rcollector.repos.end())
1930  removeRepository(*rit);
1931  }
1932 
1934 
1936  {
1937  // copy the set of services since refreshService
1938  // can eventually invalidate the iterator
1939  ServiceSet services( serviceBegin(), serviceEnd() );
1940  for_( it, services.begin(), services.end() )
1941  {
1942  if ( !it->enabled() )
1943  continue;
1944 
1945  try {
1946  refreshService(*it, options_r);
1947  }
1948  catch ( const repo::ServicePluginInformalException & e )
1949  { ;/* ignore ServicePluginInformalException */ }
1950  }
1951  }
1952 
1953  void RepoManager::Impl::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
1954  {
1955  ServiceInfo service( getService( alias ) );
1956  assert_alias( service );
1957  assert_url( service );
1958  // NOTE: It might be necessary to modify and rewrite the service info.
1959  // Either when probing the type, or when adjusting the repositories
1960  // enable/disable state.:
1961  bool serviceModified = false;
1962  MIL << "Going to refresh service '" << service.alias() << "', url: "<< service.url() << ", opts: " << options_r << endl;
1963 
1965 
1966  // if the type is unknown, try probing.
1967  if ( service.type() == repo::ServiceType::NONE )
1968  {
1969  repo::ServiceType type = probeService( service.url() );
1970  if ( type != ServiceType::NONE )
1971  {
1972  service.setProbedType( type ); // lazy init!
1973  serviceModified = true;
1974  }
1975  }
1976 
1977  // get target distro identifier
1978  std::string servicesTargetDistro = _options.servicesTargetDistro;
1979  if ( servicesTargetDistro.empty() )
1980  {
1981  servicesTargetDistro = Target::targetDistribution( Pathname() );
1982  }
1983  DBG << "ServicesTargetDistro: " << servicesTargetDistro << endl;
1984 
1985  // parse it
1986  RepoCollector collector(servicesTargetDistro);
1987  // FIXME Ugly hack: ServiceRepos may throw ServicePluginInformalException
1988  // which is actually a notification. Using an exception for this
1989  // instead of signal/callback is bad. Needs to be fixed here, in refreshServices()
1990  // and in zypper.
1991  std::pair<DefaultIntegral<bool,false>, repo::ServicePluginInformalException> uglyHack;
1992  try {
1993  ServiceRepos repos(service, bind( &RepoCollector::collect, &collector, _1 ));
1994  }
1995  catch ( const repo::ServicePluginInformalException & e )
1996  {
1997  /* ignore ServicePluginInformalException and throw later */
1998  uglyHack.first = true;
1999  uglyHack.second = e;
2000  }
2001 
2003  // On the fly remember the new repo states as defined the reopoindex.xml.
2004  // Move into ServiceInfo later.
2005  ServiceInfo::RepoStates newRepoStates;
2006 
2007  // set service alias and base url for all collected repositories
2008  for_( it, collector.repos.begin(), collector.repos.end() )
2009  {
2010  // First of all: Prepend service alias:
2011  it->setAlias( str::form( "%s:%s", service.alias().c_str(), it->alias().c_str() ) );
2012  // set refrence to the parent service
2013  it->setService( service.alias() );
2014 
2015  // remember the new parsed repo state
2016  newRepoStates[it->alias()] = *it;
2017 
2018  // if the repo url was not set by the repoindex parser, set service's url
2019  Url url;
2020  if ( it->baseUrlsEmpty() )
2021  url = service.rawUrl();
2022  else
2023  {
2024  // service repo can contain only one URL now, so no need to iterate.
2025  url = it->rawUrl(); // raw!
2026  }
2027 
2028  // libzypp currently has problem with separate url + path handling
2029  // so just append the path to the baseurl
2030  if ( !it->path().empty() )
2031  {
2032  Pathname path(url.getPathName());
2033  path /= it->path();
2034  url.setPathName( path.asString() );
2035  it->setPath("");
2036  }
2037 
2038  // save the url
2039  it->setBaseUrl( url );
2040  }
2041 
2043  // Now compare collected repos with the ones in the system...
2044  //
2045  RepoInfoList oldRepos;
2046  getRepositoriesInService( service.alias(), std::back_inserter( oldRepos ) );
2047 
2049  // find old repositories to remove...
2050  for_( oldRepo, oldRepos.begin(), oldRepos.end() )
2051  {
2052  if ( ! foundAliasIn( oldRepo->alias(), collector.repos ) )
2053  {
2054  if ( oldRepo->enabled() )
2055  {
2056  // Currently enabled. If this was a user modification remember the state.
2057  const auto & last = service.repoStates().find( oldRepo->alias() );
2058  if ( last != service.repoStates().end() && ! last->second.enabled )
2059  {
2060  DBG << "Service removes user enabled repo " << oldRepo->alias() << endl;
2061  service.addRepoToEnable( oldRepo->alias() );
2062  serviceModified = true;
2063  }
2064  else
2065  DBG << "Service removes enabled repo " << oldRepo->alias() << endl;
2066  }
2067  else
2068  DBG << "Service removes disabled repo " << oldRepo->alias() << endl;
2069 
2070  removeRepository( *oldRepo );
2071  }
2072  }
2073 
2075  // create missing repositories and modify exising ones if needed...
2076  for_( it, collector.repos.begin(), collector.repos.end() )
2077  {
2078  // User explicitly requested the repo being enabled?
2079  // User explicitly requested the repo being disabled?
2080  // And hopefully not both ;) If so, enable wins.
2081 
2082  TriBool toBeEnabled( indeterminate ); // indeterminate - follow the service request
2083  DBG << "Service request to " << (it->enabled()?"enable":"disable") << " service repo " << it->alias() << endl;
2084 
2085  if ( options_r.testFlag( RefreshService_restoreStatus ) )
2086  {
2087  DBG << "Opt RefreshService_restoreStatus " << it->alias() << endl;
2088  // this overrides any pending request!
2089  // Remove from enable request list.
2090  // NOTE: repoToDisable is handled differently.
2091  // It gets cleared on each refresh.
2092  service.delRepoToEnable( it->alias() );
2093  // toBeEnabled stays indeterminate!
2094  }
2095  else
2096  {
2097  if ( service.repoToEnableFind( it->alias() ) )
2098  {
2099  DBG << "User request to enable service repo " << it->alias() << endl;
2100  toBeEnabled = true;
2101  // Remove from enable request list.
2102  // NOTE: repoToDisable is handled differently.
2103  // It gets cleared on each refresh.
2104  service.delRepoToEnable( it->alias() );
2105  serviceModified = true;
2106  }
2107  else if ( service.repoToDisableFind( it->alias() ) )
2108  {
2109  DBG << "User request to disable service repo " << it->alias() << endl;
2110  toBeEnabled = false;
2111  }
2112  }
2113 
2114  RepoInfoList::iterator oldRepo( findAlias( it->alias(), oldRepos ) );
2115  if ( oldRepo == oldRepos.end() )
2116  {
2117  // Not found in oldRepos ==> a new repo to add
2118 
2119  // Make sure the service repo is created with the appropriate enablement
2120  if ( ! indeterminate(toBeEnabled) )
2121  it->setEnabled( toBeEnabled );
2122 
2123  DBG << "Service adds repo " << it->alias() << " " << (it->enabled()?"enabled":"disabled") << endl;
2124  addRepository( *it );
2125  }
2126  else
2127  {
2128  // ==> an exising repo to check
2129  bool oldRepoModified = false;
2130 
2131  if ( indeterminate(toBeEnabled) )
2132  {
2133  // No user request: check for an old user modificaton otherwise follow service request.
2134  // NOTE: Assert toBeEnabled is boolean afterwards!
2135  if ( oldRepo->enabled() == it->enabled() )
2136  toBeEnabled = it->enabled(); // service requests no change to the system
2137  else if (options_r.testFlag( RefreshService_restoreStatus ) )
2138  {
2139  toBeEnabled = it->enabled(); // RefreshService_restoreStatus forced
2140  DBG << "Opt RefreshService_restoreStatus " << it->alias() << " forces " << (toBeEnabled?"enabled":"disabled") << endl;
2141  }
2142  else
2143  {
2144  const auto & last = service.repoStates().find( oldRepo->alias() );
2145  if ( last == service.repoStates().end() || last->second.enabled != it->enabled() )
2146  toBeEnabled = it->enabled(); // service request has changed since last refresh -> follow
2147  else
2148  {
2149  toBeEnabled = oldRepo->enabled(); // service request unchaned since last refresh -> keep user modification
2150  DBG << "User modified service repo " << it->alias() << " may stay " << (toBeEnabled?"enabled":"disabled") << endl;
2151  }
2152  }
2153  }
2154 
2155  // changed enable?
2156  if ( toBeEnabled == oldRepo->enabled() )
2157  {
2158  DBG << "Service repo " << it->alias() << " stays " << (oldRepo->enabled()?"enabled":"disabled") << endl;
2159  }
2160  else if ( toBeEnabled )
2161  {
2162  DBG << "Service repo " << it->alias() << " gets enabled" << endl;
2163  oldRepo->setEnabled( true );
2164  oldRepoModified = true;
2165  }
2166  else
2167  {
2168  DBG << "Service repo " << it->alias() << " gets disabled" << endl;
2169  oldRepo->setEnabled( false );
2170  oldRepoModified = true;
2171  }
2172 
2173  // all other attributes follow the service request:
2174 
2175  // changed name (raw!)
2176  if ( oldRepo->rawName() != it->rawName() )
2177  {
2178  DBG << "Service repo " << it->alias() << " gets new NAME " << it->rawName() << endl;
2179  oldRepo->setName( it->rawName() );
2180  oldRepoModified = true;
2181  }
2182 
2183  // changed autorefresh
2184  if ( oldRepo->autorefresh() != it->autorefresh() )
2185  {
2186  DBG << "Service repo " << it->alias() << " gets new AUTOREFRESH " << it->autorefresh() << endl;
2187  oldRepo->setAutorefresh( it->autorefresh() );
2188  oldRepoModified = true;
2189  }
2190 
2191  // changed priority?
2192  if ( oldRepo->priority() != it->priority() )
2193  {
2194  DBG << "Service repo " << it->alias() << " gets new PRIORITY " << it->priority() << endl;
2195  oldRepo->setPriority( it->priority() );
2196  oldRepoModified = true;
2197  }
2198 
2199  // changed url?
2200  // service repo can contain only one URL now, so no need to iterate.
2201  if ( oldRepo->rawUrl() != it->rawUrl() )
2202  {
2203  DBG << "Service repo " << it->alias() << " gets new URL " << it->rawUrl() << endl;
2204  oldRepo->setBaseUrl( it->rawUrl() );
2205  oldRepoModified = true;
2206  }
2207 
2208  // save if modified:
2209  if ( oldRepoModified )
2210  {
2211  modifyRepository( oldRepo->alias(), *oldRepo );
2212  }
2213  }
2214  }
2215 
2216  // Unlike reposToEnable, reposToDisable is always cleared after refresh.
2217  if ( ! service.reposToDisableEmpty() )
2218  {
2219  service.clearReposToDisable();
2220  serviceModified = true;
2221  }
2222 
2223  // Remember original service request for next refresh
2224  if ( service.repoStates() != newRepoStates )
2225  {
2226  service.setRepoStates( std::move(newRepoStates) );
2227  serviceModified = true;
2228  }
2229 
2231  // save service if modified: (unless a plugin service)
2232  if ( serviceModified && service.type() != ServiceType::PLUGIN )
2233  {
2234  // write out modified service file.
2235  modifyService( service.alias(), service );
2236  }
2237 
2238  if ( uglyHack.first )
2239  {
2240  throw( uglyHack.second ); // intentionally not ZYPP_THROW
2241  }
2242  }
2243 
2245 
2246  void RepoManager::Impl::modifyService( const std::string & oldAlias, const ServiceInfo & newService )
2247  {
2248  MIL << "Going to modify service " << oldAlias << endl;
2249 
2250  // we need a writable copy to link it to the file where
2251  // it is saved if we modify it
2252  ServiceInfo service(newService);
2253 
2254  if ( service.type() == ServiceType::PLUGIN )
2255  {
2257  }
2258 
2259  const ServiceInfo & oldService = getService(oldAlias);
2260 
2261  Pathname location = oldService.filepath();
2262  if( location.empty() )
2263  {
2264  ZYPP_THROW(ServiceException( oldService, _("Can't figure out where the service is stored.") ));
2265  }
2266 
2267  // remember: there may multiple services being defined in one file:
2268  ServiceSet tmpSet;
2269  parser::ServiceFileReader( location, ServiceCollector(tmpSet) );
2270 
2271  filesystem::assert_dir(location.dirname());
2272  std::ofstream file(location.c_str());
2273  for_(it, tmpSet.begin(), tmpSet.end())
2274  {
2275  if( *it != oldAlias )
2276  it->dumpAsIniOn(file);
2277  }
2278  service.dumpAsIniOn(file);
2279  file.close();
2280  service.setFilepath(location);
2281 
2282  _services.erase(oldAlias);
2283  _services.insert(service);
2284 
2285  // changed properties affecting also repositories
2286  if ( oldAlias != service.alias() // changed alias
2287  || oldService.enabled() != service.enabled() ) // changed enabled status
2288  {
2289  std::vector<RepoInfo> toModify;
2290  getRepositoriesInService(oldAlias, std::back_inserter(toModify));
2291  for_( it, toModify.begin(), toModify.end() )
2292  {
2293  if ( oldService.enabled() != service.enabled() )
2294  {
2295  if ( service.enabled() )
2296  {
2297  // reset to last refreshs state
2298  const auto & last = service.repoStates().find( it->alias() );
2299  if ( last != service.repoStates().end() )
2300  it->setEnabled( last->second.enabled );
2301  }
2302  else
2303  it->setEnabled( false );
2304  }
2305 
2306  if ( oldAlias != service.alias() )
2307  it->setService(service.alias());
2308 
2309  modifyRepository(it->alias(), *it);
2310  }
2311  }
2312 
2314  }
2315 
2317 
2319  {
2320  try
2321  {
2322  MediaSetAccess access(url);
2323  if ( access.doesFileExist("/repo/repoindex.xml") )
2324  return repo::ServiceType::RIS;
2325  }
2326  catch ( const media::MediaException &e )
2327  {
2328  ZYPP_CAUGHT(e);
2329  // TranslatorExplanation '%s' is an URL
2330  RepoException enew(str::form( _("Error trying to read from '%s'"), url.asString().c_str() ));
2331  enew.remember(e);
2332  ZYPP_THROW(enew);
2333  }
2334  catch ( const Exception &e )
2335  {
2336  ZYPP_CAUGHT(e);
2337  // TranslatorExplanation '%s' is an URL
2338  Exception enew(str::form( _("Unknown error reading from '%s'"), url.asString().c_str() ));
2339  enew.remember(e);
2340  ZYPP_THROW(enew);
2341  }
2342 
2343  return repo::ServiceType::NONE;
2344  }
2345 
2347  //
2348  // CLASS NAME : RepoManager
2349  //
2351 
2353  : _pimpl( new Impl(opt) )
2354  {}
2355 
2357  {}
2358 
2360  { return _pimpl->repoEmpty(); }
2361 
2363  { return _pimpl->repoSize(); }
2364 
2366  { return _pimpl->repoBegin(); }
2367 
2369  { return _pimpl->repoEnd(); }
2370 
2371  RepoInfo RepoManager::getRepo( const std::string & alias ) const
2372  { return _pimpl->getRepo( alias ); }
2373 
2374  bool RepoManager::hasRepo( const std::string & alias ) const
2375  { return _pimpl->hasRepo( alias ); }
2376 
2377  std::string RepoManager::makeStupidAlias( const Url & url_r )
2378  {
2379  std::string ret( url_r.getScheme() );
2380  if ( ret.empty() )
2381  ret = "repo-";
2382  else
2383  ret += "-";
2384 
2385  std::string host( url_r.getHost() );
2386  if ( ! host.empty() )
2387  {
2388  ret += host;
2389  ret += "-";
2390  }
2391 
2392  static Date::ValueType serial = Date::now();
2393  ret += Digest::digest( Digest::sha1(), str::hexstring( ++serial ) +url_r.asCompleteString() ).substr(0,8);
2394  return ret;
2395  }
2396 
2398  { return _pimpl->metadataStatus( info ); }
2399 
2401  { return _pimpl->checkIfToRefreshMetadata( info, url, policy ); }
2402 
2403  Pathname RepoManager::metadataPath( const RepoInfo &info ) const
2404  { return _pimpl->metadataPath( info ); }
2405 
2406  Pathname RepoManager::packagesPath( const RepoInfo &info ) const
2407  { return _pimpl->packagesPath( info ); }
2408 
2410  { return _pimpl->refreshMetadata( info, policy, progressrcv ); }
2411 
2412  void RepoManager::cleanMetadata( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2413  { return _pimpl->cleanMetadata( info, progressrcv ); }
2414 
2415  void RepoManager::cleanPackages( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2416  { return _pimpl->cleanPackages( info, progressrcv ); }
2417 
2419  { return _pimpl->cacheStatus( info ); }
2420 
2421  void RepoManager::buildCache( const RepoInfo &info, CacheBuildPolicy policy, const ProgressData::ReceiverFnc & progressrcv )
2422  { return _pimpl->buildCache( info, policy, progressrcv ); }
2423 
2424  void RepoManager::cleanCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2425  { return _pimpl->cleanCache( info, progressrcv ); }
2426 
2427  bool RepoManager::isCached( const RepoInfo &info ) const
2428  { return _pimpl->isCached( info ); }
2429 
2430  void RepoManager::loadFromCache( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2431  { return _pimpl->loadFromCache( info, progressrcv ); }
2432 
2434  { return _pimpl->cleanCacheDirGarbage( progressrcv ); }
2435 
2436  repo::RepoType RepoManager::probe( const Url & url, const Pathname & path ) const
2437  { return _pimpl->probe( url, path ); }
2438 
2440  { return _pimpl->probe( url ); }
2441 
2442  void RepoManager::addRepository( const RepoInfo &info, const ProgressData::ReceiverFnc & progressrcv )
2443  { return _pimpl->addRepository( info, progressrcv ); }
2444 
2445  void RepoManager::addRepositories( const Url &url, const ProgressData::ReceiverFnc & progressrcv )
2446  { return _pimpl->addRepositories( url, progressrcv ); }
2447 
2448  void RepoManager::removeRepository( const RepoInfo & info, const ProgressData::ReceiverFnc & progressrcv )
2449  { return _pimpl->removeRepository( info, progressrcv ); }
2450 
2451  void RepoManager::modifyRepository( const std::string &alias, const RepoInfo & newinfo, const ProgressData::ReceiverFnc & progressrcv )
2452  { return _pimpl->modifyRepository( alias, newinfo, progressrcv ); }
2453 
2454  RepoInfo RepoManager::getRepositoryInfo( const std::string &alias, const ProgressData::ReceiverFnc & progressrcv )
2455  { return _pimpl->getRepositoryInfo( alias, progressrcv ); }
2456 
2457  RepoInfo RepoManager::getRepositoryInfo( const Url & url, const url::ViewOption & urlview, const ProgressData::ReceiverFnc & progressrcv )
2458  { return _pimpl->getRepositoryInfo( url, urlview, progressrcv ); }
2459 
2461  { return _pimpl->serviceEmpty(); }
2462 
2464  { return _pimpl->serviceSize(); }
2465 
2467  { return _pimpl->serviceBegin(); }
2468 
2470  { return _pimpl->serviceEnd(); }
2471 
2472  ServiceInfo RepoManager::getService( const std::string & alias ) const
2473  { return _pimpl->getService( alias ); }
2474 
2475  bool RepoManager::hasService( const std::string & alias ) const
2476  { return _pimpl->hasService( alias ); }
2477 
2479  { return _pimpl->probeService( url ); }
2480 
2481  void RepoManager::addService( const std::string & alias, const Url& url )
2482  { return _pimpl->addService( alias, url ); }
2483 
2484  void RepoManager::addService( const ServiceInfo & service )
2485  { return _pimpl->addService( service ); }
2486 
2487  void RepoManager::removeService( const std::string & alias )
2488  { return _pimpl->removeService( alias ); }
2489 
2490  void RepoManager::removeService( const ServiceInfo & service )
2491  { return _pimpl->removeService( service ); }
2492 
2494  { return _pimpl->refreshServices( options_r ); }
2495 
2496  void RepoManager::refreshService( const std::string & alias, const RefreshServiceOptions & options_r )
2497  { return _pimpl->refreshService( alias, options_r ); }
2498 
2499  void RepoManager::refreshService( const ServiceInfo & service, const RefreshServiceOptions & options_r )
2500  { return _pimpl->refreshService( service, options_r ); }
2501 
2502  void RepoManager::modifyService( const std::string & oldAlias, const ServiceInfo & service )
2503  { return _pimpl->modifyService( oldAlias, service ); }
2504 
2506 
2507  std::ostream & operator<<( std::ostream & str, const RepoManager & obj )
2508  { return str << *obj._pimpl; }
2509 
2511 } // 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:329
void removeService(const std::string &alias)
Removes service specified by its name.
Service data.
Definition: ServiceInfo.h:35
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:554
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:696
RepoStatus status(MediaSetAccess &media)
Status of the remote repository.
Definition: Downloader.cc:39
void setCacheStatus(const RepoInfo &info, const RepoStatus &status)
Definition: RepoManager.cc:593
std::string generateFilename(const ServiceInfo &info) const
Definition: RepoManager.cc:590
thrown when it was impossible to determine this repo type.
std::string digest()
get hex string representation of the digest
Definition: Digest.cc:183
Retrieval of repository list for a service.
Definition: ServiceRepos.h:26
virtual std::ostream & dumpAsIniOn(std::ostream &str) const
Write this RepoInfo object into str in a .repo file format.
Definition: RepoInfo.cc:576
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:551
static ZConfig & instance()
Singleton ctor.
Definition: ZConfig.cc:674
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:693
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:529
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)
Definition: Gettext.h:30
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:194
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:396
RepoSet::size_type RepoSizeType
Definition: RepoManager.h:121
bool empty() const
Whether the status is empty (default constucted)
Definition: RepoStatus.cc:136
void loadFromCache(const RepoInfo &info, const ProgressData::ReceiverFnc &progressrcv=ProgressData::ReceiverFnc())
Load resolvables into the pool.
ServiceConstIterator serviceEnd() const
Iterator to place behind last service in internal storage.
repo::RepoType probe(const Url &url, const Pathname &path) const
Probe repo metadata type.
std::string generateFilename(const RepoInfo &info) const
Definition: RepoManager.cc:587
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:565
void touchIndexFile(const RepoInfo &info)
Definition: RepoManager.cc:843
void setAlias(const std::string &alias)
set the repository alias
Definition: RepoInfoBase.cc:94
void addRepoToEnable(const std::string &alias_r)
Add alias_r to the set of ReposToEnable.
Definition: ServiceInfo.cc:131
void removeRepository(const RepoInfo &info, OPT_PROGRESS)
RefreshServiceFlags RefreshServiceOptions
Options tuning RefreshService.
Definition: RepoManager.h:149
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:335
void refreshService(const std::string &alias, const RefreshServiceOptions &options_r=RefreshServiceOptions())
Refresh specific service.
bool doesFileExist(const Pathname &file, unsigned media_nr=1)
Checks if a file exists on the specified media, with user callbacks.
void setFilepath(const Pathname &filename)
set the path to the .repo file
What is known about a repository.
Definition: RepoInfo.h:71
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:615
#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:171
void setBaseUrl(const Url &url)
Clears current base URL list and adds url.
Definition: RepoInfo.cc:323
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:105
Service already exists and some unique attribute can't be duplicated.
void refreshService(const ServiceInfo &service, const RefreshServiceOptions &options_r)
Definition: RepoManager.cc:575
bool repo_add_probe() const
Whether repository urls should be probed.
Definition: ZConfig.cc:840
urls_const_iterator baseUrlsEnd() const
iterator that points at end of repository urls
Definition: RepoInfo.cc:399
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:36
static RepoStatus fromCookieFile(const Pathname &path)
Reads the status from a cookie file.
Definition: RepoStatus.cc:108
Service without alias was used in an operation.
RepoStatus metadataStatus(const RepoInfo &info) const
Definition: RepoManager.cc:808
RepoSet::const_iterator RepoConstIterator
Definition: RepoManager.h:120
function< bool(const ProgressData &)> ReceiverFnc
Most simple version of progress reporting The percentage in most cases.
Definition: ProgressData.h:139
Url::asString() view options.
Definition: UrlBase.h:39
void cleanMetadata(const RepoInfo &info, OPT_PROGRESS)
#define ERR
Definition: Logger.h:49
unsigned int MediaAccessId
Media manager access Id type.
Definition: MediaSource.h:29
repo::RepoType probeCache(const Pathname &path_r) const
Probe Metadata in a local cache directory.
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:619
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:557
RepoSizeType repoSize() const
Repo manager settings.
Definition: RepoManager.h:53
boost::logic::tribool TriBool
3-state boolean logic (true, false and indeterminate).
Definition: String.h:29
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:313
void removeService(const ServiceInfo &service)
Definition: RepoManager.cc:569
transform_iterator< repo::RepoVariablesUrlReplacer, url_set::const_iterator > urls_const_iterator
Definition: RepoInfo.h:101
Progress callback from another progress.
Definition: ProgressData.h:390
std::map< std::string, RepoState > RepoStates
Definition: ServiceInfo.h:158
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:119
bool toMin()
Set counter value to current min value.
Definition: ProgressData.h:269
RepoInfo getRepositoryInfo(const std::string &alias, OPT_PROGRESS)
Downloader for SUSETags (YaST2) repositories Encapsulates all the knowledge of which files have to be...
Definition: Downloader.h:34
boost::noncopyable NonCopyable
Ensure derived classes cannot be copied.
Definition: NonCopyable.h:26
static Pool instance()
Singleton ctor.
Definition: Pool.h:52
bool serviceEmpty() const
Definition: RepoManager.cc:549
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:96
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:40
void clearReposToDisable()
Clear the set of ReposToDisable.
Definition: ServiceInfo.cc:168
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:668
thrown when it was impossible to determine one url for this repo.
Definition: RepoException.h:78
Just inherits Exception to separate media exceptions.
static const ServiceType NONE
No service set.
Definition: ServiceType.h:34
static const SolvAttr repositoryToolVersion
Definition: SolvAttr.h:173
Service type enumeration.
Definition: ServiceType.h:26
void modifyRepository(const std::string &alias, const RepoInfo &newinfo_r, OPT_PROGRESS)
ServiceSet::const_iterator ServiceConstIterator
Definition: RepoManager.h:115
void setRepoStates(RepoStates newStates_r)
Remember a new set of repository states.
Definition: ServiceInfo.cc:174
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:422
#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:339
void setType(const repo::RepoType &t)
set the repository type
Definition: RepoInfo.cc:332
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:532
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:673
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)
Definition: Gettext.h:29
static const ServiceType PLUGIN
Plugin services are scripts installed on your system that provide the package manager with repositori...
Definition: ServiceType.h:43
Base Exception for service handling.
std::string receiveLine()
Read one line from the input stream.
void delRepoToEnable(const std::string &alias_r)
Remove alias_r from the set of ReposToEnable.
Definition: ServiceInfo.cc:137
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:271
ServiceSet::size_type ServiceSizeType
Definition: RepoManager.h:116
Class for handling media authentication data.
Definition: MediaUserAuth.h:30
bool reposToDisableEmpty() const
Definition: ServiceInfo.cc:144
static const RepoType NONE
Definition: RepoType.h:32
int touch(const Pathname &path)
Change file's modification and access times.
Definition: PathInfo.cc:1142
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:603
void setPackagesPath(const Pathname &path)
set the path where the local packages are stored
Definition: RepoInfo.cc:342
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
Temporarily disable MediaChangeReport Sometimes helpful to suppress interactive messages connected to...
int close()
Wait for the progamm to complete.
bool hasRepo(const std::string &alias) const
Return whether there is a known repository for alias.
static const RepoType RPMMD
Definition: RepoType.h:29
creates and provides information about known sources.
Definition: RepoManager.h:105
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:324
RepoStatus cacheStatus(const RepoInfo &info) const
Status of metadata cache.
repo::RepoType type() const
Type of repository,.
Definition: RepoInfo.cc:363
int readdir(std::list< std::string > &retlist_r, const Pathname &path_r, bool dots_r)
Return content of directory via retlist.
Definition: PathInfo.cc:604
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.
Url rawUrl() const
The service raw url (no variables replaced)
Definition: ServiceInfo.cc:102
static const RepoType YAST2
Definition: RepoType.h:30
ServiceSet & _services
Definition: RepoManager.cc: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:111
Type toEnum() const
Definition: RepoType.h:48
Exception for repository handling.
Definition: RepoException.h:37
void saveService(ServiceInfo &service) const
Definition: RepoManager.cc:639
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
Probe the metadata type of a repository located at url.
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:178
DefaultIntegral< bool, false > _reposDirty
Definition: RepoManager.cc:623
value_type val() const
Definition: ProgressData.h:295
ServiceConstIterator serviceEnd() const
Definition: RepoManager.cc:552
Functor thats filter RepoInfo by service which it belongs to.
Definition: RepoManager.h:636
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:60
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:156
static const RepoInfo noRepo
Represents no Repository (one with an empty alias).
Definition: RepoInfo.h:80
bool regex_match(const std::string &s, smatch &matches, const regex &regex)
regex ZYPP_STR_REGEX regex ZYPP_STR_REGEX
Definition: Regex.h:70
Thrown when the repo alias is found to be invalid.
ServiceSizeType serviceSize() const
Gets count of service in RepoManager (in specified location)
static const RepoType RPMPLAINDIR
Definition: RepoType.h:31
static const std::string & systemRepoAlias()
Reserved system repository alias .
Definition: Repository.cc:37
bool repoToEnableFind(const std::string &alias_r) const
Whether alias_r is mentioned in ReposToEnable.
Definition: ServiceInfo.cc:128
ServiceSizeType serviceSize() const
Definition: RepoManager.cc:550
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:843
Repository already exists and some unique attribute can't be duplicated.
ServiceConstIterator serviceBegin() const
Iterator to first service in internal storage.
bool set(value_type val_r)
Set new counter value.
Definition: ProgressData.h:246
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:527
Url url() const
The service url.
Definition: ServiceInfo.cc:99
static bool schemeIsDownloading(const std::string &scheme_r)
http https ftp sftp tftp
Definition: Url.cc:474
void modifyRepository(const RepoInfo &oldrepo, const RepoInfo &newrepo)
Log certain modifications to a repository.
Definition: HistoryLog.cc:268
std::ostream & operator<<(std::ostream &str, const RepoManager::Impl &obj)
Definition: RepoManager.cc:634
Impl * clone() const
clone for RWCOW_pointer
Definition: RepoManager.cc:628
urls_size_type baseUrlsSize() const
number of repository urls
Definition: RepoInfo.cc:402
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:151
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
void setProbedType(const repo::ServiceType &t) const
Lazy init service type.
Definition: ServiceInfo.cc:113
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:306
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:384
#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:185
repo::ServiceType type() const
Service type.
Definition: ServiceInfo.cc:108
iterator begin() const
Iterator to the begin of query results.
Definition: LookupAttr.cc:236
Repository type enumeration.
Definition: RepoType.h:27
RefreshCheckStatus checkIfToRefreshMetadata(const RepoInfo &info, const Url &url, RawMetadataRefreshPolicy policy)
Definition: RepoManager.cc:880
repo::ServiceType probeService(const Url &url) const