16#include <zypp-media/MediaException>
17#include <zypp-core/base/UserRequestException>
19#include <zypp-core/fs/PathInfo.h>
21using namespace std::literals;
40 for (
auto i = cHeaders.beginList (); i != cHeaders.endList(); i++) {
41 for (
const auto &val : i->second )
42 m.addValue( i->first, val );
45 return expected<ProvideRequestRef>::success( ProvideRequestRef(
new ProvideRequest(&
owner,
urls, std::move(m))) );
58 if ( !destFile.empty() )
60 if ( !deltaFile.empty() )
67 for (
auto i = cHeaders.beginList (); i != cHeaders.endList(); i++) {
68 for (
const auto &val : i->second )
69 m.addValue( i->first, val );
72 return expected<ProvideRequestRef>::success( ProvideRequestRef(
new ProvideRequest(&
owner,
urls, std::move(m)) ) );
78 return expected<ProvideRequestRef>::success( ProvideRequestRef(
new ProvideRequest(
nullptr, {
url }, std::move(m) ) ) );
92 return d_func()->_parent;
107 startedReq->_pastRedirects.push_back ( url );
113 if ( !startedReq->_pastRedirects.size() )
116 if ( std::find( startedReq->_pastRedirects.begin(), startedReq->_pastRedirects.end(), url ) != startedReq->_pastRedirects.end() )
124 return d_func()->_currStats;
129 return d_func()->_prevStats;
134 return d_func()->_itemStarted;
138 return d_func()->_itemFinished;
145 d->_prevStats = d->_currStats;
151 d->_currStats->_pulseTime = d->_itemFinished;
162 .
_pulseTime = std::chrono::steady_clock::now(),
163 ._runningRequests =
_runningReq ? (uint)1 : (uint)0
170 WAR <<
"Received event for unknown request, ignoring" << std::endl;
174 if ( msg.
code() == ProvideMessage::Code::ProvideStarted ) {
175 MIL <<
"Request: "<< req->url() <<
" was started" << std::endl;
183 WAR <<
"Received event for unknown request, ignoring" << std::endl;
187 MIL <<
"Request: "<< req->url() <<
" CACHE MISS, request will be restarted by queue." << std::endl;
193 WAR <<
"Received event for unknown request, ignoring" << std::endl;
200 const auto code = msg.
code();
201 if ( code == ProvideMessage::Code::Redirect ) {
208 MIL <<
"Request finished with redirect." << std::endl;
216 MIL <<
"Request redirected to: " << newUrl << std::endl;
218 if ( log ) log->requestRedirect( *
this, msg.
requestId(), newUrl );
220 finishedReq->setUrl( newUrl );
231 }
else if ( code == ProvideMessage::Code::Metalink ) {
236 MIL <<
"Request finished with mirrorlist from server." << std::endl;
241 std::vector<zypp::Url> urls;
243 for(
auto i = mirrors.cbegin(); i != mirrors.cend(); i++ ) {
248 urls.push_back ( newUrl );
251 WAR <<
"Received invalid URL from worker: " << i->asString() <<
" ignoring!" << std::endl;
253 WAR <<
"Received invalid value for newUrl from worker ignoring!" << std::endl;
257 if ( urls.size () == 0 ) {
262 MIL <<
"Found usable nr of mirrors: " << urls.size () << std::endl;
263 finishedReq->setUrls( urls );
268 if ( log ) log->requestDone( *
this, msg.
requestId() );
274 MIL <<
"End of mirrorlist handling"<< std::endl;
277 }
else if ( code >= ProvideMessage::Code::FirstClientErrCode && code <= ProvideMessage::Code::LastSrvErrCode ) {
282 std::exception_ptr errPtr;
284 const auto reqUrl = finishedReq->activeUrl().value();
287 case ProvideMessage::Code::BadRequest:
290 case ProvideMessage::Code::PeerCertificateInvalid:
293 case ProvideMessage::Code::ConnectionFailed:
296 case ProvideMessage::Code::ExpectedSizeExceeded: {
298 std::optional<int64_t> filesize;
299 finishedReq->provideMessage ().forEachVal( [&](
const std::string &key,
const auto &val ){
301 filesize = val.asInt64();
312 case ProvideMessage::Code::Cancelled:
315 case ProvideMessage::Code::InvalidChecksum:
318 case ProvideMessage::Code::Timeout:
321 case ProvideMessage::Code::NotFound:
324 case ProvideMessage::Code::Forbidden:
325 case ProvideMessage::Code::Unauthorized: {
327 const auto &hintVal = msg.
value(
"authHint"sv );
329 if ( hintVal.valid() && hintVal.isString() ) {
337 reqUrl, reason,
"", hint
342 case ProvideMessage::Code::MountFailed:
345 case ProvideMessage::Code::Jammed:
348 case ProvideMessage::Code::MediaChangeSkip:
349 errPtr =
ZYPP_EXCPT_PTR( zypp::SkipRequestException (
zypp::str::Str() <<
"User-requested skipping for URL: " << reqUrl <<
" " << reason ) );
351 case ProvideMessage::Code::MediaChangeAbort:
352 errPtr =
ZYPP_EXCPT_PTR( zypp::AbortRequestException(
zypp::str::Str() <<
"Aborting requested by user for URL: " << reqUrl <<
" " << reason ) );
354 case ProvideMessage::Code::InternalError:
357 case ProvideMessage::Code::NotAFile:
360 case ProvideMessage::Code::MediumNotDesired:
371 if ( log ) log->requestFailed( *
this, msg.
requestId(), errPtr );
385 WAR <<
"Received event for unknown request, ignoring" << std::endl;
391 if ( log ) log->requestFailed( *
this, finishedReq->provideMessage().requestId(), excpt );
402 WAR <<
"Received authenticationRequired for unknown request, rejecting" << std::endl;
409 MIL <<
"Looking for existing auth data for " << effectiveUrl <<
"more recent then " << lastTimestamp << std::endl;
411 auto credPtr = mgr.
getCred( effectiveUrl );
412 if ( credPtr && credPtr->lastDatabaseUpdate() > lastTimestamp ) {
413 MIL <<
"Found existing auth data for " << effectiveUrl <<
"ts: " << credPtr->lastDatabaseUpdate() << std::endl;
414 return expected<zypp::media::AuthData>::success( *credPtr );
417 if ( credPtr )
MIL <<
"Found existing auth data for " << effectiveUrl <<
"but too old ts: " << credPtr->lastDatabaseUpdate() << std::endl;
419 std::string username;
421 username = i->second;
425 MIL <<
"NO Auth data found, asking user. Last tried username was: " << username << std::endl;
428 if ( !userAuth || !userAuth->valid() ) {
429 MIL <<
"User rejected to give auth" << std::endl;
440 return expected<zypp::media::AuthData>::success(*userAuth);
443 return expected<zypp::media::AuthData>::error( std::current_exception() );
454 return d_func()->_parent.queueRequest( request );
460 if ( d->_itemState != newState ) {
465 const auto oldState = d->_itemState;
466 d->_itemState = newState;
467 d->_sigStateChanged( *
this, oldState, d->_itemState );
470 d->_itemStarted = std::chrono::steady_clock::now();
472 if ( log ) log->itemStart( *
this );
476 d->_itemFinished = std::chrono::steady_clock::now();
478 if ( log) log->itemDone( *
this );
479 d->_parent.dequeueItem(
this);
490 MIL <<
"Item Cleanup due to released Promise in state:" <<
state() << std::endl;
496 return d_func()->_itemState;
513 case ProvideMessage::Code::Attach:
516 case ProvideMessage::Code::Detach:
519 case ProvideMessage::Code::Provide:
524 throw std::logic_error(
"Invalid message type in ProvideRequest");
526 if ( !
url.valid() ) {
543 case ProvideMessage::Code::Attach:
546 case ProvideMessage::Code::Detach:
549 case ProvideMessage::Code::Provide:
554 throw std::logic_error(
"Invalid message type in ProvideRequest");
560 , _mirrorList ( urls )
561 , _initialSpec ( request )
566 return ProvideFileItemRef(
new ProvideFileItem( urls, request, parent ) );
572 WAR <<
"Double init of ProvideFileItem!" << std::endl;
595 auto promiseRef = std::make_shared<ProvidePromise<ProvideRes>>( shared_this<ProvideItem>() );
615 WAR <<
"Received event for unknown request, ignoring" << std::endl;
619 if ( msg.
code() == ProvideMessage::Code::ProvideStarted ) {
620 MIL <<
"Provide File Request: "<< req->url() <<
" was started" << std::endl;
624 if ( !locPath.empty() )
628 if ( !locPath.empty() )
632 auto effUrl = req->activeUrl().value_or(
zypp::Url() );
641 if ( log ) log->requestStart( *
this, msg.
requestId(), effUrl, m );
649 if ( finishedReq != _runningReq ) {
650 WAR <<
"Received event for unknown request, ignoring" << std::endl;
654 if ( msg.
code () == ProvideMessage::Code::ProvideFinished ) {
656 auto log = provider().log();
659 m[
"spec"] = _initialSpec;
660 if ( log ) log->requestDone( *
this, msg.
requestId(), m );
663 MIL <<
"Request was successfully finished!" << std::endl;
673 const bool doesDownload = wConf.worker_type() == ProvideQueue::Config::Downloading;
674 const bool fileNeedsCleanup = doesDownload || ( wConf.worker_type() == ProvideQueue::Config::CPUBound && wConf.cfg_flags() & ProvideQueue::Config::FileArtifacts );
676 std::optional<zypp::ManagedFile> resFile;
678 if ( doesDownload ) {
680 resFile = provider().addToFileCache ( locFilename );
683 MIL <<
"CACHE MISS, file " << locFilename <<
" was already removed, queueing again" << std::endl;
684 cacheMiss ( finishedReq );
685 finishedReq->clearForRestart();
686 enqueueRequest( finishedReq );
699 if ( fileNeedsCleanup )
702 resFile->resetDispose();
705 _targetFile = locFilename;
708 auto resObj = std::make_shared<ProvideResourceData>();
709 resObj->_mediaHandle = this->_handleRef;
710 resObj->_myFile = *resFile;
711 resObj->_resourceUrl = *(finishedReq->activeUrl());
712 resObj->_responseHeaders = msg.
headers();
717 p->setReady( expected<ProvideRes>::success( ProvideRes( resObj )) );
723 updateState( Finished );
727 cancelWithError( std::current_exception() );
729 cancelWithError( std::current_exception() );
741 auto weakThis = weak_from_this ();
742 provider().dequeueRequest ( _runningReq, error );
743 if ( weakThis.expired () )
752 p->setReady( expected<ProvideRes>::error( error ) );
757 updateState( Finished );
767 auto i = std::find_if( attachedMedia.begin(), attachedMedia.end(), [&](
const auto &m ) { return m._name == _handleRef.handle(); } );
768 if ( i == attachedMedia.end() )
771 urlToUse = i->_attachedUrl;
780 bool checkStaging =
false;
797 baseStats._bytesProvided = providedByNow;
808 , _mirrorList ( urls )
809 , _initialSpec ( request )
814 MIL <<
"Killing the AttachMediaItem" << std::endl;
821 auto promiseRef = std::make_shared<ProvidePromise<Provide::MediaHandle>>( shared_this<ProvideItem>() );
831 WAR <<
"Double init of AttachMediaItem!" << std::endl;
845 std::vector<zypp::Url> usableMirrs;
846 std::optional<ProvideQueue::Config> scheme;
849 const auto &s = prov.schemeConfig( prov.effectiveScheme( mirrIt->getScheme() ) );
851 WAR <<
"URL: " << *mirrIt <<
" is not supported, ignoring!" << std::endl;
856 usableMirrs.push_back ( *mirrIt );
858 if ( scheme->worker_type () == s->worker_type () ) {
859 usableMirrs.push_back( *mirrIt );
861 WAR <<
"URL: " << *mirrIt <<
" has different worker type than the primary URL: "<< usableMirrs.front() <<
", ignoring!" << std::endl;
883 auto &attachedMedia = prov.attachedMediaInfos ();
885 for (
auto &medium : attachedMedia ) {
892 for (
auto &otherItem : prov.items() ) {
893 auto attachIt = std::dynamic_pointer_cast<AttachMediaItem>(otherItem);
895 || attachIt.get() ==
this
902 const auto sameMedium = attachIt->_initialSpec.isSameMedium(
_initialSpec);
903 if ( zypp::indeterminate(sameMedium) ) {
905 if ( attachIt->_mirrorList.front() !=
_mirrorList.front() )
908 else if ( !(
bool)sameMedium )
911 MIL <<
"Found item providing the same medium, attaching to finished signal and waiting for it to be finished" << std::endl;
921 case ProvideQueue::Config::Downloading: {
932 if ( !smvDataLocal ) {
944 std::vector<zypp::Url> urls;
971 case ProvideQueue::Config::VolatileMount:
972 case ProvideQueue::Config::SimpleMount: {
981 ERR <<
"Failed to queue request" << std::endl;
1026 }
catch (
const std::exception &e ) {
1027 ERR <<
"WTF " << e.what () << std::endl;
1029 ERR <<
"WTF " << std::endl;
1033 _sigReady.emit( zyppng::expected<AttachedMediaInfo *>::success(&medium) );
1037 MIL <<
"Before setFinished" << std::endl;
1044 MIL <<
"Cancelling Item with error" << std::endl;
1048 _sigReady.emit( expected<AttachedMediaInfo *>::error(error) );
1052 auto weakThis = weak_from_this ();
1054 if ( weakThis.expired () )
1065 p->setReady( expected<zyppng::Provide::MediaHandle>::error( error ) );
1083 std::rethrow_exception ( result.error() );
1088 MIL_PRV <<
"Master item was cancelled, reverting to Uninitialized state and waiting for scheduler to run again" << std::endl;
1100 return AttachMediaItemRef(
new AttachMediaItem(urls, request, parent) );
1111 WAR <<
"Received event for unknown request, ignoring" << std::endl;
1115 if(
_workerType == ProvideQueue::Config::Downloading ) {
1117 if ( msg.
code() == ProvideMessage::Code::ProvideFinished ) {
1121 zypp::Url baseUrl = *finishedReq->activeUrl();
1127 if ( !smvDataRemote ) {
1136 if ( !smvDataRemote->valid () ) {
1141 if (!
_verifier->matches( smvDataRemote ) ) {
1143 DBG <<
"remote: " << smvDataRemote << std::endl;
1151 }
else if ( msg.
code() == ProvideMessage::Code::NotFound ) {
1167 if ( msg.
code() == ProvideMessage::Code::AttachFinished ) {
1172 , *finishedReq->activeUrl()
1184 if(
_workerType == ProvideQueue::Config::Downloading ) {
Store and operate with byte count.
Base class for Exception.
std::string asCompleteString() const
Returns a complete string representation of the Url object.
std::string asString() const
Returns a default string representation of the Url object.
std::string getPathName(EEncoding eflag=zypp::url::E_DECODED) const
Returns the path name from the URL.
void setPathName(const std::string &path, EEncoding eflag=zypp::url::E_DECODED)
Set the path name.
Wrapper class for stat/lstat.
bool isExist() const
Return whether valid stat info exists.
Pathname dirname() const
Return all but the last component od this path.
const std::string & asString() const
String representation.
bool empty() const
Test for an empty path.
expected< zypp::media::AuthData > authenticationRequired(ProvideQueue &queue, ProvideRequestRef req, const zypp::Url &effectiveUrl, int64_t lastTimestamp, const std::map< std::string, std::string > &extraFields) override
zypp::Pathname _stagingFile
void cancelWithError(std::exception_ptr error) override
zypp::ByteCount bytesExpected() const override
void setMediaRef(Provide::MediaHandle &&hdl)
Provide::MediaHandle & mediaRef()
Provide::MediaHandle _handleRef
void initialize() override
static ProvideFileItemRef create(const std::vector< zypp::Url > &urls, const ProvideFileSpec &request, ProvidePrivate &parent)
ProvideFileItem(const std::vector< zypp::Url > &urls, const ProvideFileSpec &request, ProvidePrivate &parent)
ProvideFileSpec _initialSpec
ProvidePromiseRef< ProvideRes > promise()
std::vector< zypp::Url > _mirrorList
zypp::ByteCount _expectedBytes
zypp::Pathname _targetFile
ItemStats makeStats() override
void informalMessage(ProvideQueue &, ProvideRequestRef req, const ProvideMessage &msg) override
ProvidePromiseWeakRef< ProvideRes > _promise
HeaderValueMap & customHeaders()
const zypp::Pathname & destFilenameHint() const
const zypp::ByteCount & downloadSize() const
The size of the resource on the server.
const zypp::Pathname & deltafile() const
The existing deltafile that can be used to reduce download size ( zchunk or metalink )
bool checkExistsOnly() const
bool safeRedirectTo(ProvideRequestRef startedReq, const zypp::Url &url)
virtual std::chrono::steady_clock::time_point startTime() const
virtual void cacheMiss(ProvideRequestRef req)
ProvideItem(ProvidePrivate &parent)
ProvidePrivate & provider()
virtual expected< zypp::media::AuthData > authenticationRequired(ProvideQueue &queue, ProvideRequestRef req, const zypp::Url &effectiveUrl, int64_t lastTimestamp, const std::map< std::string, std::string > &extraFields)
virtual ItemStats makeStats()
virtual bool canRedirectTo(ProvideRequestRef startedReq, const zypp::Url &url)
virtual std::chrono::steady_clock::time_point finishedTime() const
virtual zypp::ByteCount bytesExpected() const
ProvideRequestRef _runningReq
void redirectTo(ProvideRequestRef startedReq, const zypp::Url &url)
virtual void informalMessage(ProvideQueue &, ProvideRequestRef req, const ProvideMessage &msg)
const std::optional< ItemStats > & previousStats() const
virtual void finishReq(ProvideQueue &queue, ProvideRequestRef finishedReq, const ProvideMessage &msg)
virtual void cancelWithError(std::exception_ptr error)=0
const std::optional< ItemStats > & currentStats() const
void updateState(const State newState)
virtual bool enqueueRequest(ProvideRequestRef request)
HeaderValueMap headers() const
std::vector< FieldVal > values(const std::string_view &str) const
FieldVal value(const std::string_view &str, const FieldVal &defaultVal=FieldVal()) const
void setValue(const std::string &name, const FieldVal &value)
static ProvideMessage createProvide(const uint32_t reqId, const zypp::Url &url, const std::optional< std::string > &filename={}, const std::optional< std::string > &deltaFile={}, const std::optional< int64_t > &expFilesize={}, bool checkExistOnly=false)
static ProvideMessage createDetach(const uint32_t reqId, const zypp::Url &attachUrl)
static ProvideMessage createAttach(const uint32_t reqId, const zypp::Url &url, const std::string attachId, const std::string &label, const std::optional< std::string > &verifyType={}, const std::optional< std::string > &verifyData={}, const std::optional< int32_t > &mediaNr={})
bool dequeueRequest(ProvideRequestRef req, std::exception_ptr error)
std::string nextMediaId() const
Signal< std::optional< zypp::media::AuthData >(const zypp::Url &reqUrl, const std::string &triedUsername, const std::map< std::string, std::string > &extraValues) > _sigAuthRequired
std::vector< AttachedMediaInfo > & attachedMediaInfos()
void schedule(ScheduleReason reason)
const Config & workerConfig() const
static constexpr uint32_t InvalidId
void setActiveUrl(const zypp::Url &urlToUse)
ProvideQueueWeakRef _myQueue
const std::vector< zypp::Url > & urls() const
static expected< ProvideRequestRef > createDetach(const zypp::Url &url)
static expected< ProvideRequestRef > create(ProvideItem &owner, const std::vector< zypp::Url > &urls, const std::string &id, ProvideMediaSpec &spec)
void setCurrentQueue(ProvideQueueRef ref)
ProvideQueueRef currentQueue()
const std::optional< zypp::Url > activeUrl() const
int unlink(const Pathname &path)
Like 'unlink'.
AutoDispose< const Pathname > ManagedFile
A Pathname plus associated cleanup code to be executed when path is no longer needed.
constexpr std::string_view AttachId("attach_id")
constexpr std::string_view VerifyData("verify_data")
constexpr std::string_view VerifyType("verify_type")
constexpr std::string_view MediaNr("media_nr")
constexpr std::string_view Url("url")
constexpr std::string_view LastUser("username")
constexpr std::string_view Url("url")
constexpr std::string_view Reason("reason")
constexpr std::string_view LocalFilename("local_filename")
constexpr std::string_view CacheHit("cacheHit")
constexpr std::string_view Url("url")
constexpr std::string_view MetalinkEnabled("metalink_enabled")
constexpr std::string_view ExpectedFilesize("expected_filesize")
constexpr std::string_view DeltaFile("delta_file")
constexpr std::string_view CheckExistOnly("check_existance_only")
constexpr std::string_view Filename("filename")
constexpr std::string_view StagingFilename("staging_filename")
constexpr std::string_view Url("url")
constexpr std::string_view LocalFilename("local_filename")
constexpr std::string_view NewUrl("new_url")
std::unordered_map< std::string, boost::any > AnyMap
constexpr std::string_view NETWORK_METALINK_ENABLED("zypp-nw-metalink-enabled")
std::shared_ptr< ProvidePromise< T > > ProvidePromiseRef
static constexpr std::string_view DEFAULT_MEDIA_VERIFIER("SuseMediaV1")
ZYPP_IMPL_PRIVATE(Provide)
Convenient building of std::string via std::ostringstream Basically a std::ostringstream autoconverti...
std::chrono::steady_clock::time_point _pulseTime
#define ZYPP_CAUGHT(EXCPT)
Drops a logline telling the Exception was caught (in order to handle it).
#define ZYPP_EXCPT_PTR(EXCPT)
Drops a logline and returns Exception as a std::exception_ptr.