23 #include <zypp-core/zyppng/base/EventDispatcher> 24 #include <zypp-core/zyppng/base/EventLoop> 27 #include <zypp-curl/ng/network/Downloader> 28 #include <zypp-curl/ng/network/NetworkRequestDispatcher> 29 #include <zypp-curl/ng/network/DownloadSpec> 31 #include <zypp-media/MediaConfig> 33 #include <zypp-media/auth/CredentialManager> 44 constexpr std::string_view
MEDIACACHE_REGEX(
"^\\/media\\.[1-9][0-9]*\\/media$");
48 using clock = std::chrono::steady_clock;
64 clock::time_point now = clock::now();
73 if ( dlnow && dlnow !=
_dnlNow ) {
107 MIL <<
"Releasing internal::SharedData for MediaNetwork." << std::endl;
111 static std::shared_ptr<SharedData> data = std::shared_ptr<SharedData>(
new SharedData() );
128 std::chrono::steady_clock::time_point
_creationTime = std::chrono::steady_clock::now();
135 auto age = std::chrono::steady_clock::now() - i->second._creationTime;
136 if ( age > std::chrono::minutes( 30 ) ) {
137 MIL <<
"Found cached media file, but it's older than 30 mins, requesting a new one" << std::endl;
151 MIL <<
"Initializing internal::SharedData for MediaNetwork" << std::endl;
153 _downloader = std::make_shared<zyppng::Downloader>();
167 MediaNetwork::MediaNetwork(
const Url & url_r,
168 const Pathname & attach_point_hint_r )
173 MIL <<
"MediaNetwork::MediaNetwork(" << url_r <<
", " << attach_point_hint_r <<
")" << endl;
182 char *atemp = ::strdup( apath.
asString().c_str());
185 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
187 WAR <<
"attach point " << ainfo.
path()
188 <<
" is not useable for " << url_r.
getScheme() << endl;
191 else if( atest != NULL)
208 if ( !
_shared->_downloader->requestDispatcher()->supportsProtocol(
_url ) ) {
209 std::string msg(
"Unsupported protocol '");
248 std::vector<zyppng::connection> signalConnections;
250 while( signalConnections.size() ) {
251 signalConnections.back().disconnect();
252 signalConnections.pop_back();
256 zyppng::DownloadRef dl =
_shared->_downloader->downloadFile( spec );
257 std::optional<internal::ProgressTracker> progTracker;
260 if ( !report)
return;
265 if ( !report || !progTracker )
267 progTracker->updateStats( 0.0, dlNow );
268 if ( !(*report)->progress( progTracker->_dnlPercent, spec.
url(), progTracker-> _drateTotal, progTracker->_drateLast ) )
272 const auto &progressSlot = [&](
zyppng::Download &req, off_t dlTotal, off_t dlNow ) {
273 if ( !report || !progTracker )
276 progTracker->updateStats( dlTotal, dlNow );
277 if ( !(*report)->progress( progTracker->_dnlPercent, spec.
url(), progTracker-> _drateTotal, progTracker->_drateLast ) )
285 bool firstTry =
true;
294 if ( cmcred && auth.lastDatabaseUpdate() < cmcred->lastDatabaseUpdate() ) {
296 DBG <<
"got stored credentials:" << endl << *credentials << endl;
309 curlcred->setUsername(cmcred->username());
318 curlcred->setAuthType( availAuth );
321 if (auth_report->prompt(
_url, prompt_msg, *curlcred))
323 DBG <<
"callback answer: retry" << endl
324 <<
"CurlAuthData: " << *curlcred << endl;
326 if (curlcred->valid())
328 credentials = curlcred;
342 DBG <<
"callback answer: cancel" << endl;
346 if ( !credentials ) {
353 credentials->setUrl(
_url);
359 signalConnections.insert( signalConnections.end(), {
367 signalConnections.insert( signalConnections.end(), {
376 std::for_each( signalConnections.begin(), signalConnections.end(), [](
auto &conn ) { conn.disconnect(); });
378 if ( dl->hasError() ) {
380 std::exception_ptr excp;
381 const auto &error = dl->lastRequestError();
382 switch ( error.type() ) {
430 DBG <<
"BUG: Download error flag is set , but Error code is NoError" << std::endl;
439 if ( excp && !retry ) {
440 if ( report ) (*report)->finish( spec.
url(), errCode, error.toString() );
441 std::rethrow_exception( excp );
457 const auto &filename = file.
filename();
460 const bool requestedMediaFile =
_shared->mediaRegex().matches( filename.asString() );
461 auto &mediaFileCache =
_shared->_mediaCacheEntries;
464 DBG <<
"FILEURL IS: " << fileurl << std::endl;
465 DBG <<
"Downloading to: " << targetFilename << std::endl;
468 DBG <<
"assert_dir " << targetFilename.
dirname() <<
" failed" << endl;
472 if ( requestedMediaFile ) {
473 MIL <<
"Requested " << filename <<
" trying media cache first" << std::endl;
475 auto i =
_shared->findInCache( mediaCacheKey );
476 if ( i != mediaFileCache.end() ) {
477 MIL <<
"Found cached media file, returning a copy to the file" << std::endl;
481 mediaFileCache.erase(i);
482 MIL <<
"Failed to copy the requested file, proceeding with download" << std::endl;
485 MIL <<
"Nothing in the file cache, requesting the file from the server." << std::endl;
499 if ( requestedMediaFile ) {
500 MIL <<
"Media file was not found, remembering in the cache" << std::endl;
507 if ( requestedMediaFile ) {
512 MIL <<
"Saved requested media file in media cache for future use" << std::endl;
514 MIL <<
"Failed to save requested media file in cache, requesting again next time." << std::endl;
521 MIL <<
"Checking if file " << filename <<
" does exist" << std::endl;
523 const bool requestMediaFile =
_shared->mediaRegex().matches( filename.
asString() );
524 auto &mediaFileCache =
_shared->_mediaCacheEntries;
527 if ( requestMediaFile ) {
528 MIL <<
"Request for " << filename <<
" is a media file, trying the cache first" << std::endl;
529 auto i =
_shared->findInCache( mediaCacheKey );
530 if ( i != mediaFileCache.end() ) {
531 MIL <<
"Found a cache entry for requested media file, returning right away" << std::endl;
532 if ( i->second._file->empty() ) {
565 if ( !result && requestMediaFile ) {
566 MIL << filename <<
" does not exist on medium, remembering in the cache" << std::endl;
578 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
579 Pathname filename = dirname + it->name;
582 switch ( it->type ) {
589 getDir( filename, recurse_r );
593 WAR <<
"Ignore error (" << res <<
") on creating local directory '" <<
localPath( filename ) <<
"'" << endl;
605 const Pathname & dirname,
bool dots )
const 611 const Pathname & dirname,
bool dots )
const std::string getScheme() const
Returns the scheme name of the URL.
static const zypp::str::regex & mediaRegex()
SignalProxy< void(Download &req, off_t dlnow)> sigAlive()
int assert_dir(const Pathname &path, unsigned mode)
Like 'mkdir -p'.
const Pathname & path() const
Return current Pathname.
#define ZYPP_THROW(EXCPT)
Drops a logline and throws the Exception.
static ZConfig & instance()
Singleton ctor.
int _dnlPercent
Percent completed or 0 if _dnlTotal is unknown.
std::string asString() const
DownloadSpec & setTransferSettings(TransferSettings &&set)
SignalProxy< void(Download &req, NetworkAuthData &auth, const std::string &availAuth)> sigAuthRequired()
std::optional< clock::time_point > _timeLast
Start last period(~1sec)
static std::shared_ptr< SharedData > instance()
static const Pathname & defaultLocation()
double _drateLast
Download rate in last period.
zypp::filesystem::TmpDir _mediaCacheDir
SignalProxy< void(Download &req)> sigFinished()
#define ZYPP_EXCPT_PTR(EXCPT)
Drops a logline and returns Exception as a std::exception_ptr.
std::list< DirEntry > DirContent
Returned by readdir.
int hardlinkCopy(const Pathname &oldpath, const Pathname &newpath)
Create newpath as hardlink or copy of oldpath.
constexpr std::string_view MEDIACACHE_REGEX("^\media\[1-9][0-9]*\media$")
static CheckSum md5FromString(const std::string &input_r)
#define ZYPP_RETHROW(EXCPT)
Drops a logline and rethrows, updating the CodeLocation.
std::string asString() const
Returns a default string representation of the Url object.
auto findInCache(const std::string &mediaCacheKey)
Provide a new empty temporary directory and recursively delete it when no longer needed.
std::optional< clock::time_point > _timeStart
Start total stats.
const std::string & asString() const
String representation.
Pathname dirname() const
Return all but the last component od this path.
void updateStats(double dltotal=0.0, double dlnow=0.0)
std::string asCompleteString() const
Returns a complete string representation of the Url object.
bool isValid() const
Verifies the Url.
double _dnlLast
Bytes downloaded at period start.
const zypp::Pathname & targetPath() const
int unlink(const Pathname &path)
Like 'unlink'.
zypp::ByteCount expectedFileSize() const
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
zypp::media::CurlAuthData NetworkAuthData
static ZYPP_API ThreadData & current()
std::shared_ptr< EventDispatcher > ensureDispatcher()
SignalProxy< void(Download &req)> sigStarted()
zyppng::DownloaderRef _downloader
Pathname absolutename() const
Return this path, adding a leading '/' if relative.
std::chrono::steady_clock::time_point _creationTime
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
zyppng::EventDispatcherRef _dispatcher
SignalProxy< void(Download &req, off_t dltotal, off_t dlnow)> sigProgress()
Wrapper class for ::stat/::lstat.
double _dnlNow
Bytes downloaded now.
SharedData & operator=(const SharedData &)=delete
double _dnlTotal
Bytes to download or 0 if unknown.
Easy-to use interface to the ZYPP dependency resolver.
std::chrono::steady_clock clock
int rmdir(const Pathname &path)
Like 'rmdir'.
double _drateTotal
Download rate so far.
DownloadSpec & setCheckExistsOnly(bool set=true)
std::unordered_map< std::string, MediaFileCacheEntry > _mediaCacheEntries
MediaFileCacheEntry(zypp::ManagedFile &&file)
std::string getUsername(EEncoding eflag=zypp::url::E_DECODED) const
Returns the username from the URL authority.