libzypp  17.25.10
MediaSetAccess.cc
Go to the documentation of this file.
1 /*---------------------------------------------------------------------\
2 | ____ _ __ __ ___ |
3 | |__ / \ / / . \ . \ |
4 | / / \ V /| _/ _/ |
5 | / /__ | | | | | | |
6 | /_____||_| |_| |_| |
7 | |
8 \---------------------------------------------------------------------*/
9 
10 #include <iostream>
11 #include <fstream>
12 
13 #include <zypp/base/LogTools.h>
14 #include <zypp/base/Regex.h>
16 #include <zypp/ZYppCallbacks.h>
17 #include <zypp/MediaSetAccess.h>
18 #include <zypp/PathInfo.h>
19 #include <zypp/TmpPath.h>
20 //#include <zypp/source/MediaSetAccessReportReceivers.h>
21 
22 using std::endl;
23 
25 namespace zypp
26 {
27 
29 
31 
33  const Pathname & prefered_attach_point)
34  : _url(url)
35  , _prefAttachPoint(prefered_attach_point)
36  {}
37 
38  MediaSetAccess::MediaSetAccess(const std::string & label_r,
39  const Url &url,
40  const Pathname & prefered_attach_point)
41  : _url(url)
42  , _prefAttachPoint(prefered_attach_point)
43  , _label( label_r )
44  {}
45 
47  {
48  try
49  {
50  media::MediaManager manager;
51  for ( const auto & mm : _medias )
52  manager.close( mm.second );
53  }
54  catch(...) {} // don't let exception escape a dtor.
55  }
56 
57 
59  {
60  if (_medias.find(media_nr) != _medias.end())
61  {
62  // the media already exists, set theverifier
63  media::MediaAccessId id = _medias[media_nr];
64  media::MediaManager media_mgr;
65  media_mgr.addVerifier( id, verifier );
66  // remove any saved verifier for this media
67  _verifiers.erase(media_nr);
68  }
69  else
70  {
71  // save the verifier in the map, and set it when
72  // the media number is first attached
73  _verifiers[media_nr] = verifier;
74  }
75  }
76 
77  void MediaSetAccess::releaseFile( const OnMediaLocation & on_media_file )
78  {
79  releaseFile( on_media_file.filename(), on_media_file.medianr() );
80  }
81 
82  void MediaSetAccess::releaseFile( const Pathname & file, unsigned media_nr)
83  {
84  media::MediaManager media_mgr;
86 
87  media = getMediaAccessId( media_nr);
88  DBG << "Going to release file " << file
89  << " from media number " << media_nr << endl;
90 
91  if ( ! media_mgr.isAttached(media) )
92  return; //disattached media is free
93 
94  media_mgr.releaseFile (media, file);
95  }
96 
98  bool dots, unsigned media_nr )
99  {
100  media::MediaManager media_mgr;
101  media::MediaAccessId media;
102  media = getMediaAccessId(media_nr);
103 
104  // try to attach the media
105  if ( ! media_mgr.isAttached(media) )
106  media_mgr.attach(media);
107 
108  media_mgr.dirInfo(media, retlist, dirname, dots);
109  }
110 
112  {
115  void operator()( media::MediaAccessId media, const Pathname &file )
116  {
117  media::MediaManager media_mgr;
118  media_mgr.provideFile(media, file, expectedFileSize);
119  result = media_mgr.localPath(media, file);
120  }
121  };
122 
124  {
126  void operator()( media::MediaAccessId media, const Pathname &file )
127  {
128  media::MediaManager media_mgr;
129  media_mgr.provideDirTree(media, file);
130  result = media_mgr.localPath(media, file);
131  }
132  };
133 
135  {
137  void operator()( media::MediaAccessId media, const Pathname &file )
138  {
139  media::MediaManager media_mgr;
140  media_mgr.provideDir(media, file);
141  result = media_mgr.localPath(media, file);
142  }
143  };
144 
146  {
147  bool result;
149  : result(false)
150  {}
151 
152  void operator()( media::MediaAccessId media, const Pathname &file )
153  {
154  media::MediaManager media_mgr;
155  result = media_mgr.doesFileExist(media, file);
156  }
157  };
158 
159 
160 
161  Pathname MediaSetAccess::provideFile( const OnMediaLocation & resource, ProvideFileOptions options, const Pathname &deltafile )
162  {
164  op.expectedFileSize = resource.downloadSize();
165  provide( boost::ref(op), resource, options, deltafile );
166  return op.result;
167  }
168 
169  Pathname MediaSetAccess::provideFile(const Pathname & file, unsigned media_nr, ProvideFileOptions options )
170  {
171  OnMediaLocation resource;
173  resource.setLocation(file, media_nr);
174  provide( boost::ref(op), resource, options, Pathname() );
175  return op.result;
176  }
177 
178  Pathname MediaSetAccess::provideOptionalFile( const Pathname & file, unsigned media_nr )
179  {
180  try
181  {
182  if ( doesFileExist( file, media_nr ) )
183  return provideFile( file, media_nr, PROVIDE_NON_INTERACTIVE );
184  }
185  catch ( const media::MediaFileNotFoundException & excpt_r )
186  { ZYPP_CAUGHT( excpt_r ); }
187  catch ( const media::MediaForbiddenException & excpt_r )
188  { ZYPP_CAUGHT( excpt_r ); }
189  catch ( const media::MediaNotAFileException & excpt_r )
190  { ZYPP_CAUGHT( excpt_r ); }
191  return Pathname();
192  }
193 
194  ManagedFile MediaSetAccess::provideFileFromUrl(const Url &file_url, ProvideFileOptions options)
195  {
196  Url url(file_url);
197  Pathname path(url.getPathName());
198  url.setPathName ("/");
199  MediaSetAccess access(url);
200 
202 
203  Pathname file = access.provideFile(path, 1, options);
204 
205  //prevent the file from being deleted when MediaSetAccess gets out of scope
206  if ( filesystem::hardlinkCopy(file, tmpFile) != 0 )
207  ZYPP_THROW(Exception("Can't copy file from " + file.asString() + " to " + tmpFile->asString() ));
208 
209  return tmpFile;
210  }
211 
213  {
214  try
215  {
216  return provideFileFromUrl( file_url, PROVIDE_NON_INTERACTIVE );
217  }
218  catch ( const media::MediaFileNotFoundException & excpt_r )
219  { ZYPP_CAUGHT( excpt_r ); }
220  catch ( const media::MediaNotAFileException & excpt_r )
221  { ZYPP_CAUGHT( excpt_r ); }
222  return ManagedFile();
223  }
224 
225  bool MediaSetAccess::doesFileExist(const Pathname & file, unsigned media_nr )
226  {
228  OnMediaLocation resource;
229  resource.setLocation(file, media_nr);
230  provide( boost::ref(op), resource, PROVIDE_DEFAULT, Pathname());
231  return op.result;
232  }
233 
235  const OnMediaLocation &resource,
236  ProvideFileOptions options,
237  const Pathname &deltafile )
238  {
239  Pathname file(resource.filename());
240  unsigned media_nr(resource.medianr());
241 
243  media::MediaManager media_mgr;
244 
245  media::MediaAccessId media;
246 
247  do
248  {
249  // get the mediaId, but don't try to attach it here
250  media = getMediaAccessId( media_nr);
251  bool deltafileset = false;
252 
253  try
254  {
255  DBG << "Going to try to provide " << (resource.optional() ? "optional" : "") << " file " << file
256  << " from media number " << media_nr << endl;
257  // try to attach the media
258  if ( ! media_mgr.isAttached(media) )
259  media_mgr.attach(media);
260  media_mgr.setDeltafile(media, deltafile);
261  deltafileset = true;
262  op(media, file);
263  media_mgr.setDeltafile(media, Pathname());
264  break;
265  }
266  catch ( media::MediaException & excp )
267  {
268  ZYPP_CAUGHT(excp);
269  if (deltafileset)
270  media_mgr.setDeltafile(media, Pathname());
272  unsigned int devindex = 0;
273  std::vector<std::string> devices;
274  media_mgr.getDetectedDevices(media, devices, devindex);
275 
276  do
277  {
278  if (user != media::MediaChangeReport::EJECT) // no use in calling this again
279  {
280  DBG << "Media couldn't provide file " << file << " , releasing." << endl;
281  try
282  {
283  media_mgr.release(media);
284  }
285  catch (const Exception & excpt_r)
286  {
287  ZYPP_CAUGHT(excpt_r);
288  MIL << "Failed to release media " << media << endl;
289  }
290  }
291 
292  // set up the reason
294 
295  if( typeid(excp) == typeid( media::MediaFileNotFoundException ) ||
296  typeid(excp) == typeid( media::MediaNotAFileException ) )
297  {
299  }
300  else if( typeid(excp) == typeid( media::MediaNotDesiredException) ||
301  typeid(excp) == typeid( media::MediaNotAttachedException) )
302  {
304  }
305  else if( typeid(excp) == typeid( media::MediaTimeoutException) ||
306  typeid(excp) == typeid( media::MediaTemporaryProblemException))
307  {
309  }
310 
311  // Propagate the original error if _no_ callback receiver is connected, or
312  // non_interactive mode (for optional files) is used (except for wrong media).
314  || (( options & PROVIDE_NON_INTERACTIVE ) && reason != media::MediaChangeReport::WRONG ) )
315  {
316  MIL << "Can't provide file. Non-Interactive mode." << endl;
317  ZYPP_RETHROW(excp);
318  }
319  else
320  {
321  // release all media before requesting another (#336881)
322  media_mgr.releaseAll();
323 
324  user = report->requestMedia (
325  _url,
326  media_nr,
327  _label,
328  reason,
329  excp.asUserHistory(),
330  devices,
331  devindex
332  );
333  }
334 
335  MIL << "ProvideFile exception caught, callback answer: " << user << endl;
336 
337  if( user == media::MediaChangeReport::ABORT )
338  {
339  DBG << "Aborting" << endl;
340  AbortRequestException aexcp("Aborting requested by user");
341  aexcp.remember(excp);
342  ZYPP_THROW(aexcp);
343  }
344  else if ( user == media::MediaChangeReport::IGNORE )
345  {
346  DBG << "Skipping" << endl;
347  SkipRequestException nexcp("User-requested skipping of a file");
348  nexcp.remember(excp);
349  ZYPP_THROW(nexcp);
350  }
351  else if ( user == media::MediaChangeReport::EJECT )
352  {
353  DBG << "Eject: try to release" << endl;
354  try
355  {
356  media_mgr.releaseAll();
357  media_mgr.release (media, devindex < devices.size() ? devices[devindex] : "");
358  }
359  catch ( const Exception & e)
360  {
361  ZYPP_CAUGHT(e);
362  }
363  }
364  else if ( user == media::MediaChangeReport::RETRY ||
366  {
367  // retry
368  DBG << "Going to try again" << endl;
369  // invalidate current media access id
370  media_mgr.close(media);
371  _medias.erase(media_nr);
372 
373  // not attaching, media set will do that for us
374  // this could generate uncaught exception (#158620)
375  break;
376  }
377  else
378  {
379  DBG << "Don't know, let's ABORT" << endl;
380  ZYPP_RETHROW ( excp );
381  }
382  } while( user == media::MediaChangeReport::EJECT );
383  }
384 
385  // retry or change URL
386  } while( true );
387  }
388 
390  bool recursive,
391  unsigned media_nr,
392  ProvideFileOptions options )
393  {
394  OnMediaLocation resource;
395  resource.setLocation(dir, media_nr);
396  if ( recursive )
397  {
399  provide( boost::ref(op), resource, options, Pathname());
400  return op.result;
401  }
403  provide( boost::ref(op), resource, options, Pathname());
404  return op.result;
405  }
406 
408  {
409  if ( _medias.find( medianr ) != _medias.end() )
410  {
411  return _medias[medianr];
412  }
413 
414  Url url( medianr > 1 ? rewriteUrl( _url, medianr ) : _url );
415  media::MediaManager media_mgr;
416  media::MediaAccessId id = media_mgr.open( url, _prefAttachPoint );
417  _medias[medianr] = id;
418 
419  try
420  {
421  if ( _verifiers.find(medianr) != _verifiers.end() )
422  {
423  // a verifier is set for this media
424  // FIXME check the case where the verifier exists
425  // but we have no access id for the media
426  media_mgr.delVerifier( id );
427  media_mgr.addVerifier( id, _verifiers[medianr] );
428  // remove any saved verifier for this media
429  _verifiers.erase( medianr );
430  }
431  }
432  catch ( const Exception &e )
433  {
434  ZYPP_CAUGHT(e);
435  WAR << "Verifier not found" << endl;
436  }
437 
438  return id;
439  }
440 
441 
442  Url MediaSetAccess::rewriteUrl (const Url & url_r, const media::MediaNr medianr)
443  {
444  std::string scheme = url_r.getScheme();
445  if (scheme == "cd" || scheme == "dvd")
446  return url_r;
447 
448  DBG << "Rewriting url " << url_r << endl;
449 
450  if( scheme == "iso")
451  {
452  // TODO the iso parameter will not be required in the future, this
453  // code has to be adapted together with the MediaISO change.
454  // maybe some MediaISOURL interface should be used.
455  std::string isofile = url_r.getQueryParam("iso");
456  str::regex e("^(.*)(cd|dvd|media)[0-9]+\\.iso$", str::regex::icase);
457 
458  str::smatch what;
459  if(str::regex_match(isofile, what, e))
460  {
461  Url url( url_r);
462  isofile = what[1] + what[2] + str::numstring(medianr) + ".iso";
463  url.setQueryParam("iso", isofile);
464  DBG << "Url rewrite result: " << url << endl;
465  return url;
466  }
467  }
468  else
469  {
470  std::string pathname = url_r.getPathName();
471  str::regex e("^(.*)(cd|dvd|media)[0-9]+(/)?$", str::regex::icase);
472  str::smatch what;
473  if(str::regex_match(pathname, what, e))
474  {
475  Url url( url_r);
476  pathname = what[1] + what[2] + str::numstring(medianr) + what[3];
477  url.setPathName(pathname);
478  DBG << "Url rewrite result: " << url << endl;
479  return url;
480  }
481  }
482  return url_r;
483  }
484 
486  {
487  DBG << "Releasing all media IDs held by this MediaSetAccess" << endl;
488  media::MediaManager manager;
489  for (MediaMap::const_iterator m = _medias.begin(); m != _medias.end(); ++m)
490  manager.release(m->second, "");
491  }
492 
493  std::ostream & MediaSetAccess::dumpOn( std::ostream & str ) const
494  {
495  str << "MediaSetAccess (URL='" << _url << "', attach_point_hint='" << _prefAttachPoint << "')";
496  return str;
497  }
498 
500 } // namespace zypp
static ManagedFile provideOptionalFileFromUrl(const Url &file_url)
Provides an optional file from url.
std::string getScheme() const
Returns the scheme name of the URL.
Definition: Url.cc:528
#define MIL
Definition: Logger.h:91
void provide(ProvideOperation op, const OnMediaLocation &resource, ProvideFileOptions options, const Pathname &deltafile)
void provideDirTree(MediaAccessId accessId, const Pathname &dirname) const
FIXME: see MediaAccess class.
void setDeltafile(MediaAccessId accessId, const Pathname &filename) const
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
Definition: Exception.h:392
Describes a resource file located on a medium.
Regular expression.
Definition: Regex.h:94
static ManagedFile provideFileFromUrl(const Url &file_url, ProvideFileOptions options=PROVIDE_DEFAULT)
Provides file from url.
bool doesFileExist(MediaAccessId accessId, const Pathname &filename) const
FIXME: see MediaAccess class.
MediaMap _medias
Mapping between media number and Media Access ID.
Url _url
Media or media set URL.
Pathname provideOptionalFile(const Pathname &file, unsigned media_nr=1)
Provides an optional file from media media_nr.
Store and operate with byte count.
Definition: ByteCount.h:30
Pathname provideDir(const Pathname &dir, bool recursive, unsigned media_nr=1, ProvideFileOptions options=PROVIDE_DEFAULT)
Provides direcotry dir from media number media_nr.
void dirInfo(MediaAccessId accessId, std::list< std::string > &retlist, const Pathname &dirname, bool dots=true) const
FIXME: see MediaAccess class.
virtual std::ostream & dumpOn(std::ostream &str) const
Overload to realize std::ostream & operator<<.
IO error which can happen on worse connection like timeout exceed.
String related utilities and Regular expression matching.
bool doesFileExist(const Pathname &file, unsigned media_nr=1)
Checks if a file exists on the specified media, with user callbacks.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
Definition: ManagedFile.h:27
Url url
Definition: MediaCurl.cc:66
Pathname _prefAttachPoint
Prefered mount point.
void release()
Release all attached media of this set.
static Url rewriteUrl(const Url &url_r, const media::MediaNr medianr)
Replaces media number in specified url with given medianr.
void provideFile(MediaAccessId accessId, const Pathname &filename, const ByteCount &expectedFileSize) const
Provide provide file denoted by relative path below of the &#39;attach point&#39; of the specified media and ...
unsigned int MediaAccessId
Media manager access Id type.
Definition: MediaSource.h:29
void operator()(media::MediaAccessId media, const Pathname &file)
Pathname localPath(MediaAccessId accessId, const Pathname &pathname) const
Shortcut for &#39;localRoot() + pathname&#39;, but returns an empty pathname if media is not attached...
void releaseFile(const OnMediaLocation &resource)
Release file from media.
unsigned medianr() const
The media number the resource is located on.
void release(MediaAccessId accessId, const std::string &ejectDev="")
Release the attached media and optionally eject.
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
Definition: Exception.h:400
Do not differentiate case.
Definition: Regex.h:99
std::string getQueryParam(const std::string &param, EEncoding eflag=zypp::url::E_DECODED) const
Return the value for the specified query parameter.
Definition: Url.cc:655
const std::string & asString() const
String representation.
Definition: Pathname.h:91
Just inherits Exception to separate media exceptions.
void dirInfo(filesystem::DirContent &retlist, const Pathname &dirname, bool dots=true, unsigned media_nr=1)
Fills retlist with directory information.
std::string asUserHistory() const
A single (multiline) string composed of asUserString and historyAsString.
Definition: Exception.cc:91
const ByteCount & downloadSize() const
The size of the resource on the server.
#define WAR
Definition: Logger.h:92
IMPL_PTR_TYPE(Application)
std::list< DirEntry > DirContent
Returned by readdir.
Definition: PathInfo.h:547
int hardlinkCopy(const Pathname &oldpath, const Pathname &newpath)
Create newpath as hardlink or copy of oldpath.
Definition: PathInfo.cc:845
void addVerifier(MediaAccessId accessId, const MediaVerifierRef &verifier)
Add verifier implementation for the specified media id.
void operator()(media::MediaAccessId media, const Pathname &file)
OnMediaLocation & setLocation(Pathname filename_r, unsigned medianr_r=1)
Set filename_r and medianr_r (defaults to 1).
const Pathname & filename() const
The path to the resource on the medium.
std::string numstring(char n, int w=0)
Definition: String.h:286
void provideDir(MediaAccessId accessId, const Pathname &dirname) const
FIXME: see MediaAccess class.
void attach(MediaAccessId accessId)
Attach the media using the concrete handler (checks all devices).
function< void(media::MediaAccessId, const Pathname &)> ProvideOperation
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
Definition: Exception.h:396
Regular expression match result.
Definition: Regex.h:162
Manages access to the &#39;physical&#39; media, e.g CDROM drives, Disk volumes, directory trees...
Definition: MediaManager.h:461
Base class for Exception.
Definition: Exception.h:145
void operator()(media::MediaAccessId media, const Pathname &file)
void setVerifier(unsigned media_nr, media::MediaVerifierRef verifier)
Sets a MediaVerifier verifier for given media number.
callback::SendReport< DownloadProgressReport > * report
Definition: MediaCurl.cc:70
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
Definition: Url.cc:599
MediaVerifierRef verifier
Wrapper for const correct access via Smart pointer types.
Definition: PtrTypes.h:285
media::MediaAccessId getMediaAccessId(media::MediaNr medianr)
Reference counted access to a Tp object calling a custom Dispose function when the last AutoDispose h...
Definition: AutoDispose.h:92
bool regex_match(const std::string &s, smatch &matches, const regex &regex)
regex ZYPP_STR_REGEX regex ZYPP_STR_REGEX
Definition: Regex.h:70
bool isAttached(MediaAccessId accessId) const
Check if media is attached or not.
void operator()(media::MediaAccessId media, const Pathname &file)
void releaseAll()
Release all attached media.
void getDetectedDevices(MediaAccessId accessId, std::vector< std::string > &devices, unsigned int &index) const
Fill in a vector of detected ejectable devices and the index of the currently attached device within ...
Easy-to use interface to the ZYPP dependency resolver.
Definition: CodePitfalls.doc:1
Pathname provideFile(const OnMediaLocation &resource, ProvideFileOptions options=PROVIDE_DEFAULT, const Pathname &deltafile=Pathname())
Provides a file from a media location.
MediaSetAccess(const Url &url, const Pathname &prefered_attach_point="")
Creates a callback enabled media access for specified url.
MediaAccessId open(const Url &url, const Pathname &preferred_attach_point="")
Opens the media access for specified with the url.
bool optional() const
Whether this is an optional resource.
VerifierMap _verifiers
Mapping between media number and corespondent verifier.
Url manipulation class.
Definition: Url.h:91
void delVerifier(MediaAccessId accessId)
Remove verifier for specified media id.
void releaseFile(MediaAccessId accessId, const Pathname &filename) const
FIXME: see MediaAccess class.
unsigned int MediaNr
Definition: MediaManager.h:40
void close(MediaAccessId accessId)
Close the media access with specified id.
#define DBG
Definition: Logger.h:90
static ManagedFile asManagedFile()
Create a temporary file and convert it to a automatically cleaned up ManagedFile. ...
Definition: TmpPath.cc:230
The user is not asked anything, and the error exception is just propagated.