diff --git a/src/AbstractCommand.cc b/src/AbstractCommand.cc index ba1297bc..ae7f5b2f 100644 --- a/src/AbstractCommand.cc +++ b/src/AbstractCommand.cc @@ -237,7 +237,8 @@ bool AbstractCommand::execute() if (req_ && fileEntry_->getLength() > 0 && e_->getRequestGroupMan()->getMaxOverallDownloadSpeedLimit() == 0 && requestGroup_->getMaxDownloadSpeedLimit() == 0 && - serverStatTimer_.difference(global::wallclock()) >= 10) { + serverStatTimer_.difference(global::wallclock()) >= + std::chrono::seconds(10)) { serverStatTimer_ = global::wallclock(); std::vector> usedHosts; if (getOption()->getAsBool(PREF_SELECT_LEAST_USED_HOST)) { @@ -284,7 +285,7 @@ bool AbstractCommand::execute() A2_LOG_DEBUG("All segments are ignored."); // This will execute other idle Commands and let them // finish quickly. - e_->setRefreshInterval(0); + e_->setRefreshInterval(std::chrono::milliseconds(0)); return true; } @@ -386,7 +387,8 @@ bool AbstractCommand::execute() } Timer wakeTime(global::wallclock()); - wakeTime.advance(getOption()->getAsInt(PREF_RETRY_WAIT)); + wakeTime.advance( + std::chrono::seconds(getOption()->getAsInt(PREF_RETRY_WAIT))); req_->setWakeTime(wakeTime); return prepareForRetry(0); } @@ -401,7 +403,7 @@ bool AbstractCommand::execute() A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, err); } requestGroup_->setHaltRequested(true); - getDownloadEngine()->setRefreshInterval(0); + getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0)); return true; } } @@ -457,7 +459,7 @@ bool AbstractCommand::prepareForRetry(time_t wait) } else { // We don't use wait so that Command can be executed by - // DownloadEngine::setRefreshInterval(0). + // DownloadEngine::setRefreshInterval(std::chrono::milliseconds(0)). command->setStatus(Command::STATUS_INACTIVE); } e_->addCommand(std::move(command)); diff --git a/src/AbstractCommand.h b/src/AbstractCommand.h index 5cca26a5..6cf5a5de 100644 --- a/src/AbstractCommand.h +++ b/src/AbstractCommand.h @@ -83,7 +83,7 @@ private: Timer checkPoint_; Timer serverStatTimer_; - time_t timeout_; + std::chrono::seconds timeout_; bool checkSocketIsReadable_; bool checkSocketIsWritable_; @@ -185,14 +185,14 @@ public: // check. void swapSocket(std::shared_ptr& socket); - time_t getTimeout() const + std::chrono::seconds getTimeout() const { return timeout_; } - void setTimeout(time_t timeout) + void setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } void prepareForNextAction(std::unique_ptr checkEntry); diff --git a/src/AbstractHttpServerResponseCommand.cc b/src/AbstractHttpServerResponseCommand.cc index fe3fbb34..07ae91be 100644 --- a/src/AbstractHttpServerResponseCommand.cc +++ b/src/AbstractHttpServerResponseCommand.cc @@ -119,7 +119,8 @@ bool AbstractHttpServerResponseCommand::execute() afterSend(httpServer_, e_); return true; } else { - if(timeoutTimer_.difference(global::wallclock()) >= 30) { + if (timeoutTimer_.difference(global::wallclock()) >= + std::chrono::seconds(30)) { A2_LOG_INFO(fmt("CUID#%" PRId64 " - HttpServer: Timeout while trasmitting response.", getCuid())); diff --git a/src/AbstractProxyRequestCommand.cc b/src/AbstractProxyRequestCommand.cc index 6d52ea9c..3dd01adf 100644 --- a/src/AbstractProxyRequestCommand.cc +++ b/src/AbstractProxyRequestCommand.cc @@ -64,7 +64,7 @@ AbstractProxyRequestCommand::AbstractProxyRequestCommand (std::make_shared (cuid, s, std::make_shared(s))) { - setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); disableReadCheckSocket(); setWriteCheckSocket(getSocket()); } diff --git a/src/ActivePeerConnectionCommand.cc b/src/ActivePeerConnectionCommand.cc index 311daf1a..1e2b44da 100644 --- a/src/ActivePeerConnectionCommand.cc +++ b/src/ActivePeerConnectionCommand.cc @@ -60,10 +60,10 @@ ActivePeerConnectionCommand::ActivePeerConnectionCommand (cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - time_t interval) + std::chrono::seconds interval) : Command(cuid), requestGroup_(requestGroup), - interval_(interval), + interval_(std::move(interval)), e_(e), numNewConnection_(5) { diff --git a/src/ActivePeerConnectionCommand.h b/src/ActivePeerConnectionCommand.h index 0aeaa6d7..fc6203f8 100644 --- a/src/ActivePeerConnectionCommand.h +++ b/src/ActivePeerConnectionCommand.h @@ -59,7 +59,7 @@ private: std::shared_ptr peerStorage_; std::shared_ptr btAnnounce_; - time_t interval_; // UNIT: sec + std::chrono::seconds interval_; DownloadEngine* e_; Timer checkPoint_; int numNewConnection_; // the number of the connection to establish. @@ -67,7 +67,7 @@ public: ActivePeerConnectionCommand(cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - time_t interval); + std::chrono::seconds interval); virtual ~ActivePeerConnectionCommand(); diff --git a/src/AdaptiveURISelector.cc b/src/AdaptiveURISelector.cc index afa42a5b..c00d15ad 100644 --- a/src/AdaptiveURISelector.cc +++ b/src/AdaptiveURISelector.cc @@ -96,6 +96,10 @@ std::string AdaptiveURISelector::select return selected; } +namespace { +constexpr auto MAX_TIMEOUT = std::chrono::seconds(60); +} // namespace + void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) { if (requestGroup_->getTimeout()*2 >= MAX_TIMEOUT) return; @@ -111,10 +115,11 @@ void AdaptiveURISelector::mayRetryWithIncreasedTimeout(FileEntry* fileEntry) if(A2_LOG_DEBUG_ENABLED) { for(std::deque::const_iterator i = uris.begin(), eoi = uris.end(); i != eoi; ++i) { - A2_LOG_DEBUG(fmt("AdaptiveURISelector: will retry server with increased" - " timeout (%ld s): %s", - static_cast(requestGroup_->getTimeout()), - (*i).c_str())); + A2_LOG_DEBUG( + fmt("AdaptiveURISelector: will retry server with increased" + " timeout (%ld s): %s", + static_cast(requestGroup_->getTimeout().count()), + (*i).c_str())); } } } diff --git a/src/AdaptiveURISelector.h b/src/AdaptiveURISelector.h index a9f5d8ac..28a7fa0b 100644 --- a/src/AdaptiveURISelector.h +++ b/src/AdaptiveURISelector.h @@ -38,6 +38,7 @@ #include "URISelector.h" #include +#include namespace aria2 { @@ -53,8 +54,6 @@ private: int nbServerToEvaluate_; int nbConnections_; - static const time_t MAX_TIMEOUT = 60; - void mayRetryWithIncreasedTimeout(FileEntry* fileEntry); std::string selectOne(const std::deque& uris); diff --git a/src/AutoSaveCommand.cc b/src/AutoSaveCommand.cc index 8362d196..400a55dc 100644 --- a/src/AutoSaveCommand.cc +++ b/src/AutoSaveCommand.cc @@ -38,9 +38,9 @@ namespace aria2 { -AutoSaveCommand::AutoSaveCommand -(cuid_t cuid, DownloadEngine* e, time_t interval) - : TimeBasedCommand(cuid, e, interval, true) +AutoSaveCommand::AutoSaveCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval) + : TimeBasedCommand(cuid, e, std::move(interval), true) {} AutoSaveCommand::~AutoSaveCommand() {} diff --git a/src/AutoSaveCommand.h b/src/AutoSaveCommand.h index ccbd9d92..591246a0 100644 --- a/src/AutoSaveCommand.h +++ b/src/AutoSaveCommand.h @@ -42,7 +42,8 @@ namespace aria2 { class AutoSaveCommand : public TimeBasedCommand { public: - AutoSaveCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + AutoSaveCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~AutoSaveCommand(); diff --git a/src/BackupIPv4ConnectCommand.cc b/src/BackupIPv4ConnectCommand.cc index 8963953f..66eaf6a9 100644 --- a/src/BackupIPv4ConnectCommand.cc +++ b/src/BackupIPv4ConnectCommand.cc @@ -114,7 +114,8 @@ bool BackupIPv4ConnectCommand::execute() // TODO Although we check 300ms initial timeout as described in // RFC 6555, the interval will be much longer and around 1 second // due to the refresh interval mechanism in DownloadEngine. - if(startTime_.differenceInMillis(global::wallclock()) >= 300) { + if(startTime_.difference(global::wallclock()) >= + std::chrono::milliseconds(300)) { socket_ = std::make_shared(); try { socket_->establishConnection(ipaddr_, port_); diff --git a/src/BackupIPv4ConnectCommand.h b/src/BackupIPv4ConnectCommand.h index fd3b2dfa..8ae50e06 100644 --- a/src/BackupIPv4ConnectCommand.h +++ b/src/BackupIPv4ConnectCommand.h @@ -81,7 +81,7 @@ private: DownloadEngine* e_; Timer startTime_; Timer timeoutCheck_; - time_t timeout_; + std::chrono::seconds timeout_; }; } // namespace aria2 diff --git a/src/BtAnnounce.cc b/src/BtAnnounce.cc index 25b321d7..1d77e4d6 100644 --- a/src/BtAnnounce.cc +++ b/src/BtAnnounce.cc @@ -54,4 +54,6 @@ const std::string BtAnnounce::PEERS("peers"); const std::string BtAnnounce::PEERS6("peers6"); +constexpr std::chrono::seconds BtAnnounce::DEFAULT_ANNOUNCE_INTERVAL; + } // namespace aria2 diff --git a/src/BtAnnounce.h b/src/BtAnnounce.h index de1a0524..2ee2131f 100644 --- a/src/BtAnnounce.h +++ b/src/BtAnnounce.h @@ -116,7 +116,7 @@ public: */ virtual void shuffleAnnounce() = 0; - virtual void overrideMinInterval(time_t interval) = 0; + virtual void overrideMinInterval(std::chrono::seconds interval) = 0; virtual void setTcpPort(uint16_t port) = 0; @@ -138,7 +138,7 @@ public: static const std::string PEERS6; - static const time_t DEFAULT_ANNOUNCE_INTERVAL = 120; + constexpr static auto DEFAULT_ANNOUNCE_INTERVAL = std::chrono::seconds(120); }; } // namespace aria2 diff --git a/src/BtLeecherStateChoke.cc b/src/BtLeecherStateChoke.cc index 7da3f6b3..dd352926 100644 --- a/src/BtLeecherStateChoke.cc +++ b/src/BtLeecherStateChoke.cc @@ -47,17 +47,20 @@ namespace aria2 { BtLeecherStateChoke::BtLeecherStateChoke() : round_(0), - lastRound_(0) + lastRound_(Timer::zero()) {} BtLeecherStateChoke::~BtLeecherStateChoke() {} -BtLeecherStateChoke::PeerEntry::PeerEntry(const std::shared_ptr& peer): - peer_(peer), downloadSpeed_(peer->calculateDownloadSpeed()), - // peer must be interested to us and sent block in the last 30 seconds - regularUnchoker_ - (peer->peerInterested() && - peer->getLastDownloadUpdate().difference(global::wallclock()) < 30) {} +BtLeecherStateChoke::PeerEntry::PeerEntry(const std::shared_ptr& peer) + : peer_(peer), + downloadSpeed_(peer->calculateDownloadSpeed()), + // peer must be interested to us and sent block in the last 30 seconds + regularUnchoker_(peer->peerInterested() && + peer->getLastDownloadUpdate().difference( + global::wallclock()) < std::chrono::seconds(30)) +{ +} BtLeecherStateChoke::PeerEntry::PeerEntry(const PeerEntry& c) : peer_(c.peer_), diff --git a/src/BtSeederStateChoke.cc b/src/BtSeederStateChoke.cc index dbe7e410..29e4cc10 100644 --- a/src/BtSeederStateChoke.cc +++ b/src/BtSeederStateChoke.cc @@ -47,11 +47,15 @@ namespace aria2 { BtSeederStateChoke::BtSeederStateChoke() : round_(0), - lastRound_(0) + lastRound_(Timer::zero()) {} BtSeederStateChoke::~BtSeederStateChoke() {} +namespace { +constexpr auto TIME_FRAME = std::chrono::seconds(20); +} // namespace + BtSeederStateChoke::PeerEntry::PeerEntry (const std::shared_ptr& peer): peer_(peer), diff --git a/src/BtSeederStateChoke.h b/src/BtSeederStateChoke.h index c7342d52..d333b7c6 100644 --- a/src/BtSeederStateChoke.h +++ b/src/BtSeederStateChoke.h @@ -61,7 +61,6 @@ private: bool recentUnchoking_; int uploadSpeed_; - const static time_t TIME_FRAME = 20; public: PeerEntry(const std::shared_ptr& peer); PeerEntry(const PeerEntry& c); diff --git a/src/BtSetup.cc b/src/BtSetup.cc index db2624ce..7e9ec591 100644 --- a/src/BtSetup.cc +++ b/src/BtSetup.cc @@ -125,8 +125,9 @@ void BtSetup::setup(std::vector>& commands, commands.push_back(std::move(c)); } { - auto c = make_unique - (e->newCUID(), requestGroup, e, metadataGetMode?2:10); + auto c = make_unique( + e->newCUID(), requestGroup, e, + std::chrono::seconds(metadataGetMode ? 2 : 10)); c->setBtRuntime(btRuntime); c->setPieceStorage(pieceStorage); c->setPeerStorage(peerStorage); @@ -158,8 +159,8 @@ void BtSetup::setup(std::vector>& commands, if(!metadataGetMode) { auto unionCri = make_unique(); if(option->defined(PREF_SEED_TIME)) { - unionCri->addSeedCriteria(make_unique - (option->getAsInt(PREF_SEED_TIME)*60)); + unionCri->addSeedCriteria(make_unique( + std::chrono::seconds(option->getAsInt(PREF_SEED_TIME) * 60))); } { double ratio = option->getAsDouble(PREF_SEED_RATIO); @@ -271,10 +272,10 @@ void BtSetup::setup(std::vector>& commands, } } } - time_t btStopTimeout = option->getAsInt(PREF_BT_STOP_TIMEOUT); + auto btStopTimeout = option->getAsInt(PREF_BT_STOP_TIMEOUT); if(btStopTimeout > 0) { auto stopDownloadCommand = make_unique - (e->newCUID(), requestGroup, e, btStopTimeout); + (e->newCUID(), requestGroup, e, std::chrono::seconds(btStopTimeout)); stopDownloadCommand->setBtRuntime(btRuntime); stopDownloadCommand->setPieceStorage(pieceStorage); commands.push_back(std::move(stopDownloadCommand)); diff --git a/src/BtStopDownloadCommand.cc b/src/BtStopDownloadCommand.cc index 3fe63b5a..ba3ebcaf 100644 --- a/src/BtStopDownloadCommand.cc +++ b/src/BtStopDownloadCommand.cc @@ -50,10 +50,10 @@ BtStopDownloadCommand::BtStopDownloadCommand (cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - time_t timeout) - : TimeBasedCommand(cuid, e, 1), + std::chrono::seconds timeout) + : TimeBasedCommand(cuid, e, std::chrono::seconds(1)), requestGroup_(requestGroup), - timeout_(timeout) + timeout_(std::move(timeout)) {} void BtStopDownloadCommand::preProcess() @@ -66,7 +66,7 @@ void BtStopDownloadCommand::preProcess() " --bt-stop-timeout option."), GroupId::toHex(requestGroup_->getGID()).c_str())); requestGroup_->setForceHaltRequested(true); - getDownloadEngine()->setRefreshInterval(0); + getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0)); enableExit(); } } diff --git a/src/BtStopDownloadCommand.h b/src/BtStopDownloadCommand.h index b4dc819b..ae592a92 100644 --- a/src/BtStopDownloadCommand.h +++ b/src/BtStopDownloadCommand.h @@ -51,7 +51,7 @@ class BtStopDownloadCommand:public TimeBasedCommand { private: RequestGroup* requestGroup_; - time_t timeout_; + std::chrono::seconds timeout_; Timer checkPoint_; @@ -63,7 +63,7 @@ public: (cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e, - time_t timeout); + std::chrono::seconds timeout); virtual void preProcess() CXX11_OVERRIDE; diff --git a/src/ConnectCommand.cc b/src/ConnectCommand.cc index 063fa457..f4fd534b 100644 --- a/src/ConnectCommand.cc +++ b/src/ConnectCommand.cc @@ -57,7 +57,7 @@ ConnectCommand::ConnectCommand(cuid_t cuid, : AbstractCommand(cuid, req, fileEntry, requestGroup, e, s), proxyRequest_(proxyRequest) { - setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); disableReadCheckSocket(); setWriteCheckSocket(getSocket()); } diff --git a/src/ConsoleStatCalc.cc b/src/ConsoleStatCalc.cc index 05702d18..d90e6284 100644 --- a/src/ConsoleStatCalc.cc +++ b/src/ConsoleStatCalc.cc @@ -265,10 +265,10 @@ void printProgressSummary(const RequestGroupList& groups, size_t cols, } } // namespace -ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval, +ConsoleStatCalc::ConsoleStatCalc(std::chrono::seconds summaryInterval, bool colorOutput, bool humanReadable): - summaryInterval_(summaryInterval), + summaryInterval_(std::move(summaryInterval)), readoutVisibility_(true), truncate_(true), #ifdef __MINGW32__ @@ -288,7 +288,8 @@ ConsoleStatCalc::ConsoleStatCalc(time_t summaryInterval, void ConsoleStatCalc::calculateStat(const DownloadEngine* e) { - if(cp_.differenceInMillis(global::wallclock())+A2_DELTA_MILLIS < 1000) { + if(cp_.difference(global::wallclock()) + A2_DELTA_MILLIS < + std::chrono::milliseconds(1000)) { return; } cp_ = global::wallclock(); @@ -317,8 +318,8 @@ ConsoleStatCalc::calculateStat(const DownloadEngine* e) } ColorizedStream o; if(e->getRequestGroupMan()->countRequestGroup() > 0) { - if((summaryInterval_ > 0) && - lastSummaryNotified_.differenceInMillis(global::wallclock())+ + if((summaryInterval_ > std::chrono::seconds(0)) && + lastSummaryNotified_.difference(global::wallclock())+ A2_DELTA_MILLIS >= summaryInterval_*1000) { lastSummaryNotified_ = global::wallclock(); printProgressSummary(e->getRequestGroupMan()->getRequestGroups(), cols, e, diff --git a/src/ConsoleStatCalc.h b/src/ConsoleStatCalc.h index b0606a86..f3faaaa6 100644 --- a/src/ConsoleStatCalc.h +++ b/src/ConsoleStatCalc.h @@ -61,7 +61,7 @@ private: Timer lastSummaryNotified_; - time_t summaryInterval_; + std::chrono::seconds summaryInterval_; std::unique_ptr sizeFormatter_; bool readoutVisibility_; @@ -69,7 +69,7 @@ private: bool isTTY_; bool colorOutput_; public: - ConsoleStatCalc(time_t summaryInterval, bool colorOutput = true, + ConsoleStatCalc(std::chrono::seconds summaryInterval, bool colorOutput = true, bool humanReadable = true); virtual ~ConsoleStatCalc() {} diff --git a/src/DHTAutoSaveCommand.cc b/src/DHTAutoSaveCommand.cc index 7cd22fca..3623c0e0 100644 --- a/src/DHTAutoSaveCommand.cc +++ b/src/DHTAutoSaveCommand.cc @@ -57,8 +57,8 @@ namespace aria2 { DHTAutoSaveCommand::DHTAutoSaveCommand -(cuid_t cuid, DownloadEngine* e, int family, time_t interval) - : TimeBasedCommand{cuid, e, interval}, +(cuid_t cuid, DownloadEngine* e, int family, std::chrono::seconds interval) + : TimeBasedCommand{cuid, e, std::move(interval)}, family_{family}, routingTable_{nullptr} {} diff --git a/src/DHTAutoSaveCommand.h b/src/DHTAutoSaveCommand.h index 9f6111f4..011373df 100644 --- a/src/DHTAutoSaveCommand.h +++ b/src/DHTAutoSaveCommand.h @@ -56,7 +56,7 @@ private: void save(); public: DHTAutoSaveCommand - (cuid_t cuid, DownloadEngine* e, int family, time_t interval); + (cuid_t cuid, DownloadEngine* e, int family, std::chrono::seconds interval); virtual ~DHTAutoSaveCommand(); diff --git a/src/DHTBucketRefreshCommand.cc b/src/DHTBucketRefreshCommand.cc index eb9b2fac..120577fc 100644 --- a/src/DHTBucketRefreshCommand.cc +++ b/src/DHTBucketRefreshCommand.cc @@ -43,8 +43,8 @@ namespace aria2 { DHTBucketRefreshCommand::DHTBucketRefreshCommand -(cuid_t cuid, DownloadEngine* e, time_t interval) - : TimeBasedCommand{cuid, e, interval}, +(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) + : TimeBasedCommand{cuid, e, std::move(interval)}, routingTable_{nullptr}, taskQueue_{nullptr}, taskFactory_{nullptr} diff --git a/src/DHTBucketRefreshCommand.h b/src/DHTBucketRefreshCommand.h index 2d9f5ca2..bf0a6a50 100644 --- a/src/DHTBucketRefreshCommand.h +++ b/src/DHTBucketRefreshCommand.h @@ -53,7 +53,8 @@ private: DHTTaskFactory* taskFactory_; public: - DHTBucketRefreshCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + DHTBucketRefreshCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~DHTBucketRefreshCommand(); diff --git a/src/DHTConstants.h b/src/DHTConstants.h index a6534b47..a59b1db7 100644 --- a/src/DHTConstants.h +++ b/src/DHTConstants.h @@ -35,6 +35,9 @@ #ifndef D_DHT_CONSTANTS_H #define D_DHT_CONSTANTS_H +#include "common.h" +#include "TimerA2.h" + // Increment this if major improvements or bug fixes are made in DHT // code. This is 2 bytes unsigned integer. #define DHT_VERSION 3U @@ -46,20 +49,20 @@ #define DHT_TOKEN_LENGTH 4 // See --dht-message-timeout option. -#define DHT_MESSAGE_TIMEOUT 10 +constexpr auto DHT_MESSAGE_TIMEOUT = std::chrono::seconds(10); -#define DHT_NODE_CONTACT_INTERVAL (15*60) +constexpr auto DHT_NODE_CONTACT_INTERVAL = std::chrono::minutes(15); -#define DHT_BUCKET_REFRESH_INTERVAL (15*60) +constexpr auto DHT_BUCKET_REFRESH_INTERVAL = std::chrono::minutes(15); -#define DHT_BUCKET_REFRESH_CHECK_INTERVAL (5*60) +constexpr auto DHT_BUCKET_REFRESH_CHECK_INTERVAL = std::chrono::minutes(5); -#define DHT_PEER_ANNOUNCE_PURGE_INTERVAL (30*60) +constexpr auto DHT_PEER_ANNOUNCE_PURGE_INTERVAL = std::chrono::minutes(30); -#define DHT_PEER_ANNOUNCE_INTERVAL (15*60) +constexpr auto DHT_PEER_ANNOUNCE_INTERVAL = std::chrono::minutes(15); -#define DHT_PEER_ANNOUNCE_CHECK_INTERVAL (5*60) +constexpr auto DHT_PEER_ANNOUNCE_CHECK_INTERVAL = std::chrono::minutes(5); -#define DHT_TOKEN_UPDATE_INTERVAL (10*60) +constexpr auto DHT_TOKEN_UPDATE_INTERVAL = std::chrono::minutes(10); #endif // D_DHT_CONSTANTS_H diff --git a/src/DHTGetPeersCommand.cc b/src/DHTGetPeersCommand.cc index 345c5182..c992ae1b 100644 --- a/src/DHTGetPeersCommand.cc +++ b/src/DHTGetPeersCommand.cc @@ -55,13 +55,13 @@ namespace aria2 { namespace { -const time_t GET_PEER_INTERVAL = (15*60); +constexpr auto GET_PEER_INTERVAL = std::chrono::minutes(15); // Interval when the size of peer list is low. -const time_t GET_PEER_INTERVAL_LOW = (5*60); +constexpr auto GET_PEER_INTERVAL_LOW = std::chrono::minutes(5); // Interval when the peer list is empty. -const time_t GET_PEER_INTERVAL_ZERO = 60; +constexpr auto GET_PEER_INTERVAL_ZERO = std::chrono::minutes(1); // Interval for retry. -const time_t GET_PEER_INTERVAL_RETRY = 5; +constexpr auto GET_PEER_INTERVAL_RETRY = std::chrono::seconds(5); // Maximum retries. Try more than 5 to drop bad node. const int MAX_RETRIES = 10; @@ -77,7 +77,7 @@ DHTGetPeersCommand::DHTGetPeersCommand taskQueue_{nullptr}, taskFactory_{nullptr}, numRetry_{0}, - lastGetPeerTime_{0} + lastGetPeerTime_{Timer::zero()} { requestGroup_->increaseNumCommand(); } @@ -92,7 +92,7 @@ bool DHTGetPeersCommand::execute() if(btRuntime_->isHalt()) { return true; } - time_t elapsed = lastGetPeerTime_.difference(global::wallclock()); + auto elapsed = lastGetPeerTime_.difference(global::wallclock()); if(!task_ && (elapsed >= GET_PEER_INTERVAL || (((btRuntime_->lessThanMinPeers() && diff --git a/src/DHTMessageDispatcher.h b/src/DHTMessageDispatcher.h index c8da7b2c..fc5eb4dd 100644 --- a/src/DHTMessageDispatcher.h +++ b/src/DHTMessageDispatcher.h @@ -52,7 +52,7 @@ public: virtual void addMessageToQueue(std::unique_ptr message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback = std::unique_ptr{}) = 0; diff --git a/src/DHTMessageDispatcherImpl.cc b/src/DHTMessageDispatcherImpl.cc index c692a5fc..027fb2ae 100644 --- a/src/DHTMessageDispatcherImpl.cc +++ b/src/DHTMessageDispatcherImpl.cc @@ -56,11 +56,11 @@ DHTMessageDispatcherImpl::DHTMessageDispatcherImpl void DHTMessageDispatcherImpl::addMessageToQueue (std::unique_ptr message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback) { - messageQueue_.push_back(make_unique - (std::move(message), timeout, std::move(callback))); + messageQueue_.push_back(make_unique( + std::move(message), std::move(timeout), std::move(callback))); } void @@ -92,7 +92,7 @@ bool DHTMessageDispatcherImpl::sendMessage(DHTMessageEntry* entry) // DHTTask(such as DHTAbstractNodeLookupTask) don't finish // forever. if(!entry->message->isReply()) { - tracker_->addMessage(entry->message.get(), 0, + tracker_->addMessage(entry->message.get(), std::chrono::seconds(0), std::move(entry->callback)); } } diff --git a/src/DHTMessageDispatcherImpl.h b/src/DHTMessageDispatcherImpl.h index e2d0e72c..d03b5cb3 100644 --- a/src/DHTMessageDispatcherImpl.h +++ b/src/DHTMessageDispatcherImpl.h @@ -49,7 +49,7 @@ private: std::deque> messageQueue_; - time_t timeout_; + std::chrono::seconds timeout_; bool sendMessage(DHTMessageEntry* msg); public: @@ -57,7 +57,7 @@ public: virtual void addMessageToQueue(std::unique_ptr message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback = std::unique_ptr{}) CXX11_OVERRIDE; @@ -72,9 +72,9 @@ public: virtual size_t countMessageInQueue() const CXX11_OVERRIDE; - void setTimeout(time_t timeout) + void setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } }; diff --git a/src/DHTMessageEntry.cc b/src/DHTMessageEntry.cc index 52f5d41f..7d22786e 100644 --- a/src/DHTMessageEntry.cc +++ b/src/DHTMessageEntry.cc @@ -41,10 +41,10 @@ namespace aria2 { DHTMessageEntry::DHTMessageEntry (std::unique_ptr message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback) : message{std::move(message)}, - timeout{timeout}, + timeout{std::move(timeout)}, callback{std::move(callback)} {} diff --git a/src/DHTMessageEntry.h b/src/DHTMessageEntry.h index c2794e74..9b71b21d 100644 --- a/src/DHTMessageEntry.h +++ b/src/DHTMessageEntry.h @@ -48,11 +48,11 @@ class DHTMessageCallback; struct DHTMessageEntry { std::unique_ptr message; - time_t timeout; + std::chrono::seconds timeout; std::unique_ptr callback; DHTMessageEntry(std::unique_ptr message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback); }; diff --git a/src/DHTMessageTracker.cc b/src/DHTMessageTracker.cc index ae25ae76..96612e29 100644 --- a/src/DHTMessageTracker.cc +++ b/src/DHTMessageTracker.cc @@ -58,14 +58,14 @@ DHTMessageTracker::DHTMessageTracker() void DHTMessageTracker::addMessage (DHTMessage* message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback) { entries_.push_back(make_unique (message->getRemoteNode(), message->getTransactionID(), message->getMessageType(), - timeout, std::move(callback))); + std::move(timeout), std::move(callback))); } std::pair, @@ -93,8 +93,9 @@ DHTMessageTracker::messageArrived targetNode->getIPAddress(), targetNode->getPort()); - int64_t rtt = entry->getElapsedMillis(); - A2_LOG_DEBUG(fmt("RTT is %" PRId64 "", rtt)); + auto rtt = std::chrono::duration_cast( + entry->getElapsed()); + A2_LOG_DEBUG(fmt("RTT is %" PRId64 "", rtt.count())); message->getRemoteNode()->updateRTT(rtt); if(*targetNode != *message->getRemoteNode()) { // Node ID has changed. Drop previous node ID from @@ -124,7 +125,8 @@ void DHTMessageTracker::handleTimeoutEntry(DHTMessageTrackerEntry* entry) auto& node = entry->getTargetNode(); A2_LOG_DEBUG(fmt("Message timeout: To:%s:%u", node->getIPAddress().c_str(), node->getPort())); - node->updateRTT(entry->getElapsedMillis()); + node->updateRTT(std::chrono::duration_cast( + entry->getElapsed())); node->timeout(); if(node->isBad()) { A2_LOG_DEBUG(fmt("Marked bad: %s:%u", diff --git a/src/DHTMessageTracker.h b/src/DHTMessageTracker.h index 0cb51fac..a135fb2c 100644 --- a/src/DHTMessageTracker.h +++ b/src/DHTMessageTracker.h @@ -64,7 +64,7 @@ public: DHTMessageTracker(); void addMessage(DHTMessage* message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback = std::unique_ptr{}); diff --git a/src/DHTMessageTrackerEntry.cc b/src/DHTMessageTrackerEntry.cc index 94bee1f5..042725f8 100644 --- a/src/DHTMessageTrackerEntry.cc +++ b/src/DHTMessageTrackerEntry.cc @@ -46,14 +46,14 @@ DHTMessageTrackerEntry::DHTMessageTrackerEntry (std::shared_ptr targetNode, std::string transactionID, std::string messageType, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback) : targetNode_{std::move(targetNode)}, transactionID_{std::move(transactionID)}, messageType_{std::move(messageType)}, callback_{std::move(callback)}, dispatchedTime_{global::wallclock()}, - timeout_{timeout} + timeout_{std::move(timeout)} {} bool DHTMessageTrackerEntry::isTimeout() const @@ -80,9 +80,9 @@ bool DHTMessageTrackerEntry::match(const std::string& transactionID, const std:: return false; } -int64_t DHTMessageTrackerEntry::getElapsedMillis() const +Timer::Clock::duration DHTMessageTrackerEntry::getElapsed() const { - return dispatchedTime_.differenceInMillis(global::wallclock()); + return dispatchedTime_.difference(global::wallclock()); } const std::shared_ptr& DHTMessageTrackerEntry::getTargetNode() const diff --git a/src/DHTMessageTrackerEntry.h b/src/DHTMessageTrackerEntry.h index 42ff4e8b..9fe9dc62 100644 --- a/src/DHTMessageTrackerEntry.h +++ b/src/DHTMessageTrackerEntry.h @@ -61,12 +61,12 @@ private: Timer dispatchedTime_; - time_t timeout_; + std::chrono::seconds timeout_; public: DHTMessageTrackerEntry(std::shared_ptr targetNode, std::string transactionID, std::string messageType, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr callback = std::unique_ptr{}); @@ -80,7 +80,7 @@ public: const std::string& getMessageType() const; const std::unique_ptr& getCallback() const; std::unique_ptr popCallback(); - int64_t getElapsedMillis() const; + Timer::Clock::duration getElapsed() const; }; } // namespace aria2 diff --git a/src/DHTNode.cc b/src/DHTNode.cc index 0e64c5fc..258e878d 100644 --- a/src/DHTNode.cc +++ b/src/DHTNode.cc @@ -43,12 +43,14 @@ namespace aria2 { -DHTNode::DHTNode():port_(0), rtt_(0), condition_(0), lastContact_(0) +DHTNode::DHTNode() + : port_(0), rtt_(0), condition_(0), lastContact_(Timer::zero()) { generateID(); } -DHTNode::DHTNode(const unsigned char* id):port_(0), rtt_(0), condition_(1), lastContact_(0) +DHTNode::DHTNode(const unsigned char* id) + : port_(0), rtt_(0), condition_(1), lastContact_(Timer::zero()) { memcpy(id_, id, DHT_ID_LENGTH); } @@ -122,12 +124,12 @@ void DHTNode::timeout() std::string DHTNode::toString() const { - return fmt("DHTNode ID=%s, Host=%s(%u), Condition=%d, RTT=%d", + return fmt("DHTNode ID=%s, Host=%s(%u), Condition=%d, RTT=%ld", util::toHex(id_, DHT_ID_LENGTH).c_str(), ipaddr_.c_str(), port_, condition_, - rtt_); + rtt_.count()); } void DHTNode::setID(const unsigned char* id) diff --git a/src/DHTNode.h b/src/DHTNode.h index 1180856f..2c2b9edb 100644 --- a/src/DHTNode.h +++ b/src/DHTNode.h @@ -52,8 +52,7 @@ private: uint16_t port_; - // in milli sec - int rtt_; + std::chrono::milliseconds rtt_; int condition_; @@ -75,9 +74,9 @@ public: return id_; } - void updateRTT(int millisec) + void updateRTT(std::chrono::milliseconds t) { - rtt_ = millisec; + rtt_ = std::move(t); } const std::string& getIPAddress() const diff --git a/src/DHTPeerAnnounceCommand.cc b/src/DHTPeerAnnounceCommand.cc index 43ce6701..b8eaa1e2 100644 --- a/src/DHTPeerAnnounceCommand.cc +++ b/src/DHTPeerAnnounceCommand.cc @@ -44,8 +44,8 @@ namespace aria2 { DHTPeerAnnounceCommand::DHTPeerAnnounceCommand -(cuid_t cuid, DownloadEngine* e, time_t interval) - : TimeBasedCommand{cuid, e, interval}, +(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) + : TimeBasedCommand{cuid, e, std::move(interval)}, peerAnnounceStorage_{nullptr} {} diff --git a/src/DHTPeerAnnounceCommand.h b/src/DHTPeerAnnounceCommand.h index 8be4d7bf..48f109c9 100644 --- a/src/DHTPeerAnnounceCommand.h +++ b/src/DHTPeerAnnounceCommand.h @@ -47,7 +47,8 @@ class DHTPeerAnnounceCommand:public TimeBasedCommand { private: DHTPeerAnnounceStorage* peerAnnounceStorage_; public: - DHTPeerAnnounceCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + DHTPeerAnnounceCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~DHTPeerAnnounceCommand(); diff --git a/src/DHTPeerAnnounceEntry.cc b/src/DHTPeerAnnounceEntry.cc index d72fa2f2..e13bb5fd 100644 --- a/src/DHTPeerAnnounceEntry.cc +++ b/src/DHTPeerAnnounceEntry.cc @@ -66,28 +66,16 @@ size_t DHTPeerAnnounceEntry::countPeerAddrEntry() const return peerAddrEntries_.size(); } -namespace { -class FindStaleEntry { -private: - time_t timeout_; -public: - FindStaleEntry(time_t timeout):timeout_(timeout) {} - - bool operator()(const PeerAddrEntry& entry) const - { - if(entry.getLastUpdated().difference(global::wallclock()) >= timeout_) { - return true; - } else { - return false; - } - } -}; -} // namespace - -void DHTPeerAnnounceEntry::removeStalePeerAddrEntry(time_t timeout) +void DHTPeerAnnounceEntry::removeStalePeerAddrEntry( + const std::chrono::seconds& timeout) { - peerAddrEntries_.erase(std::remove_if(peerAddrEntries_.begin(), peerAddrEntries_.end(), - FindStaleEntry(timeout)), peerAddrEntries_.end()); + peerAddrEntries_.erase( + std::remove_if(std::begin(peerAddrEntries_), std::end(peerAddrEntries_), + [&timeout](const PeerAddrEntry& entry) { + return entry.getLastUpdated().difference(global::wallclock()) >= + timeout; + }), + std::end(peerAddrEntries_)); } bool DHTPeerAnnounceEntry::empty() const diff --git a/src/DHTPeerAnnounceEntry.h b/src/DHTPeerAnnounceEntry.h index b1d29b8c..00a45ea2 100644 --- a/src/DHTPeerAnnounceEntry.h +++ b/src/DHTPeerAnnounceEntry.h @@ -71,7 +71,7 @@ public: return peerAddrEntries_; } - void removeStalePeerAddrEntry(time_t timeout); + void removeStalePeerAddrEntry(const std::chrono::seconds& timeout); bool empty() const; diff --git a/src/DHTPeerAnnounceStorage.cc b/src/DHTPeerAnnounceStorage.cc index ac0d071b..a008a00d 100644 --- a/src/DHTPeerAnnounceStorage.cc +++ b/src/DHTPeerAnnounceStorage.cc @@ -108,24 +108,16 @@ void DHTPeerAnnounceStorage::getPeers(std::vector >& peers } } -namespace { -class RemoveStalePeerAddrEntry -{ -public: - void operator()(const std::shared_ptr& e) - { - e->removeStalePeerAddrEntry(DHT_PEER_ANNOUNCE_PURGE_INTERVAL); - } -}; -} // namespace - void DHTPeerAnnounceStorage::handleTimeout() { A2_LOG_DEBUG(fmt("Now purge peer announces(%lu entries) which are timed out.", static_cast(entries_.size()))); - std::for_each(entries_.begin(), entries_.end(), RemoveStalePeerAddrEntry()); - for(auto i = entries_.begin(), - eoi = entries_.end(); i != eoi;) { + std::for_each(std::begin(entries_), std::end(entries_), + [](const std::shared_ptr& e) { + e->removeStalePeerAddrEntry(DHT_PEER_ANNOUNCE_PURGE_INTERVAL); + }); + + for(auto i = std::begin(entries_); i != std::end(entries_); ) { if((*i)->empty()) { entries_.erase(i++); } else { @@ -140,7 +132,8 @@ void DHTPeerAnnounceStorage::announcePeer() { A2_LOG_DEBUG("Now announcing peer."); for (auto& e: entries_) { - if(e->getLastUpdated().difference(global::wallclock()) < DHT_PEER_ANNOUNCE_INTERVAL) { + if (e->getLastUpdated().difference(global::wallclock()) < + DHT_PEER_ANNOUNCE_INTERVAL) { continue; } e->notifyUpdate(); diff --git a/src/DHTPingTask.h b/src/DHTPingTask.h index 17b35940..3a4c48d5 100644 --- a/src/DHTPingTask.h +++ b/src/DHTPingTask.h @@ -52,7 +52,7 @@ private: bool pingSuccessful_; - time_t timeout_; + std::chrono::seconds timeout_; void addMessage(); public: @@ -66,9 +66,9 @@ public: void onTimeout(const std::shared_ptr& node); - void setTimeout(time_t timeout) + void setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } bool isPingSuccessful() const; diff --git a/src/DHTReplaceNodeTask.h b/src/DHTReplaceNodeTask.h index 78cb9144..f722a0ca 100644 --- a/src/DHTReplaceNodeTask.h +++ b/src/DHTReplaceNodeTask.h @@ -51,7 +51,7 @@ private: int numRetry_; - time_t timeout_; + std::chrono::seconds timeout_; void sendMessage(); public: @@ -66,9 +66,9 @@ public: void onTimeout(const std::shared_ptr& node); - void setTimeout(time_t timeout) + void setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } }; diff --git a/src/DHTSetup.cc b/src/DHTSetup.cc index 3c88d99a..d369d935 100644 --- a/src/DHTSetup.cc +++ b/src/DHTSetup.cc @@ -148,13 +148,13 @@ std::vector> DHTSetup::setup auto tokenTracker = make_unique(); // For now, UDPTrackerClient was enabled along with DHT auto udpTrackerClient = std::make_shared(); - const time_t messageTimeout = - e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT); + const auto messageTimeout = + e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT); // wiring up tracker->setRoutingTable(routingTable.get()); tracker->setMessageFactory(factory.get()); - dispatcher->setTimeout(messageTimeout); + dispatcher->setTimeout(std::chrono::seconds(messageTimeout)); receiver->setMessageFactory(factory.get()); receiver->setRoutingTable(routingTable.get()); @@ -164,7 +164,7 @@ std::vector> DHTSetup::setup taskFactory->setMessageDispatcher(dispatcher.get()); taskFactory->setMessageFactory(factory.get()); taskFactory->setTaskQueue(taskQueue.get()); - taskFactory->setTimeout(messageTimeout); + taskFactory->setTimeout(std::chrono::seconds(messageTimeout)); routingTable->setTaskQueue(taskQueue.get()); routingTable->setTaskFactory(taskFactory.get()); @@ -234,8 +234,8 @@ std::vector> DHTSetup::setup tempCommands.push_back(std::move(command)); } { - auto command = make_unique - (e->newCUID(), e, family, 30*60); + auto command = make_unique(e->newCUID(), e, family, + std::chrono::minutes(30)); command->setLocalNode(localNode); command->setRoutingTable(routingTable.get()); tempCommands.push_back(std::move(command)); diff --git a/src/DHTTaskFactoryImpl.cc b/src/DHTTaskFactoryImpl.cc index e40186f2..f3691ce6 100644 --- a/src/DHTTaskFactoryImpl.cc +++ b/src/DHTTaskFactoryImpl.cc @@ -64,7 +64,7 @@ std::shared_ptr DHTTaskFactoryImpl::createPingTask(const std::shared_ptr& remoteNode, int numRetry) { - std::shared_ptr task(new DHTPingTask(remoteNode, numRetry)); + auto task = std::make_shared(remoteNode, numRetry); task->setTimeout(timeout_); setCommonProperty(task); return task; diff --git a/src/DHTTaskFactoryImpl.h b/src/DHTTaskFactoryImpl.h index 53ff57e1..38ae6174 100644 --- a/src/DHTTaskFactoryImpl.h +++ b/src/DHTTaskFactoryImpl.h @@ -59,7 +59,7 @@ private: DHTTaskQueue* taskQueue_; - time_t timeout_; + std::chrono::seconds timeout_; void setCommonProperty(const std::shared_ptr& task); public: @@ -100,9 +100,9 @@ public: void setLocalNode(const std::shared_ptr& localNode); - void setTimeout(time_t timeout) + void setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } }; diff --git a/src/DHTTokenUpdateCommand.cc b/src/DHTTokenUpdateCommand.cc index d2074223..c9890fae 100644 --- a/src/DHTTokenUpdateCommand.cc +++ b/src/DHTTokenUpdateCommand.cc @@ -44,8 +44,8 @@ namespace aria2 { DHTTokenUpdateCommand::DHTTokenUpdateCommand -(cuid_t cuid, DownloadEngine* e, time_t interval) - : TimeBasedCommand{cuid, e, interval}, +(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) + : TimeBasedCommand{cuid, e, std::move(interval)}, tokenTracker_{nullptr} {} diff --git a/src/DHTTokenUpdateCommand.h b/src/DHTTokenUpdateCommand.h index b273db3e..369c75b0 100644 --- a/src/DHTTokenUpdateCommand.h +++ b/src/DHTTokenUpdateCommand.h @@ -47,7 +47,8 @@ class DHTTokenUpdateCommand:public TimeBasedCommand { private: DHTTokenTracker* tokenTracker_; public: - DHTTokenUpdateCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + DHTTokenUpdateCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~DHTTokenUpdateCommand(); diff --git a/src/DefaultBtAnnounce.cc b/src/DefaultBtAnnounce.cc index f7d491cf..34042525 100644 --- a/src/DefaultBtAnnounce.cc +++ b/src/DefaultBtAnnounce.cc @@ -61,10 +61,10 @@ DefaultBtAnnounce::DefaultBtAnnounce (DownloadContext* downloadContext, const Option* option) : downloadContext_{downloadContext}, trackers_(0), - prevAnnounceTimer_(0), + prevAnnounceTimer_(Timer::zero()), interval_(DEFAULT_ANNOUNCE_INTERVAL), minInterval_(DEFAULT_ANNOUNCE_INTERVAL), - userDefinedInterval_(0), + userDefinedInterval_(std::chrono::seconds(0)), complete_(0), incomplete_(0), announceList_(bittorrent::getTorrentAttrs(downloadContext)->announceList), @@ -77,12 +77,11 @@ DefaultBtAnnounce::~DefaultBtAnnounce() { } bool DefaultBtAnnounce::isDefaultAnnounceReady() { - return - (trackers_ == 0 && - prevAnnounceTimer_. - difference(global::wallclock()) >= (userDefinedInterval_==0? - minInterval_:userDefinedInterval_) && - !announceList_.allTiersFailed()); + return (trackers_ == 0 && + prevAnnounceTimer_.difference(global::wallclock()) >= + (userDefinedInterval_.count() == 0 ? minInterval_ + : userDefinedInterval_) && + !announceList_.allTiersFailed()); } bool DefaultBtAnnounce::isStoppedAnnounceReady() { @@ -305,13 +304,14 @@ DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse, } const Integer* ival = downcast(dict->get(BtAnnounce::INTERVAL)); if(ival && ival->i() > 0) { - interval_ = ival->i(); - A2_LOG_DEBUG(fmt("Interval:%ld", static_cast(interval_))); + interval_ = std::chrono::seconds(ival->i()); + A2_LOG_DEBUG(fmt("Interval:%ld", static_cast(interval_.count()))); } const Integer* mival = downcast(dict->get(BtAnnounce::MIN_INTERVAL)); if(mival && mival->i() > 0) { - minInterval_ = mival->i(); - A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast(minInterval_))); + minInterval_ = std::chrono::seconds(mival->i()); + A2_LOG_DEBUG( + fmt("Min interval:%ld", static_cast(minInterval_.count()))); minInterval_ = std::min(minInterval_, interval_); } else { // Use interval as a minInterval if minInterval is not supplied. @@ -355,8 +355,9 @@ void DefaultBtAnnounce::processUDPTrackerResponse const std::shared_ptr& reply = req->reply; A2_LOG_DEBUG("Now processing UDP tracker response."); if(reply->interval > 0) { - minInterval_ = reply->interval; - A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast(minInterval_))); + minInterval_ = std::chrono::seconds(reply->interval); + A2_LOG_DEBUG( + fmt("Min interval:%ld", static_cast(minInterval_.count()))); interval_ = minInterval_; } complete_ = reply->seeders; @@ -401,9 +402,9 @@ void DefaultBtAnnounce::setPeerStorage peerStorage_ = peerStorage; } -void DefaultBtAnnounce::overrideMinInterval(time_t interval) +void DefaultBtAnnounce::overrideMinInterval(std::chrono::seconds interval) { - minInterval_ = interval; + minInterval_ = std::move(interval); } } // namespace aria2 diff --git a/src/DefaultBtAnnounce.h b/src/DefaultBtAnnounce.h index 067b365e..054948e8 100644 --- a/src/DefaultBtAnnounce.h +++ b/src/DefaultBtAnnounce.h @@ -53,9 +53,9 @@ private: DownloadContext* downloadContext_; int trackers_; Timer prevAnnounceTimer_; - time_t interval_; - time_t minInterval_; - time_t userDefinedInterval_; + std::chrono::seconds interval_; + std::chrono::seconds minInterval_; + std::chrono::seconds userDefinedInterval_; int complete_; int incomplete_; AnnounceList announceList_; @@ -129,7 +129,8 @@ public: virtual void shuffleAnnounce() CXX11_OVERRIDE; - virtual void overrideMinInterval(time_t interval) CXX11_OVERRIDE; + virtual void + overrideMinInterval(std::chrono::seconds interval) CXX11_OVERRIDE; virtual void setTcpPort(uint16_t port) CXX11_OVERRIDE { @@ -138,12 +139,12 @@ public: void setRandomizer(Randomizer* randomizer); - time_t getInterval() const + const std::chrono::seconds& getInterval() const { return interval_; } - time_t getMinInterval() const + const std::chrono::seconds& getMinInterval() const { return minInterval_; } @@ -163,9 +164,9 @@ public: return trackerId_; } - void setUserDefinedInterval(time_t interval) + void setUserDefinedInterval(std::chrono::seconds interval) { - userDefinedInterval_ = interval; + userDefinedInterval_ = std::move(interval); } }; diff --git a/src/DefaultBtInteractive.cc b/src/DefaultBtInteractive.cc index a65f57f9..24dbbd78 100644 --- a/src/DefaultBtInteractive.cc +++ b/src/DefaultBtInteractive.cc @@ -172,10 +172,10 @@ DefaultBtInteractive::receiveAndSendHandshake() void DefaultBtInteractive::doPostHandshakeProcessing() { // Set time 0 to haveTimer to cache http/ftp download piece completion - haveTimer_.reset(0); + haveTimer_ = Timer::zero(); keepAliveTimer_ = global::wallclock(); floodingTimer_ = global::wallclock(); - pexTimer_.reset(0); + pexTimer_ = Timer::zero(); if(peer_->isExtendedMessagingEnabled()) { addHandshakeExtendedMessageToQueue(); } @@ -254,9 +254,12 @@ void DefaultBtInteractive::decideChoking() { } } +namespace { +constexpr auto MAX_HAVE_DELAY_SEC = std::chrono::seconds(10); +} // namespace + void DefaultBtInteractive::checkHave() { const size_t MIN_HAVE_PACK_SIZE = 20; - const time_t MAX_HAVE_DELAY_SEC = 10; pieceStorage_->getAdvertisedPieceIndexes(haveIndexes_, cuid_, haveTimer_); haveTimer_ = global::wallclock(); if(haveIndexes_.size() >= MIN_HAVE_PACK_SIZE) { @@ -430,6 +433,10 @@ void DefaultBtInteractive::sendPendingMessage() { dispatcher_->sendMessages(); } +namespace { +constexpr auto FLOODING_CHECK_INTERVAL = std::chrono::seconds(5); +} // namespace + void DefaultBtInteractive::detectMessageFlooding() { if(floodingTimer_. difference(global::wallclock()) >= FLOODING_CHECK_INTERVAL) { @@ -445,13 +452,13 @@ void DefaultBtInteractive::detectMessageFlooding() { void DefaultBtInteractive::checkActiveInteraction() { - time_t inactiveTime = inactiveTimer_.difference(global::wallclock()); + auto inactiveTime = inactiveTimer_.difference(global::wallclock()); // To allow aria2 to accept mutially interested peer, disconnect uninterested // peer. { const time_t interval = 30; if(!peer_->amInterested() && !peer_->peerInterested() && - inactiveTime >= interval) { + inactiveTime >= std::chrono::seconds(interval)) { peer_->setDisconnectedGracefully(true); // TODO change the message throw DL_ABORT_EX @@ -465,7 +472,7 @@ void DefaultBtInteractive::checkActiveInteraction() // are disconnected in a certain time period. { const time_t interval = 60; - if(inactiveTime >= interval) { + if(inactiveTime >= std::chrono::seconds(interval)) { peer_->setDisconnectedGracefully(true); throw DL_ABORT_EX (fmt(EX_DROP_INACTIVE_CONNECTION, @@ -522,7 +529,8 @@ void DefaultBtInteractive::doInteractionProcessing() { dispatcher_->addMessageToQueue(std::move(i)); } } - if(perSecTimer_.difference(global::wallclock()) >= 1) { + if(perSecTimer_.difference(global::wallclock()) >= + std::chrono::seconds(1)) { perSecTimer_ = global::wallclock(); // Drop timeout request after queuing message to give a chance // to other connection to request piece. @@ -540,7 +548,8 @@ void DefaultBtInteractive::doInteractionProcessing() { checkActiveInteraction(); decideChoking(); detectMessageFlooding(); - if(perSecTimer_.difference(global::wallclock()) >= 1) { + if(perSecTimer_.difference(global::wallclock()) >= + std::chrono::seconds(1)) { perSecTimer_ = global::wallclock(); dispatcher_->checkRequestSlotAndDoNecessaryThing(); } diff --git a/src/DefaultBtInteractive.h b/src/DefaultBtInteractive.h index 3cabf13c..74af41b6 100644 --- a/src/DefaultBtInteractive.h +++ b/src/DefaultBtInteractive.h @@ -132,7 +132,7 @@ private: Timer inactiveTimer_; Timer pexTimer_; Timer perSecTimer_; - time_t keepAliveInterval_; + std::chrono::seconds keepAliveInterval_; bool utPexEnabled_; bool dhtEnabled_; @@ -147,8 +147,6 @@ private: std::vector haveIndexes_; Timer haveLastSent_; - static const time_t FLOODING_CHECK_INTERVAL = 5; - void addBitfieldMessageToQueue(); void addAllowedFastMessageToQueue(); void addHandshakeExtendedMessageToQueue(); @@ -224,8 +222,8 @@ public: void setExtensionMessageRegistry (std::unique_ptr registry); - void setKeepAliveInterval(time_t keepAliveInterval) { - keepAliveInterval_ = keepAliveInterval; + void setKeepAliveInterval(std::chrono::seconds keepAliveInterval) { + keepAliveInterval_ = std::move(keepAliveInterval); } void setUTPexEnabled(bool f) diff --git a/src/DefaultBtMessageDispatcher.h b/src/DefaultBtMessageDispatcher.h index a67c28ab..00a14072 100644 --- a/src/DefaultBtMessageDispatcher.h +++ b/src/DefaultBtMessageDispatcher.h @@ -62,7 +62,7 @@ private: BtMessageFactory* messageFactory_; std::shared_ptr peer_; RequestGroupMan* requestGroupMan_; - time_t requestTimeout_; + std::chrono::seconds requestTimeout_; public: DefaultBtMessageDispatcher(); @@ -140,9 +140,9 @@ public: cuid_ = cuid; } - void setRequestTimeout(time_t requestTimeout) + void setRequestTimeout(std::chrono::seconds requestTimeout) { - requestTimeout_ = requestTimeout; + requestTimeout_ = std::move(requestTimeout); } void setPeerConnection(PeerConnection* peerConnection) diff --git a/src/DefaultPeerStorage.cc b/src/DefaultPeerStorage.cc index 2a424d96..f320994b 100644 --- a/src/DefaultPeerStorage.cc +++ b/src/DefaultPeerStorage.cc @@ -62,7 +62,7 @@ DefaultPeerStorage::DefaultPeerStorage() : maxPeerListSize_(MAX_PEER_LIST_SIZE), seederStateChoke_(make_unique()), leecherStateChoke_(make_unique()), - lastTransferStatMapUpdated_(0) + lastTransferStatMapUpdated_(Timer::zero()) {} DefaultPeerStorage::~DefaultPeerStorage() @@ -183,11 +183,11 @@ bool DefaultPeerStorage::isPeerAvailable() { bool DefaultPeerStorage::isBadPeer(const std::string& ipaddr) { auto i = badPeers_.find(ipaddr); - if(i == badPeers_.end()) { + if(i == std::end(badPeers_)) { return false; } - if(global::wallclock().getTime() >= (*i).second) { + if((*i).second <= global::wallclock()) { badPeers_.erase(i); return false; } @@ -197,10 +197,10 @@ bool DefaultPeerStorage::isBadPeer(const std::string& ipaddr) void DefaultPeerStorage::addBadPeer(const std::string& ipaddr) { - if(lastBadPeerCleaned_.difference(global::wallclock()) >= 3600) { - for(auto i = badPeers_.begin(), - eoi = badPeers_.end(); i != eoi;) { - if(global::wallclock().getTime() >= (*i).second) { + if(lastBadPeerCleaned_.difference(global::wallclock()) >= + std::chrono::hours(1)) { + for(auto i = std::begin(badPeers_); i != std::end(badPeers_);) { + if((*i).second <= global::wallclock()) { A2_LOG_DEBUG(fmt("Purge %s from bad peer", (*i).first.c_str())); badPeers_.erase(i++); // badPeers_.end() will not be invalidated. @@ -212,8 +212,11 @@ void DefaultPeerStorage::addBadPeer(const std::string& ipaddr) } A2_LOG_DEBUG(fmt("Added %s as bad peer", ipaddr.c_str())); // We use variable timeout to avoid many bad peers wake up at once. - badPeers_[ipaddr] = global::wallclock().getTime()+ - std::max(SimpleRandomizer::getInstance()->getRandomNumber(601), 120L); + auto t = global::wallclock(); + t.advance(std::chrono::seconds( + std::max(SimpleRandomizer::getInstance()->getRandomNumber(601), 120L))); + + badPeers_[ipaddr] = std::move(t); } void DefaultPeerStorage::deleteUnusedPeer(size_t delSize) { @@ -281,7 +284,7 @@ void DefaultPeerStorage::returnPeer(const std::shared_ptr& peer) bool DefaultPeerStorage::chokeRoundIntervalElapsed() { - const time_t CHOKE_ROUND_INTERVAL = 10; + constexpr auto CHOKE_ROUND_INTERVAL = std::chrono::seconds(10); if(pieceStorage_->downloadFinished()) { return seederStateChoke_->getLastRound(). difference(global::wallclock()) >= CHOKE_ROUND_INTERVAL; diff --git a/src/DefaultPeerStorage.h b/src/DefaultPeerStorage.h index c49e4d9c..0b10c635 100644 --- a/src/DefaultPeerStorage.h +++ b/src/DefaultPeerStorage.h @@ -71,7 +71,7 @@ private: Timer lastTransferStatMapUpdated_; - std::map badPeers_; + std::map badPeers_; Timer lastBadPeerCleaned_; bool isPeerAlreadyAdded(const std::shared_ptr& peer); diff --git a/src/DefaultPieceStorage.cc b/src/DefaultPieceStorage.cc index 713e8365..c8932810 100644 --- a/src/DefaultPieceStorage.cc +++ b/src/DefaultPieceStorage.cc @@ -725,32 +725,18 @@ DefaultPieceStorage::getAdvertisedPieceIndexes(std::vector& indexes, } } -namespace { -class FindElapsedHave +void +DefaultPieceStorage::removeAdvertisedPiece(const std::chrono::seconds& elapsed) { -private: - time_t elapsed; -public: - FindElapsedHave(time_t elapsed):elapsed(elapsed) {} + auto itr = std::find_if(std::begin(haves_), std::end(haves_), + [&elapsed](const HaveEntry& have) { + return have.getRegisteredTime().difference(global::wallclock()) >= elapsed; + }); - bool operator()(const HaveEntry& have) { - if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) { - return true; - } else { - return false; - } - } -}; -} // namespace - -void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed) -{ - auto itr = std::find_if(haves_.begin(), haves_.end(), - FindElapsedHave(elapsed)); - if(itr != haves_.end()) { + if(itr != std::end(haves_)) { A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY, - static_cast(haves_.end()-itr))); - haves_.erase(itr, haves_.end()); + static_cast(std::end(haves_) - itr))); + haves_.erase(itr, std::end(haves_)); } } diff --git a/src/DefaultPieceStorage.h b/src/DefaultPieceStorage.h index 82c74ceb..00b6b08e 100644 --- a/src/DefaultPieceStorage.h +++ b/src/DefaultPieceStorage.h @@ -262,7 +262,8 @@ public: cuid_t myCuid, const Timer& lastCheckTime) CXX11_OVERRIDE; - virtual void removeAdvertisedPiece(time_t elapsed) CXX11_OVERRIDE; + virtual void + removeAdvertisedPiece(const std::chrono::seconds& elapsed) CXX11_OVERRIDE; virtual void markAllPiecesDone() CXX11_OVERRIDE; diff --git a/src/DelayedCommand.h b/src/DelayedCommand.h index b02bffa0..809b8058 100644 --- a/src/DelayedCommand.h +++ b/src/DelayedCommand.h @@ -59,9 +59,9 @@ public: } public: - DelayedCommand(cuid_t cuid, DownloadEngine* e, time_t delay, + DelayedCommand(cuid_t cuid, DownloadEngine* e, std::chrono::seconds delay, std::unique_ptr command, bool noWait) - : TimeBasedCommand(cuid, e, delay), + : TimeBasedCommand(cuid, e, std::move(delay)), command_{std::move(command)}, noWait_{noWait} { diff --git a/src/DownloadCommand.cc b/src/DownloadCommand.cc index 20337611..c921da9e 100644 --- a/src/DownloadCommand.cc +++ b/src/DownloadCommand.cc @@ -328,7 +328,7 @@ bool DownloadCommand::prepareForNextSegment() { // Following 2lines are needed for DownloadEngine to detect // completed RequestGroups without 1sec delay. getDownloadEngine()->setNoWait(true); - getDownloadEngine()->setRefreshInterval(0); + getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0)); return true; } else { // The number of segments should be 1 in order to pass through the next diff --git a/src/DownloadCommand.h b/src/DownloadCommand.h index 485cdc74..2d2663be 100644 --- a/src/DownloadCommand.h +++ b/src/DownloadCommand.h @@ -53,7 +53,7 @@ private: std::unique_ptr messageDigest_; - time_t startupIdleTime_; + std::chrono::seconds startupIdleTime_; int lowestDownloadSpeedLimit_; @@ -99,9 +99,9 @@ public: void installStreamFilter(std::unique_ptr streamFilter); - void setStartupIdleTime(time_t startupIdleTime) + void setStartupIdleTime(std::chrono::seconds startupIdleTime) { - startupIdleTime_ = startupIdleTime; + startupIdleTime_ = std::move(startupIdleTime); } void setLowestDownloadSpeedLimit(int lowestDownloadSpeedLimit) diff --git a/src/DownloadContext.cc b/src/DownloadContext.cc index 60b71d5e..a49a8cf3 100644 --- a/src/DownloadContext.cc +++ b/src/DownloadContext.cc @@ -50,7 +50,7 @@ namespace aria2 { DownloadContext::DownloadContext() : ownerRequestGroup_(nullptr), attrs_(MAX_CTX_ATTR), - downloadStopTime_(0), + downloadStopTime_(Timer::zero()), pieceLength_(0), checksumVerified_(false), knowsTotalLength_(true), @@ -62,7 +62,7 @@ DownloadContext::DownloadContext(int32_t pieceLength, std::string path) : ownerRequestGroup_(nullptr), attrs_(MAX_CTX_ATTR), - downloadStopTime_(0), + downloadStopTime_(Timer::zero()), pieceLength_(pieceLength), checksumVerified_(false), knowsTotalLength_(true), @@ -76,7 +76,7 @@ DownloadContext::~DownloadContext() {} void DownloadContext::resetDownloadStartTime() { - downloadStopTime_.reset(0); + downloadStopTime_ = Timer::zero(); netStat_.downloadStart(); } @@ -86,10 +86,10 @@ void DownloadContext::resetDownloadStopTime() netStat_.downloadStop(); } -int64_t DownloadContext::calculateSessionTime() const +Timer::Clock::duration DownloadContext::calculateSessionTime() const { const Timer& startTime = netStat_.getDownloadStartTime(); - return startTime.differenceInMillis(downloadStopTime_); + return startTime.difference(downloadStopTime_); } std::shared_ptr diff --git a/src/DownloadContext.h b/src/DownloadContext.h index 4b594c9c..5f8e36d7 100644 --- a/src/DownloadContext.h +++ b/src/DownloadContext.h @@ -222,7 +222,7 @@ public: return downloadStopTime_; } - int64_t calculateSessionTime() const; + Timer::Clock::duration calculateSessionTime() const; // Returns FileEntry at given offset. std::shared_ptr() is // returned if no such FileEntry is found. diff --git a/src/DownloadEngine.cc b/src/DownloadEngine.cc index cfc0848d..377befe2 100644 --- a/src/DownloadEngine.cc +++ b/src/DownloadEngine.cc @@ -90,12 +90,16 @@ volatile sig_atomic_t globalHaltRequested = 0; } // namespace global +namespace { +constexpr auto DEFAULT_REFRESH_INTERVAL = std::chrono::seconds(1); +} // namespace + DownloadEngine::DownloadEngine(std::unique_ptr eventPoll) : eventPoll_(std::move(eventPoll)), haltRequested_(0), noWait_(true), refreshInterval_(DEFAULT_REFRESH_INTERVAL), - lastRefresh_(0), + lastRefresh_(Timer::zero()), cookieStorage_(make_unique()), #ifdef ENABLE_BITTORRENT btRegistry_(make_unique()), @@ -164,7 +168,7 @@ int DownloadEngine::run(bool oneshot) noWait_ = false; global::wallclock().reset(); calculateStatistics(); - if(lastRefresh_.differenceInMillis(global::wallclock())+A2_DELTA_MILLIS >= + if(lastRefresh_.difference(global::wallclock())+A2_DELTA_MILLIS >= refreshInterval_) { refreshInterval_ = DEFAULT_REFRESH_INTERVAL; lastRefresh_ = global::wallclock(); @@ -188,9 +192,10 @@ void DownloadEngine::waitData() if(noWait_) { tv.tv_sec = tv.tv_usec = 0; } else { - lldiv_t qr = lldiv(refreshInterval_*1000, 1000000); - tv.tv_sec = qr.quot; - tv.tv_usec = qr.rem; + auto t = + std::chrono::duration_cast(refreshInterval_); + tv.tv_sec = t.count() / 1000000; + tv.tv_usec = t.count() % 1000000; } eventPoll_->poll(tv); } @@ -245,7 +250,7 @@ void DownloadEngine::afterEachIteration() requestHalt(); global::globalHaltRequested = 2; setNoWait(true); - setRefreshInterval(0); + setRefreshInterval(std::chrono::milliseconds(0)); return; } @@ -254,7 +259,7 @@ void DownloadEngine::afterEachIteration() requestForceHalt(); global::globalHaltRequested = 4; setNoWait(true); - setRefreshInterval(0); + setRefreshInterval(std::chrono::milliseconds(0)); return; } } @@ -307,7 +312,8 @@ void DownloadEngine::poolSocket(const std::string& key, std::multimap::value_type p(key, entry); socketPool_.insert(p); - if(lastSocketPoolScan_.difference(global::wallclock()) < 60) { + if(lastSocketPoolScan_.difference(global::wallclock()) < + std::chrono::minutes(1)) { return; } std::multimap newPool; @@ -351,9 +357,9 @@ void DownloadEngine::poolSocket uint16_t proxyport, const std::shared_ptr& sock, const std::string& options, - time_t timeout) + std::chrono::seconds timeout) { - SocketPoolEntry e(sock, options, timeout); + SocketPoolEntry e(sock, options, std::move(timeout)); poolSocket(createSockPoolKey(ipaddr, port, username, proxyhost, proxyport),e); } @@ -363,9 +369,9 @@ void DownloadEngine::poolSocket const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr& sock, - time_t timeout) + std::chrono::seconds timeout) { - SocketPoolEntry e(sock, timeout); + SocketPoolEntry e(sock, std::move(timeout)); poolSocket(createSockPoolKey(ipaddr, port, A2STR::NIL,proxyhost,proxyport),e); } @@ -388,20 +394,20 @@ bool getPeerInfo(std::pair& res, void DownloadEngine::poolSocket(const std::shared_ptr& request, const std::shared_ptr& proxyRequest, const std::shared_ptr& socket, - time_t timeout) + std::chrono::seconds timeout) { if(proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), proxyRequest->getHost(), proxyRequest->getPort(), - socket, timeout); + socket, std::move(timeout)); return; } std::pair peerInfo; if(getPeerInfo(peerInfo, socket)) { poolSocket(peerInfo.first, peerInfo.second, - A2STR::NIL, 0, socket, timeout); + A2STR::NIL, 0, socket, std::move(timeout)); } } @@ -411,20 +417,20 @@ void DownloadEngine::poolSocket const std::shared_ptr& proxyRequest, const std::shared_ptr& socket, const std::string& options, - time_t timeout) + std::chrono::seconds timeout) { if(proxyRequest) { // If proxy is defined, then pool socket with its hostname. poolSocket(request->getHost(), request->getPort(), username, proxyRequest->getHost(), proxyRequest->getPort(), - socket, options, timeout); + socket, options, std::move(timeout)); return; } std::pair peerInfo; if(getPeerInfo(peerInfo, socket)) { poolSocket(peerInfo.first, peerInfo.second, username, - A2STR::NIL, 0, socket, options, timeout); + A2STR::NIL, 0, socket, options, std::move(timeout)); } } @@ -512,16 +518,16 @@ DownloadEngine::popPooledSocket DownloadEngine::SocketPoolEntry::SocketPoolEntry (const std::shared_ptr& socket, const std::string& options, - time_t timeout) + std::chrono::seconds timeout) : socket_(socket), options_(options), - timeout_(timeout) + timeout_(std::move(timeout)) {} DownloadEngine::SocketPoolEntry::SocketPoolEntry -(const std::shared_ptr& socket, time_t timeout) +(const std::shared_ptr& socket, std::chrono::seconds timeout) : socket_(socket), - timeout_(timeout) + timeout_(std::move(timeout)) {} DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {} @@ -577,9 +583,9 @@ const std::unique_ptr& DownloadEngine::getCookieStorage() const return cookieStorage_; } -void DownloadEngine::setRefreshInterval(int64_t interval) +void DownloadEngine::setRefreshInterval(std::chrono::milliseconds interval) { - refreshInterval_ = std::min(static_cast(999), interval); + refreshInterval_ = std::move(interval); } void DownloadEngine::addCommand diff --git a/src/DownloadEngine.h b/src/DownloadEngine.h index 7ccf61de..f6febb29 100644 --- a/src/DownloadEngine.h +++ b/src/DownloadEngine.h @@ -99,16 +99,16 @@ private: // protocol specific option string std::string options_; - time_t timeout_; + std::chrono::seconds timeout_; Timer registeredTime_; public: SocketPoolEntry(const std::shared_ptr& socket, const std::string& option, - time_t timeout); + std::chrono::seconds timeout); SocketPoolEntry(const std::shared_ptr& socket, - time_t timeout); + std::chrono::seconds timeout); ~SocketPoolEntry(); @@ -132,10 +132,7 @@ private: bool noWait_; - static const int64_t DEFAULT_REFRESH_INTERVAL = 1000; - - // Milliseconds - int64_t refreshInterval_; + std::chrono::milliseconds refreshInterval_; Timer lastRefresh_; std::unique_ptr cookieStorage_; @@ -272,24 +269,24 @@ public: const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr& sock, const std::string& options, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); void poolSocket(const std::shared_ptr& request, const std::string& username, const std::shared_ptr& proxyRequest, const std::shared_ptr& socket, const std::string& options, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); void poolSocket(const std::string& ipaddr, uint16_t port, const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr& sock, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); void poolSocket(const std::shared_ptr& request, const std::shared_ptr& proxyRequest, const std::shared_ptr& socket, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); std::shared_ptr popPooledSocket (const std::string& ipaddr, @@ -347,7 +344,7 @@ public: const std::unique_ptr& getAuthConfigFactory() const; - void setRefreshInterval(int64_t interval); + void setRefreshInterval(std::chrono::milliseconds interval); const std::string getSessionId() const { diff --git a/src/DownloadEngineFactory.cc b/src/DownloadEngineFactory.cc index fa350589..fe87507c 100644 --- a/src/DownloadEngineFactory.cc +++ b/src/DownloadEngineFactory.cc @@ -166,22 +166,22 @@ DownloadEngineFactory::newDownloadEngine e.get())); if(op->getAsInt(PREF_AUTO_SAVE_INTERVAL) > 0) { - e->addRoutineCommand - (make_unique(e->newCUID(), e.get(), - op->getAsInt(PREF_AUTO_SAVE_INTERVAL))); + e->addRoutineCommand(make_unique( + e->newCUID(), e.get(), + std::chrono::seconds(op->getAsInt(PREF_AUTO_SAVE_INTERVAL)))); } if(op->getAsInt(PREF_SAVE_SESSION_INTERVAL) > 0) { - e->addRoutineCommand(make_unique - (e->newCUID(), e.get(), - op->getAsInt(PREF_SAVE_SESSION_INTERVAL))); + e->addRoutineCommand(make_unique( + e->newCUID(), e.get(), + std::chrono::seconds(op->getAsInt(PREF_SAVE_SESSION_INTERVAL)))); } e->addRoutineCommand(make_unique - (e->newCUID(), e.get(), 10)); + (e->newCUID(), e.get(), std::chrono::seconds(10))); { - time_t stopSec = op->getAsInt(PREF_STOP); + auto stopSec = op->getAsInt(PREF_STOP); if(stopSec > 0) { - e->addRoutineCommand(make_unique(e->newCUID(), e.get(), - stopSec)); + e->addRoutineCommand(make_unique( + e->newCUID(), e.get(), std::chrono::seconds(stopSec))); } } if(op->defined(PREF_STOP_WITH_PROCESS)) { diff --git a/src/DownloadResult.h b/src/DownloadResult.h index 949c7c84..37fc3919 100644 --- a/src/DownloadResult.h +++ b/src/DownloadResult.h @@ -60,8 +60,7 @@ struct DownloadResult uint64_t sessionDownloadLength; - // milliseconds - int64_t sessionTime; + std::chrono::milliseconds sessionTime; int64_t totalLength; diff --git a/src/FileAllocationCommand.cc b/src/FileAllocationCommand.cc index a36f44cf..d15b3389 100644 --- a/src/FileAllocationCommand.cc +++ b/src/FileAllocationCommand.cc @@ -71,10 +71,11 @@ bool FileAllocationCommand::executeInternal() } fileAllocationEntry_->allocateChunk(); if(fileAllocationEntry_->finished()) { - A2_LOG_DEBUG - (fmt(MSG_ALLOCATION_COMPLETED, - static_cast(timer_.difference(global::wallclock())), - getRequestGroup()->getTotalLength())); + A2_LOG_DEBUG(fmt(MSG_ALLOCATION_COMPLETED, + static_cast( + std::chrono::duration_cast( + timer_.difference(global::wallclock())).count()), + getRequestGroup()->getTotalLength())); std::vector> commands; fileAllocationEntry_->prepareForNextAction(commands, getDownloadEngine()); getDownloadEngine()->addCommand(std::move(commands)); diff --git a/src/FileEntry.cc b/src/FileEntry.cc index bcf75f26..2ab1291c 100644 --- a/src/FileEntry.cc +++ b/src/FileEntry.cc @@ -72,7 +72,7 @@ FileEntry::FileEntry(std::string path, int64_t length, int64_t offset, offset_(offset), uris_(uris.begin(), uris.end()), path_(std::move(path)), - lastFasterReplace_(0), + lastFasterReplace_(Timer::zero()), maxConnectionPerServer_(1), requested_(true), uniqueProtocol_(false) @@ -213,10 +213,13 @@ FileEntry::getRequest return req; } +namespace { +constexpr auto startupIdleTime = std::chrono::seconds(10); +} // namespace + std::shared_ptr FileEntry::findFasterRequest(const std::shared_ptr& base) { - const int startupIdleTime = 10; if(requestPool_.empty() || lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) { return nullptr; @@ -248,7 +251,6 @@ FileEntry::findFasterRequest const std::vector >& usedHosts, const std::shared_ptr& serverStatMan) { - const int startupIdleTime = 10; const int SPEED_THRESHOLD = 20*1024; if(lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) { return nullptr; diff --git a/src/FtpNegotiationCommand.cc b/src/FtpNegotiationCommand.cc index afa3954e..c58ca388 100644 --- a/src/FtpNegotiationCommand.cc +++ b/src/FtpNegotiationCommand.cc @@ -99,7 +99,8 @@ FtpNegotiationCommand::FtpNegotiationCommand { ftp_->setBaseWorkingDir(baseWorkingDir); if(seq == SEQ_RECV_GREETING) { - setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); + setTimeout( + std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); } setWriteCheckSocket(getSocket()); } @@ -116,7 +117,8 @@ bool FtpNegotiationCommand::executeInternal() { auto command = make_unique (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), ftp_, getDownloadEngine(), dataSocket_, getSocket()); - command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)); + command->setStartupIdleTime( + std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME))); command->setLowestDownloadSpeedLimit (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT)); if(getFileEntry()->isUniqueProtocol()) { diff --git a/src/HaveEraseCommand.cc b/src/HaveEraseCommand.cc index 77727861..ceca170e 100644 --- a/src/HaveEraseCommand.cc +++ b/src/HaveEraseCommand.cc @@ -40,8 +40,11 @@ namespace aria2 { -HaveEraseCommand::HaveEraseCommand(cuid_t cuid, DownloadEngine* e, time_t interval) - :TimeBasedCommand(cuid, e, interval, true) {} +HaveEraseCommand::HaveEraseCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval) + : TimeBasedCommand(cuid, e, std::move(interval), true) +{ +} HaveEraseCommand::~HaveEraseCommand() {} @@ -60,7 +63,7 @@ void HaveEraseCommand::process() for(auto & group : groups) { const auto& ps = group->getPieceStorage(); if(ps) { - ps->removeAdvertisedPiece(5); + ps->removeAdvertisedPiece(std::chrono::seconds(5)); } } } diff --git a/src/HaveEraseCommand.h b/src/HaveEraseCommand.h index 0c7c5699..7d38b00a 100644 --- a/src/HaveEraseCommand.h +++ b/src/HaveEraseCommand.h @@ -42,7 +42,8 @@ namespace aria2 { class HaveEraseCommand : public TimeBasedCommand { public: - HaveEraseCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + HaveEraseCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~HaveEraseCommand(); diff --git a/src/HttpRequestCommand.cc b/src/HttpRequestCommand.cc index 1b3f4072..7dec1acb 100644 --- a/src/HttpRequestCommand.cc +++ b/src/HttpRequestCommand.cc @@ -74,7 +74,7 @@ HttpRequestCommand::HttpRequestCommand httpConnection->getSocketRecvBuffer()), httpConnection_(httpConnection) { - setTimeout(getOption()->getAsInt(PREF_CONNECT_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_CONNECT_TIMEOUT))); disableReadCheckSocket(); setWriteCheckSocket(getSocket()); } diff --git a/src/HttpResponseCommand.cc b/src/HttpResponseCommand.cc index c23d0cda..b259cbeb 100644 --- a/src/HttpResponseCommand.cc +++ b/src/HttpResponseCommand.cc @@ -536,7 +536,8 @@ HttpResponseCommand::createHttpDownloadCommand (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), std::move(httpResponse), httpConnection_, getDownloadEngine(), getSocket()); - command->setStartupIdleTime(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)); + command->setStartupIdleTime( + std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME))); command->setLowestDownloadSpeedLimit (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT)); if (getRequestGroup()->isFileAllocationEnabled() && diff --git a/src/HttpServerBodyCommand.cc b/src/HttpServerBodyCommand.cc index 8f5cac16..7fb715c2 100644 --- a/src/HttpServerBodyCommand.cc +++ b/src/HttpServerBodyCommand.cc @@ -148,8 +148,8 @@ void HttpServerBodyCommand::addHttpServerResponseCommand(bool delayed) auto resp = make_unique(getCuid(), httpServer_, e_, socket_); if (delayed) { - e_->addCommand( - make_unique(getCuid(), e_, 1, std::move(resp), true)); + e_->addCommand(make_unique( + getCuid(), e_, std::chrono::seconds(1), std::move(resp), true)); return; } @@ -320,7 +320,8 @@ bool HttpServerBodyCommand::execute() return false; } } else { - if(timeoutTimer_.difference(global::wallclock()) >= 30) { + if(timeoutTimer_.difference(global::wallclock()) >= + std::chrono::seconds(30)) { A2_LOG_INFO("HTTP request body timeout."); return true; } else { diff --git a/src/HttpServerCommand.cc b/src/HttpServerCommand.cc index 59159a82..f2fdb137 100644 --- a/src/HttpServerCommand.cc +++ b/src/HttpServerCommand.cc @@ -253,7 +253,8 @@ bool HttpServerCommand::execute() return true; } } else { - if(timeoutTimer_.difference(global::wallclock()) >= 30) { + if(timeoutTimer_.difference(global::wallclock()) >= + std::chrono::seconds(30)) { A2_LOG_INFO("HTTP request timeout."); return true; } else { diff --git a/src/InitiateConnectionCommand.cc b/src/InitiateConnectionCommand.cc index 585c1ff3..612d8b12 100644 --- a/src/InitiateConnectionCommand.cc +++ b/src/InitiateConnectionCommand.cc @@ -64,7 +64,7 @@ InitiateConnectionCommand::InitiateConnectionCommand DownloadEngine* e) : AbstractCommand(cuid, req, fileEntry, requestGroup, e) { - setTimeout(getOption()->getAsInt(PREF_DNS_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_DNS_TIMEOUT))); // give a chance to be executed in the next loop in DownloadEngine setStatus(Command::STATUS_ONESHOT_REALTIME); disableReadCheckSocket(); diff --git a/src/InitiatorMSEHandshakeCommand.cc b/src/InitiatorMSEHandshakeCommand.cc index b91553f6..7a04b984 100644 --- a/src/InitiatorMSEHandshakeCommand.cc +++ b/src/InitiatorMSEHandshakeCommand.cc @@ -74,7 +74,8 @@ InitiatorMSEHandshakeCommand::InitiatorMSEHandshakeCommand { disableReadCheckSocket(); setWriteCheckSocket(getSocket()); - setTimeout(getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)); + setTimeout(std::chrono::seconds( + getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT))); btRuntime_->increaseConnections(); requestGroup_->increaseNumCommand(); @@ -98,7 +99,7 @@ bool InitiatorMSEHandshakeCommand::executeInternal() { addCommandSelf(); return false; } - setTimeout(getOption()->getAsInt(PREF_BT_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_BT_TIMEOUT))); mseHandshake_->initEncryptionFacility(true); mseHandshake_->sendPublicKey(); sequence_ = INITIATOR_SEND_KEY_PENDING; diff --git a/src/LpdMessageDispatcher.cc b/src/LpdMessageDispatcher.cc index 0128b15b..e18f3a33 100644 --- a/src/LpdMessageDispatcher.cc +++ b/src/LpdMessageDispatcher.cc @@ -48,13 +48,13 @@ LpdMessageDispatcher::LpdMessageDispatcher uint16_t port, const std::string& multicastAddress, uint16_t multicastPort, - time_t interval) + std::chrono::seconds interval) : infoHash_(infoHash), port_(port), multicastAddress_(multicastAddress), multicastPort_(multicastPort), - timer_(0), - interval_(interval), + timer_(Timer::zero()), + interval_(std::move(interval)), request_(bittorrent::createLpdRequest(multicastAddress_, multicastPort_, infoHash_, port_)) {} diff --git a/src/LpdMessageDispatcher.h b/src/LpdMessageDispatcher.h index 6fa02549..42cac417 100644 --- a/src/LpdMessageDispatcher.h +++ b/src/LpdMessageDispatcher.h @@ -52,13 +52,13 @@ private: std::string multicastAddress_; uint16_t multicastPort_; Timer timer_; - time_t interval_; + std::chrono::seconds interval_; std::string request_; public: - LpdMessageDispatcher - (const std::string& infoHash, uint16_t port, - const std::string& multicastAddr, uint16_t multicastPort, - time_t interval = 5*60); + LpdMessageDispatcher( + const std::string& infoHash, uint16_t port, + const std::string& multicastAddr, uint16_t multicastPort, + std::chrono::seconds interval = std::chrono::minutes(5)); ~LpdMessageDispatcher(); diff --git a/src/MultiUrlRequestInfo.cc b/src/MultiUrlRequestInfo.cc index e8239309..458cf641 100644 --- a/src/MultiUrlRequestInfo.cc +++ b/src/MultiUrlRequestInfo.cc @@ -135,9 +135,9 @@ std::unique_ptr getStatCalc(const std::shared_ptr