libzypp  13.10.6
RepoProvideFile.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
12 #include <iostream>
13 #include <fstream>
14 #include <sstream>
15 #include <set>
16 
17 #include "zypp/base/Gettext.h"
18 #include "zypp/base/Logger.h"
19 #include "zypp/base/String.h"
22 #include "zypp/ZYppCallbacks.h"
23 #include "zypp/MediaSetAccess.h"
24 #include "zypp/ZConfig.h"
25 #include "zypp/ZYppFactory.h"
28 
31 #include "zypp/FileChecker.h"
32 #include "zypp/Fetcher.h"
33 
34 using std::endl;
35 using std::set;
36 
38 namespace zypp
39 {
40  namespace repo
42  {
43 
45  //
46  // provideFile
47  //
49 
51  namespace
52  {
53 
59  struct DownloadFileReportHack : public callback::ReceiveReport<media::DownloadProgressReport>
60  {
61  typedef callback::ReceiveReport<ReportType> BaseType;
62  typedef function<bool(int)> RedirectType;
63 
64  DownloadFileReportHack( RedirectType redirect_r )
65  : _oldRec( Distributor::instance().getReceiver() )
66  , _redirect( redirect_r )
67  { connect(); }
68  ~DownloadFileReportHack()
69  { if ( _oldRec ) Distributor::instance().setReceiver( *_oldRec ); else Distributor::instance().noReceiver(); }
70 
71  virtual void start( const Url & file, Pathname localfile )
72  {
73  if ( _oldRec )
74  _oldRec->start( file, localfile );
75  else
76  BaseType::start( file, localfile );
77  }
78 
79  virtual bool progress( int value, const Url & file, double dbps_avg = -1, double dbps_current = -1 )
80  {
81  bool ret = true;
82  if ( _oldRec )
83  ret &= _oldRec->progress( value, file, dbps_avg, dbps_current );
84  if ( _redirect )
85  ret &= _redirect( value );
86  return ret;
87  }
88 
89  virtual Action problem( const Url & file, Error error, const std::string & description )
90  {
91  if ( _oldRec )
92  return _oldRec->problem( file, error, description );
93  return BaseType::problem( file, error, description );
94  }
95  virtual void finish( const Url & file, Error error, const std::string & reason )
96  {
97  if ( _oldRec )
98  _oldRec->finish( file, error, reason );
99  else
100  BaseType::finish( file, error, reason );
101  }
102 
103  private:
104  Receiver * _oldRec;
105  RedirectType _redirect;
106  };
107 
109  } // namespace
111 
113  const OnMediaLocation & loc_r,
114  const ProvideFilePolicy & policy_r )
115  {
116  RepoMediaAccess access;
117  return access.provideFile(repo_r, loc_r, policy_r );
118  }
119 
122  {
123  public:
124  Impl( const ProvideFilePolicy & defaultPolicy_r )
125  : _defaultPolicy( defaultPolicy_r )
126  {}
127 
129  {
130  std::map<Url, shared_ptr<MediaSetAccess> >::iterator it;
131  for ( it = _medias.begin();
132  it != _medias.end();
133  ++it )
134  {
135  it->second->release();
136  }
137  }
138 
146  shared_ptr<MediaSetAccess> mediaAccessForUrl( const Url &url, RepoInfo repo )
147  {
148  std::map<Url, shared_ptr<MediaSetAccess> >::const_iterator it;
149  it = _medias.find(url);
150  shared_ptr<MediaSetAccess> media;
151  if ( it != _medias.end() )
152  {
153  media = it->second;
154  }
155  else
156  {
157  media.reset( new MediaSetAccess(url) );
158  _medias[url] = media;
159  }
160  setVerifierForRepo( repo, media );
161  return media;
162  }
163 
164  private:
165  void setVerifierForRepo( RepoInfo repo, shared_ptr<MediaSetAccess> media )
166  {
167  // Always set the MediaSetAccess label.
168  media->setLabel( repo.name() );
169 
170  // set a verifier if the repository has it
171 
172  Pathname mediafile = repo.metadataPath() + "/media.1/media";
173  if ( ! repo.metadataPath().empty() )
174  {
175  if ( PathInfo(mediafile).isExist() )
176  {
177  std::map<shared_ptr<MediaSetAccess>, RepoInfo>::const_iterator it;
178  it = _verifier.find(media);
179  if ( it != _verifier.end() )
180  {
181  if ( it->second.alias() == repo.alias() )
182  {
183  // this media is already using this repo verifier
184  return;
185  }
186  }
187 
188  std::ifstream str(mediafile.asString().c_str());
189  std::string vendor;
190  std::string mediaid;
191  std::string buffer;
192  if ( str )
193  {
194  getline(str, vendor);
195  getline(str, mediaid);
196  getline(str, buffer);
197 
198  unsigned media_nr = str::strtonum<unsigned>(buffer);
199  MIL << "Repository '" << repo.alias() << "' has " << media_nr << " medias"<< endl;
200 
201  for ( unsigned i=1; i <= media_nr; ++i )
202  {
203  media::MediaVerifierRef verifier( new repo::SUSEMediaVerifier( vendor, mediaid, i ) );
204 
205  media->setVerifier( i, verifier);
206  }
207  _verifier[media] = repo;
208  }
209  else
210  {
212  }
213  }
214  else
215  {
216  WAR << "No media verifier for repo '" << repo.alias() << "' media/media.1 does not exist in '" << repo.metadataPath() << "'" << endl;
217  }
218  }
219  else
220  {
221  WAR << "'" << repo.alias() << "' metadata path is empty. Can't set verifier. Probably this repository does not come from RepoManager." << endl;
222  }
223  }
224 
225  private:
226  std::map<shared_ptr<MediaSetAccess>, RepoInfo> _verifier;
227  std::map<Url, shared_ptr<MediaSetAccess> > _medias;
228 
229  public:
231  };
233 
234 
236  : _impl( new Impl( defaultPolicy_r ) )
237  {}
238 
240  {}
241 
243  { _impl->_defaultPolicy = policy_r; }
244 
246  { return _impl->_defaultPolicy; }
247 
249  const OnMediaLocation & loc_r,
250  const ProvideFilePolicy & policy_r )
251  {
252  MIL << loc_r << endl;
253  // Arrange DownloadFileReportHack to recieve the source::DownloadFileReport
254  // and redirect download progress triggers to call the ProvideFilePolicy
255  // callback.
256  DownloadFileReportHack dumb( bind( mem_fun_ref( &ProvideFilePolicy::progress ), ref( policy_r ), _1 ) );
257 
258  RepoException repo_excpt(repo_r,
259  str::form(_("Can't provide file '%s' from repository '%s'"),
260  loc_r.filename().c_str(),
261  repo_r.alias().c_str() ) );
262 
263  if ( repo_r.baseUrlsEmpty() )
264  {
265  repo_excpt.remember(RepoException(_("No url in repository.")));
266  ZYPP_THROW(repo_excpt);
267  }
268 
269  Fetcher fetcher;
270  fetcher.addCachePath( repo_r.packagesPath() );
271  MIL << "Added cache path " << repo_r.packagesPath() << endl;
272 
273  // Test whether download destination is writable, if not
274  // switch into the tmpspace (e.g. bnc#755239, download and
275  // install srpms as user).
276  Pathname destinationDir( repo_r.packagesPath() );
277 
278  PathInfo pi( destinationDir );
279  if ( ! pi.isExist() )
280  {
281  // try to create it...
282  assert_dir( destinationDir );
283  pi();
284  }
285  if ( geteuid() != 0 && ! pi.userMayW() )
286  {
287  WAR << "Destination dir '" << destinationDir << "' is not user writable, using tmp space." << endl;
288  destinationDir = getZYpp()->tmpPath() / destinationDir;
289  assert_dir( destinationDir );
290  fetcher.addCachePath( destinationDir );
291  MIL << "Added cache path " << destinationDir << endl;
292  }
293 
294  for ( RepoInfo::urls_const_iterator it = repo_r.baseUrlsBegin();
295  it != repo_r.baseUrlsEnd();
296  /* incremented in the loop */ )
297  {
298  Url url( *it );
299  ++it;
300  try
301  {
302  MIL << "Providing file of repo '" << repo_r.alias()
303  << "' from " << url << endl;
304  shared_ptr<MediaSetAccess> access = _impl->mediaAccessForUrl( url, repo_r );
305 
306  fetcher.enqueue( loc_r );
307 
308  // FIXME: works for packages only
309  fetcher.start( destinationDir, *access );
310 
311  // reached if no exception has been thrown, so this is the correct file
312  ManagedFile ret( destinationDir + loc_r.filename() );
313 
314  std::string scheme( url.getScheme() );
315  if ( !repo_r.keepPackages() )
316  {
318  }
319 
320  if ( loc_r.checksum().empty() )
321  {
322  // no checksum in metadata
323  WAR << "No checksum in metadata " << loc_r << endl;
324  }
325  else
326  {
327  std::ifstream input( ret->asString().c_str() );
328  CheckSum retChecksum( loc_r.checksum().type(), input );
329  input.close();
330 
331  if ( loc_r.checksum() != retChecksum )
332  {
333  // failed integity check
334  std::ostringstream err;
335  err << "File " << ret << " fails integrity check. Expected: [" << loc_r.checksum() << "] Got: [";
336  if ( retChecksum.empty() )
337  err << "Failed to compute checksum";
338  else
339  err << retChecksum;
340  err << "]";
341 
342  WAR << err.str() << endl;
343 
344  if ( policy_r.failOnChecksumError() )
345  ZYPP_THROW( FileCheckException( err.str() ) );
346  else
347  WAR << "NO failOnChecksumError: " << err.str() << endl;
348  }
349  }
350 
351  MIL << "provideFile at " << ret << endl;
352  return ret;
353  }
354  catch ( const SkipRequestException &e )
355  {
356  ZYPP_CAUGHT( e );
357  ZYPP_RETHROW(e);
358  }
359  catch ( const AbortRequestException &e )
360  {
361  ZYPP_CAUGHT( e );
362  ZYPP_RETHROW(e);
363  }
364  catch ( const Exception &e )
365  {
366  ZYPP_CAUGHT( e );
367 
368  repo_excpt.remember(e);
369 
370  WAR << "Trying next url" << endl;
371  continue;
372  }
373  } // iteration over urls
374 
375  ZYPP_THROW(repo_excpt);
376  return ManagedFile(); // not reached
377  }
378 
380  } // namespace repo
383 } // namespace zypp
std::string name() const
Repository short label.
int assert_dir(const Pathname &path, unsigned mode)
Like &#39;mkdir -p&#39;.
Definition: PathInfo.cc:324
Interface to gettext.
#define MIL
Definition: Logger.h:47
std::string alias() const
unique identifier for this source.
Implementation of the traditional SUSE media verifier.
bool empty() const
Definition: CheckSum.cc:137
ManagedFile provideFile(RepoInfo repo_r, const OnMediaLocation &loc_r, const ProvideFilePolicy &policy_r)
Provide a file from a Repository.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:320
Describes a path on a certain media amongs as the information required to download it...
RedirectType _redirect
urls_const_iterator baseUrlsBegin() const
iterator that points at begin of repository urls
Definition: RepoInfo.cc:252
std::map< Url, shared_ptr< MediaSetAccess > > _medias
Pathname metadataPath() const
Path where this repo metadata was read from.
Definition: RepoInfo.cc:216
What is known about a repository.
Definition: RepoInfo.h:66
void addCachePath(const Pathname &cache_dir)
adds a directory to the list of directories where to look for cached files
Definition: Fetcher.cc:902
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
DBusError error
Definition: HalContext.cc:86
urls_const_iterator baseUrlsEnd() const
iterator that points at end of repository urls
Definition: RepoInfo.cc:259
Pathname packagesPath() const
Path where this repo packages are cached.
Definition: RepoInfo.cc:219
void remember(const Exception &old_r)
Store an other Exception as history.
Definition: Exception.cc:89
Policy for provideFile.
transform_iterator< repo::RepoVariablesUrlReplacer, url_set::const_iterator > urls_const_iterator
Definition: RepoInfo.h:96
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:328
std::string getline(std::istream &str)
Read one line from stream.
Definition: IOStream.cc:33
bool keepPackages() const
Whether packages downloaded from this repository will be kept in local cache.
Definition: RepoInfo.cc:213
ManagedFile provideFile(RepoInfo repo_r, const OnMediaLocation &loc_r, const ProvideFilePolicy &policy_r)
Provide a file from a Repository.
std::map< shared_ptr< MediaSetAccess >, RepoInfo > _verifier
int unlink(const Pathname &path)
Like &#39;unlink&#39;.
Definition: PathInfo.cc:660
#define WAR
Definition: Logger.h:48
thrown when it was impossible to use the raw metadata for this repo.
zypp::Url url
Definition: MediaCurl.cc:193
Impl(const ProvideFilePolicy &defaultPolicy_r)
bool progress(int value) const
Evaluate callback.
#define _(MSG)
Return translated text.
Definition: Gettext.h:21
Receiver * _oldRec
void start(const Pathname &dest_dir, MediaSetAccess &media, const ProgressData::ReceiverFnc &progress=ProgressData::ReceiverFnc())
start the transfer to a destination directory dest_dir You have to provde a media set access media to...
Definition: Fetcher.cc:912
RepoMediaAccess(const ProvideFilePolicy &defaultPolicy_r=ProvideFilePolicy())
Ctor taking the default ProvideFilePolicy.
Provides files from different repos.
void setDispose(const Dispose &dispose_r)
Set a new dispose function.
Definition: AutoDispose.h:158
std::string type() const
Definition: CheckSum.cc:131
RW_pointer< Impl > _impl
bool baseUrlsEmpty() const
whether repository urls are available
Definition: RepoInfo.cc:269
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:324
std::string form(const char *format,...)
Printf style construction of std::string.
Definition: String.cc:34
Base class for Exception.
Definition: Exception.h:143
Exception for repository handling.
Definition: RepoException.h:37
const Pathname & filename() const
The path to the resource relatve to the url and path.
MediaVerifierRef verifier
Wrapper for const correct access via Smart pointer types.
Definition: PtrTypes.h:265
Reference counted access to a _Tp object calling a custom Dispose function when the last AutoDispose ...
Definition: AutoDispose.h:92
void setVerifierForRepo(RepoInfo repo, shared_ptr< MediaSetAccess > media)
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:527
void enqueue(const OnMediaLocation &resource, const FileChecker &checker=FileChecker())
Enqueue a object for transferal, they will not be transfered until start() is called.
Definition: Fetcher.cc:897
bool failOnChecksumError() const
Evaluate callback.
const ProvideFilePolicy & defaultPolicy() const
Get the current default ProvideFilePolicy.
void setDefaultPolicy(const ProvideFilePolicy &policy_r)
Set a new default ProvideFilePolicy.
This class allows to retrieve a group of files in a confortable way, providing some smartness that do...
Definition: Fetcher.h:105
Url manipulation class.
Definition: Url.h:87
Media access layer responsible for handling files distributed on a set of media with media change and...
const CheckSum & checksum() const
the checksum of the resource
shared_ptr< MediaSetAccess > mediaAccessForUrl(const Url &url, RepoInfo repo)
Provide a MediaSetAccess for url with label and verifyer adjusted.