16#include <zypp-media/MediaException>
17#include <zypp-core/base/UserRequestException>
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 );
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 );
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;
220 finishedReq->setUrl( newUrl );
231 }
else if ( code == ProvideMessage::Code::Metalink ) {
236 MIL <<
"Request finished with mirrorlist from server." << std::endl;
243 for(
auto i = mirrors.cbegin(); i != mirrors.cend(); i++ ) {
254 WAR <<
"Received invalid URL from worker: " << i->asString() <<
" ignoring!" << std::endl;
256 WAR <<
"Received invalid value for newUrl from worker ignoring!" << std::endl;
265 MIL <<
"Found usable nr of mirrors: " << newOrigin.
endpointCount() << std::endl;
266 finishedReq->setOrigin( std::move(newOrigin) );
277 MIL <<
"End of mirrorlist handling"<< std::endl;
280 }
else if ( code >= ProvideMessage::Code::FirstClientErrCode && code <= ProvideMessage::Code::LastSrvErrCode ) {
285 std::exception_ptr errPtr;
287 const auto reqUrl = finishedReq->activeUrl().value();
290 case ProvideMessage::Code::BadRequest:
293 case ProvideMessage::Code::PeerCertificateInvalid:
296 case ProvideMessage::Code::ConnectionFailed:
299 case ProvideMessage::Code::ExpectedSizeExceeded: {
301 std::optional<int64_t> filesize;
302 const auto &hdrs = finishedReq->provideMessage ().headers ();
306 filesize = val.asInt64();
316 case ProvideMessage::Code::Cancelled:
319 case ProvideMessage::Code::InvalidChecksum:
322 case ProvideMessage::Code::Timeout:
325 case ProvideMessage::Code::NotFound:
328 case ProvideMessage::Code::Forbidden:
329 case ProvideMessage::Code::Unauthorized: {
331 const auto &hintVal = msg.
value(
"authHint"sv );
333 if ( hintVal.valid() && hintVal.isString() ) {
334 hint = hintVal.asString();
341 reqUrl, reason,
"", hint
346 case ProvideMessage::Code::MountFailed:
349 case ProvideMessage::Code::Jammed:
352 case ProvideMessage::Code::MediaChangeSkip:
353 errPtr =
ZYPP_EXCPT_PTR( zypp::SkipRequestException (
zypp::str::Str() <<
"User-requested skipping for URL: " << reqUrl <<
" " << reason ) );
355 case ProvideMessage::Code::MediaChangeAbort:
356 errPtr =
ZYPP_EXCPT_PTR( zypp::AbortRequestException(
zypp::str::Str() <<
"Aborting requested by user for URL: " << reqUrl <<
" " << reason ) );
358 case ProvideMessage::Code::InternalError:
361 case ProvideMessage::Code::NotAFile:
364 case ProvideMessage::Code::MediumNotDesired:
389 WAR <<
"Received event for unknown request, ignoring" << std::endl;
395 if (
log )
log->requestFailed( *
this, finishedReq->provideMessage().requestId(), excpt );
406 WAR <<
"Received authenticationRequired for unknown request, rejecting" << std::endl;
413 MIL <<
"Looking for existing auth data for " << effectiveUrl <<
"more recent then " << lastTimestamp << std::endl;
415 auto credPtr = mgr.
getCred( effectiveUrl );
416 if ( credPtr && credPtr->lastDatabaseUpdate() > lastTimestamp ) {
417 MIL <<
"Found existing auth data for " << effectiveUrl <<
"ts: " << credPtr->lastDatabaseUpdate() << std::endl;
421 if ( credPtr )
MIL <<
"Found existing auth data for " << effectiveUrl <<
"but too old ts: " << credPtr->lastDatabaseUpdate() << std::endl;
423 std::string username;
425 username = i->second;
429 MIL <<
"NO Auth data found, asking user. Last tried username was: " << username << std::endl;
432 if ( !userAuth || !userAuth->valid() ) {
433 MIL <<
"User rejected to give auth" << std::endl;
458 return d_func()->_parent.queueRequest( request );
464 if ( d->_itemState != newState ) {
469 const auto oldState = d->_itemState;
470 d->_itemState = newState;
471 d->_sigStateChanged( *
this, oldState, d->_itemState );
474 d->_itemStarted = std::chrono::steady_clock::now();
476 if (
log )
log->itemStart( *
this );
480 d->_itemFinished = std::chrono::steady_clock::now();
482 if (
log)
log->itemDone( *
this );
483 d->_parent.dequeueItem(
this);
494 MIL <<
"Item Cleanup due to released Promise in state:" <<
state() << std::endl;
500 return d_func()->_itemState;
517 case ProvideMessage::Code::Attach:
520 case ProvideMessage::Code::Detach:
523 case ProvideMessage::Code::Prov:
528 throw std::logic_error(
"Invalid message type in ProvideRequest");
530 if ( !
url.valid() ) {
547 case ProvideMessage::Code::Attach:
550 case ProvideMessage::Code::Detach:
553 case ProvideMessage::Code::Prov:
558 throw std::logic_error(
"Invalid message type in ProvideRequest");
576 WAR <<
"Double init of ProvideFileItem!" << std::endl;
619 WAR <<
"Received event for unknown request, ignoring" << std::endl;
623 if ( msg.
code() == ProvideMessage::Code::ProvideStarted ) {
624 MIL <<
"Provide File Request: "<< req->url() <<
" was started" << std::endl;
628 if ( !locPath.empty() )
632 if ( !locPath.empty() )
636 auto effUrl = req->activeUrl().value_or(
zypp::Url() );
653 if ( finishedReq != _runningReq ) {
654 WAR <<
"Received event for unknown request, ignoring" << std::endl;
658 if ( msg.
code () == ProvideMessage::Code::ProvideFinished ) {
660 auto log = provider().log();
663 m[
"spec"] = _initialSpec;
664 if ( log ) log->requestDone( *
this, msg.
requestId(), m );
667 MIL <<
"Request was successfully finished!" << std::endl;
671 std::optional<zypp::ManagedFile> resFile;
678 const bool checkExistsOnly = _initialSpec.checkExistsOnly();
682 if ( doesDownload && !checkExistsOnly ) {
684 resFile = provider().addToFileCache ( locFilename );
687 MIL <<
"CACHE MISS, file " << locFilename <<
" was already removed, queueing again" << std::endl;
688 cacheMiss ( finishedReq );
689 finishedReq->clearForRestart();
690 enqueueRequest( finishedReq );
703 if ( fileNeedsCleanup && !checkExistsOnly )
706 resFile->resetDispose();
709 _targetFile = locFilename;
713 cancelWithError( std::current_exception() );
714 }
catch (
const std::exception &e ) {
716 cancelWithError( std::current_exception() );
718 cancelWithError( std::current_exception() );
722 auto resObj = std::make_shared<ProvideResourceData>();
723 resObj->_mediaHandle = this->_handleRef;
724 resObj->_myFile = *resFile;
725 resObj->_resourceUrl = *(finishedReq->activeUrl());
726 resObj->_responseHeaders = msg.
headers();
729 std::exception_ptr excpt;
735 ERR <<
"Caught unhandled pipline exception:" << e << std::endl;
737 excpt = std::current_exception ();
738 }
catch (
const std::exception &e ) {
739 ERR <<
"Caught unhandled pipline exception:" << e.what() << std::endl;
741 excpt = std::current_exception ();
743 ERR <<
"Caught unhandled unknown exception:" << std::endl;
744 excpt = std::current_exception ();
748 updateState( Finished );
751 ERR <<
"Rethrowing pipeline exception, this is a BUG!" << std::endl;
752 std::rethrow_exception ( excpt );
757 switch( msg.
code() ) {
763 auto log = provider().log();
764 MIL <<
"Request failed trying to recover." << std::endl;
766 bool canRedirect =
false;
767 for (
const auto &ep : _origin ) {
768 if ( canRedirectTo ( finishedReq, ep.url() ) ) {
775 MIL <<
"Trying to recover by redirecting to a mirror" << std::endl;
776 if ( enqueueRequest( finishedReq ) )
780 MIL <<
"No mirror found or no mirror usable, giving up" << std::endl;
795 auto weakThis = weak_from_this ();
797 if ( weakThis.expired () )
821 if ( std::find( attachedMedia.begin(), attachedMedia.end(),
_handleRef.mediaInfo() ) == attachedMedia.end() )
823 urlToUse =
_handleRef.mediaInfo()->attachedUrl();
832 bool checkStaging =
false;
849 baseStats._bytesProvided = providedByNow;
866 MIL <<
"Killing the AttachMediaItem" << std::endl;
883 WAR <<
"Double init of AttachMediaItem!" << std::endl;
899 if ( !scheme || !
_origin.isValid() ) {
916 auto &attachedMedia = prov.attachedMediaInfos ();
919 for (
auto &medium : attachedMedia ) {
926 for (
auto &otherItem : prov.items() ) {
927 auto attachIt = std::dynamic_pointer_cast<AttachMediaItem>(otherItem);
929 || attachIt.get() ==
this
940 MIL <<
"Found item providing the same medium, attaching to finished signal and waiting for it to be finished" << std::endl;
961 if ( !smvDataLocal ) {
966 if ( !smvDataLocal->load(
_initialSpec.mediaFile() ) ) {
974 for (
auto &ep : fileOrigin ) {
1007 ERR <<
"Failed to queue request" << std::endl;
1042 }
catch (
const std::exception &e ) {
1043 ERR <<
"WTF " << e.what () << std::endl;
1045 ERR <<
"WTF " << std::endl;
1053 MIL <<
"Before setFinished" << std::endl;
1060 MIL <<
"Cancelling Item with error" << std::endl;
1068 auto weakThis = weak_from_this ();
1070 if ( weakThis.expired () )
1098 std::rethrow_exception ( result.
error() );
1103 MIL_PRV <<
"Master item was cancelled, reverting to Uninitialized state and waiting for scheduler to run again" << std::endl;
1126 WAR <<
"Received event for unknown request, ignoring" << std::endl;
1132 if ( msg.
code() == ProvideMessage::Code::ProvideFinished ) {
1136 zypp::Url baseUrl = *finishedReq->activeUrl();
1142 if ( !smvDataRemote ) {
1151 if ( !smvDataRemote->valid () ) {
1156 if (!
_verifier->matches( smvDataRemote ) ) {
1158 DBG <<
"remote: " << smvDataRemote << std::endl;
1167 }
else if ( msg.
code() == ProvideMessage::Code::NotFound ) {
1180 if ( msg.
code() == ProvideMessage::Code::AttachFinished ) {
1182 std::optional<zypp::Pathname> mntPoint;
1184 if ( mountPtVal.valid() && mountPtVal.isString() ) {
Store and operate with byte count.
Base class for Exception.
Manages a data source characterized by an authoritative URL and a list of mirror URLs.
void setAuthority(OriginEndpoint newAuthority)
bool addMirror(OriginEndpoint newMirror)
uint endpointCount() const
std::string asCompleteString() const
Returns a complete 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.
std::shared_ptr< T > shared_this() const
static auto connect(typename internal::MemberFunction< SenderFunc >::ClassType &s, SenderFunc &&sFun, typename internal::MemberFunction< ReceiverFunc >::ClassType &recv, ReceiverFunc &&rFunc)
std::weak_ptr< T > weak_this() const
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
ProvideFileItem(zypp::MirroredOrigin origin, const ProvideFileSpec &request, ProvidePrivate &parent)
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
zypp::MirroredOrigin _origin
ProvideFileSpec _initialSpec
static ProvideFileItemRef create(zypp::MirroredOrigin origin, const ProvideFileSpec &request, ProvidePrivate &parent)
ProvidePromiseRef< ProvideRes > promise()
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
friend class ProvidePrivate
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)
friend class ProvideQueue
virtual bool enqueueRequest(ProvideRequestRef request)
const HeaderValueMap & headers() const
FieldVal value(const std::string_view &str, const FieldVal &defaultVal=FieldVal()) const
const std::vector< ProvideMessage::FieldVal > & values(const std::string_view &str) const
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_Ptr > & attachedMediaInfos()
void schedule(ScheduleReason reason)
const Config & workerConfig() const
static constexpr uint32_t InvalidId
void setActiveUrl(const zypp::Url &urlToUse)
ProvideQueueWeakRef _myQueue
static expected< ProvideRequestRef > createDetach(const zypp::Url &url)
void setCurrentQueue(ProvideQueueRef ref)
ProvideQueueRef currentQueue()
const zypp::MirroredOrigin & origin() const
const std::optional< zypp::Url > activeUrl() const
Returns the currenty active URL as set by the scheduler.
static expected< ProvideRequestRef > create(ProvideItem &owner, const zypp::MirroredOrigin &origin, const std::string &id, ProvideMediaSpec &spec)
ProvideRequest(ProvideItem *owner, zypp::MirroredOrigin origin, ProvideMessage &&msg)
A ProvideRes object is a reference counted ownership of a resource in the cache provided by a Provide...
ProvideMediaHandle MediaHandle
WorkerType worker_type() const
static expected success(ConsParams &&...params)
static expected error(ConsParams &&...params)
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.
intrusive_ptr< T > make_intrusive(Args &&... __args)
constexpr std::string_view LocalMountPoint("local_mountpoint")
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")
constexpr std::string_view NETWORK_METALINK_ENABLED("zypp-nw-metalink-enabled")
static constexpr std::string_view DEFAULT_MEDIA_VERIFIER("SuseMediaV1")
std::shared_ptr< ProvidePromise< T > > ProvidePromiseRef
std::unordered_map< std::string, boost::any > AnyMap
Convenient building of std::string via std::ostringstream Basically a std::ostringstream autoconverti...
#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.
#define ZYPP_FWD_CURRENT_EXCPT()
Drops a logline and returns the current Exception as a std::exception_ptr.
#define ZYPP_IMPL_PRIVATE(Class)