diff options
| author | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2015-06-08 02:03:31 +0900 |
|---|---|---|
| committer | Tatsuhiro Tsujikawa <tatsuhiro.t@gmail.com> | 2015-06-09 02:05:34 +0900 |
| commit | 99cd73c0926f0c07d27777fde2f15816e8040030 (patch) | |
| tree | 7c6a077b0590c49029c76686afb9c2ab1d00bb6d /src | |
| parent | 2874f6ab095a30a4d297cdc85fa3730bec41b1c2 (diff) | |
Replace timer facility with chrono lib
Diffstat (limited to 'src')
123 files changed, 550 insertions, 615 deletions
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<std::pair<size_t, std::string>> 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<SocketCore>& 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<CheckIntegrityEntry> 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<HttpConnection> (cuid, s, std::make_shared<SocketRecvBuffer>(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> peerStorage_; std::shared_ptr<BtAnnounce> 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<std::string>::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<long int>(requestGroup_->getTimeout()), - (*i).c_str())); + A2_LOG_DEBUG( + fmt("AdaptiveURISelector: will retry server with increased" + " timeout (%ld s): %s", + static_cast<long int>(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 <memory> +#include <chrono> 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<std::string>& 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<SocketCore>(); 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_(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_(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_(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>& 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<std::unique_ptr<Command>>& commands, commands.push_back(std::move(c)); } { - auto c = make_unique<ActivePeerConnectionCommand> - (e->newCUID(), requestGroup, e, metadataGetMode?2:10); + auto c = make_unique<ActivePeerConnectionCommand>( + 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<std::unique_ptr<Command>>& commands, if(!metadataGetMode) { auto unionCri = make_unique<UnionSeedCriteria>(); if(option->defined(PREF_SEED_TIME)) { - unionCri->addSeedCriteria(make_unique<TimeSeedCriteria> - (option->getAsInt(PREF_SEED_TIME)*60)); + unionCri->addSeedCriteria(make_unique<TimeSeedCriteria>( + 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<std::unique_ptr<Command>>& 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<BtStopDownloadCommand> - (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> 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<DHTMessage> message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> callback = std::unique_ptr<DHTMessageCallback>{}) = 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<DHTMessage> message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> callback) { - messageQueue_.push_back(make_unique<DHTMessageEntry> - (std::move(message), timeout, std::move(callback))); + messageQueue_.push_back(make_unique<DHTMessageEntry>( + 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<std::unique_ptr<DHTMessageEntry>> messageQueue_; - time_t timeout_; + std::chrono::seconds timeout_; bool sendMessage(DHTMessageEntry* msg); public: @@ -57,7 +57,7 @@ public: virtual void addMessageToQueue(std::unique_ptr<DHTMessage> message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> callback = std::unique_ptr<DHTMessageCallback>{}) 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<DHTMessage> message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> 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<DHTMessage> message; - time_t timeout; + std::chrono::seconds timeout; std::unique_ptr<DHTMessageCallback> callback; DHTMessageEntry(std::unique_ptr<DHTMessage> message, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> 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<DHTMessageCallback> callback) { entries_.push_back(make_unique<DHTMessageTrackerEntry> (message->getRemoteNode(), message->getTransactionID(), message->getMessageType(), - timeout, std::move(callback))); + std::move(timeout), std::move(callback))); } std::pair<std::unique_ptr<DHTResponseMessage>, @@ -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<std::chrono::milliseconds>( + 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<std::chrono::milliseconds>( + 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<DHTMessageCallback> callback = std::unique_ptr<DHTMessageCallback>{}); 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<DHTNode> targetNode, std::string transactionID, std::string messageType, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> 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<DHTNode>& 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<DHTNode> targetNode, std::string transactionID, std::string messageType, - time_t timeout, + std::chrono::seconds timeout, std::unique_ptr<DHTMessageCallback> callback = std::unique_ptr<DHTMessageCallback>{}); @@ -80,7 +80,7 @@ public: const std::string& getMessageType() const; const std::unique_ptr<DHTMessageCallback>& getCallback() const; std::unique_ptr<DHTMessageCallback> 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<std::shared_ptr<Peer> >& peers } } -namespace { -class RemoveStalePeerAddrEntry -{ -public: - void operator()(const std::shared_ptr<DHTPeerAnnounceEntry>& 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<unsigned long>(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<DHTPeerAnnounceEntry>& 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<DHTNode>& 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<DHTNode>& 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<std::unique_ptr<Command>> DHTSetup::setup auto tokenTracker = make_unique<DHTTokenTracker>(); // For now, UDPTrackerClient was enabled along with DHT auto udpTrackerClient = std::make_shared<UDPTrackerClient>(); - 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<std::unique_ptr<Command>> 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<std::unique_ptr<Command>> DHTSetup::setup tempCommands.push_back(std::move(command)); } { - auto command = make_unique<DHTAutoSaveCommand> - (e->newCUID(), e, family, 30*60); + auto command = make_unique<DHTAutoSaveCommand>(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<DHTTask> DHTTaskFactoryImpl::createPingTask(const std::shared_ptr<DHTNode>& remoteNode, int numRetry) { - std::shared_ptr<DHTPingTask> task(new DHTPingTask(remoteNode, numRetry)); + auto task = std::make_shared<DHTPingTask>(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<DHTAbstractTask>& task); public: @@ -100,9 +100,9 @@ public: void setLocalNode(const std::shared_ptr<DHTNode>& 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<Integer>(dict->get(BtAnnounce::INTERVAL)); if(ival && ival->i() > 0) { - interval_ = ival->i(); - A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_))); + interval_ = std::chrono::seconds(ival->i()); + A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_.count()))); } const Integer* mival = downcast<Integer>(dict->get(BtAnnounce::MIN_INTERVAL)); if(mival && mival->i() > 0) { - minInterval_ = mival->i(); - A2_LOG_DEBUG(fmt("Min interval:%ld", static_cast<long int>(minInterval_))); + minInterval_ = std::chrono::seconds(mival->i()); + A2_LOG_DEBUG( + fmt("Min interval:%ld", static_cast<long int>(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<UDPTrackerReply>& 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<long int>(minInterval_))); + minInterval_ = std::chrono::seconds(reply->interval); + A2_LOG_DEBUG( + fmt("Min interval:%ld", static_cast<long int>(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<size_t> 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<ExtensionMessageRegistry> 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> 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<BtSeederStateChoke>()), leecherStateChoke_(make_unique<BtLeecherStateChoke>()), - 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>& 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<std::string, time_t> badPeers_; + std::map<std::string, Timer> badPeers_; Timer lastBadPeerCleaned_; bool isPeerAlreadyAdded(const std::shared_ptr<Peer>& 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<size_t>& indexes, } } -namespace { -class FindElapsedHave +void +DefaultPieceStorage::removeAdvertisedPiece(const std::chrono::seconds& elapsed) { -private: - time_t elapsed; -public: - FindElapsedHave(time_t elapsed):elapsed(elapsed) {} - - bool operator()(const HaveEntry& have) { - if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) { - return true; - } else { - return false; - } - } -}; -} // namespace + auto itr = std::find_if(std::begin(haves_), std::end(haves_), + [&elapsed](const HaveEntry& have) { + return have.getRegisteredTime().difference(global::wallclock()) >= elapsed; + }); -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<unsigned long>(haves_.end()-itr))); - haves_.erase(itr, haves_.end()); + static_cast<unsigned long>(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> 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> messageDigest_; - time_t startupIdleTime_; + std::chrono::seconds startupIdleTime_; int lowestDownloadSpeedLimit_; @@ -99,9 +99,9 @@ public: void installStreamFilter(std::unique_ptr<StreamFilter> 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<FileEntry> 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<FileEntry>() 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) : eventPoll_(std::move(eventPoll)), haltRequested_(0), noWait_(true), refreshInterval_(DEFAULT_REFRESH_INTERVAL), - lastRefresh_(0), + lastRefresh_(Timer::zero()), cookieStorage_(make_unique<CookieStorage>()), #ifdef ENABLE_BITTORRENT btRegistry_(make_unique<BtRegistry>()), @@ -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<std::chrono::microseconds>(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<std::string, SocketPoolEntry>::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<std::string, SocketPoolEntry> newPool; @@ -351,9 +357,9 @@ void DownloadEngine::poolSocket uint16_t proxyport, const std::shared_ptr<SocketCore>& 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<SocketCore>& 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<std::string, uint16_t>& res, void DownloadEngine::poolSocket(const std::shared_ptr<Request>& request, const std::shared_ptr<Request>& proxyRequest, const std::shared_ptr<SocketCore>& 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<std::string, uint16_t> 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<Request>& proxyRequest, const std::shared_ptr<SocketCore>& 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<std::string, uint16_t> 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<SocketCore>& 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<SocketCore>& socket, time_t timeout) +(const std::shared_ptr<SocketCore>& socket, std::chrono::seconds timeout) : socket_(socket), - timeout_(timeout) + timeout_(std::move(timeout)) {} DownloadEngine::SocketPoolEntry::~SocketPoolEntry() {} @@ -577,9 +583,9 @@ const std::unique_ptr<CookieStorage>& DownloadEngine::getCookieStorage() const return cookieStorage_; } -void DownloadEngine::setRefreshInterval(int64_t interval) +void DownloadEngine::setRefreshInterval(std::chrono::milliseconds interval) { - refreshInterval_ = std::min(static_cast<int64_t>(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<SocketCore>& socket, const std::string& option, - time_t timeout); + std::chrono::seconds timeout); SocketPoolEntry(const std::shared_ptr<SocketCore>& 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> cookieStorage_; @@ -272,24 +269,24 @@ public: const std::string& proxyhost, uint16_t proxyport, const std::shared_ptr<SocketCore>& sock, const std::string& options, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); void poolSocket(const std::shared_ptr<Request>& request, const std::string& username, const std::shared_ptr<Request>& proxyRequest, const std::shared_ptr<SocketCore>& 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<SocketCore>& sock, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); void poolSocket(const std::shared_ptr<Request>& request, const std::shared_ptr<Request>& proxyRequest, const std::shared_ptr<SocketCore>& socket, - time_t timeout = 15); + std::chrono::seconds timeout = std::chrono::seconds(15)); std::shared_ptr<SocketCore> popPooledSocket (const std::string& ipaddr, @@ -347,7 +344,7 @@ public: const std::unique_ptr<AuthConfigFactory>& 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<AutoSaveCommand>(e->newCUID(), e.get(), - op->getAsInt(PREF_AUTO_SAVE_INTERVAL))); + e->addRoutineCommand(make_unique<AutoSaveCommand>( + 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<SaveSessionCommand> - (e->newCUID(), e.get(), - op->getAsInt(PREF_SAVE_SESSION_INTERVAL))); + e->addRoutineCommand(make_unique<SaveSessionCommand>( + e->newCUID(), e.get(), + std::chrono::seconds(op->getAsInt(PREF_SAVE_SESSION_INTERVAL)))); } e->addRoutineCommand(make_unique<HaveEraseCommand> - (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<TimedHaltCommand>(e->newCUID(), e.get(), - stopSec)); + e->addRoutineCommand(make_unique<TimedHaltCommand>( + 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<long int>(timer_.difference(global::wallclock())), - getRequestGroup()->getTotalLength())); + A2_LOG_DEBUG(fmt(MSG_ALLOCATION_COMPLETED, + static_cast<long int>( + std::chrono::duration_cast<std::chrono::seconds>( + timer_.difference(global::wallclock())).count()), + getRequestGroup()->getTotalLength())); std::vector<std::unique_ptr<Command>> 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<Request> FileEntry::findFasterRequest(const std::shared_ptr<Request>& base) { - const int startupIdleTime = 10; if(requestPool_.empty() || lastFasterReplace_.difference(global::wallclock()) < startupIdleTime) { return nullptr; @@ -248,7 +251,6 @@ FileEntry::findFasterRequest const std::vector<std::pair<size_t, std::string> >& usedHosts, const std::shared_ptr<ServerStatMan>& 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<FtpDownloadCommand> (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<HttpServerResponseCommand>(getCuid(), httpServer_, e_, socket_); if (delayed) { - e_->addCommand( - make_unique<DelayedCommand>(getCuid(), e_, 1, std::move(resp), true)); + e_->addCommand(make_unique<DelayedCommand>( + 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<StatCalc> getStatCalc(const std::shared_ptr<Option>& op) if(op->getAsBool(PREF_QUIET)) { return make_unique<NullStatCalc>(); } - auto impl = make_unique<ConsoleStatCalc>(op->getAsInt(PREF_SUMMARY_INTERVAL), - op->getAsBool(PREF_ENABLE_COLOR), - op->getAsBool(PREF_HUMAN_READABLE)); + auto impl = make_unique<ConsoleStatCalc>( + std::chrono::seconds(op->getAsInt(PREF_SUMMARY_INTERVAL)), + op->getAsBool(PREF_ENABLE_COLOR), op->getAsBool(PREF_HUMAN_READABLE)); impl->setReadoutVisibility(op->getAsBool(PREF_SHOW_CONSOLE_READOUT)); impl->setTruncate(op->getAsBool(PREF_TRUNCATE_CONSOLE_READOUT)); return std::move(impl); @@ -273,10 +273,6 @@ int MultiUrlRequestInfo::prepare() parseAsyncDNSServers(option_->get(PREF_ASYNC_DNS_SERVER)); e_->setAsyncDNSServers(asyncDNSServers); #endif // HAVE_ARES_ADDR_NODE - if(!Timer::monotonicClock()) { - A2_LOG_WARN("Don't change system time while aria2c is running." - " Doing this may make aria2c hang for long time."); - } std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF); if(!serverStatIf.empty()) { diff --git a/src/Peer.cc b/src/Peer.cc index 8b467db5..78594219 100644 --- a/src/Peer.cc +++ b/src/Peer.cc @@ -51,7 +51,7 @@ Peer::Peer(std::string ipaddr, uint16_t port, bool incoming): origPort_(port), cuid_(0), firstContactTime_(global::wallclock()), - dropStartTime_(0), + dropStartTime_(Timer::zero()), seeder_(false), incoming_(incoming), localPeer_(false), diff --git a/src/PeerAbstractCommand.cc b/src/PeerAbstractCommand.cc index 010fbad2..8e80e63d 100644 --- a/src/PeerAbstractCommand.cc +++ b/src/PeerAbstractCommand.cc @@ -57,7 +57,7 @@ PeerAbstractCommand::PeerAbstractCommand : Command(cuid), checkPoint_(global::wallclock()), // TODO referring global option - timeout_(e->getOption()->getAsInt(PREF_BT_TIMEOUT)), + timeout_(std::chrono::seconds(e->getOption()->getAsInt(PREF_BT_TIMEOUT))), e_(e), socket_(s), peer_(peer), diff --git a/src/PeerAbstractCommand.h b/src/PeerAbstractCommand.h index 0e9e3b7c..2b0869ae 100644 --- a/src/PeerAbstractCommand.h +++ b/src/PeerAbstractCommand.h @@ -51,7 +51,7 @@ class SocketCore; class PeerAbstractCommand : public Command { private: Timer checkPoint_; - time_t timeout_; + std::chrono::seconds timeout_; DownloadEngine* e_; std::shared_ptr<SocketCore> socket_; std::shared_ptr<Peer> peer_; @@ -79,7 +79,11 @@ protected: return peer_; } - void setTimeout(time_t timeout) { timeout_ = timeout; } + void setTimeout(std::chrono::seconds timeout) + { + timeout_ = std::move(timeout); + } + virtual bool prepareForNextPeer(time_t wait); virtual void onAbort() {}; // This function is called when DownloadFailureException is caught right after diff --git a/src/PeerInteractionCommand.cc b/src/PeerInteractionCommand.cc index 022cee14..a7deb295 100644 --- a/src/PeerInteractionCommand.cc +++ b/src/PeerInteractionCommand.cc @@ -102,7 +102,8 @@ PeerInteractionCommand::PeerInteractionCommand if(sequence_ == INITIATOR_SEND_HANDSHAKE) { disableReadCheckSocket(); setWriteCheckSocket(getSocket()); - setTimeout(getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)); + setTimeout(std::chrono::seconds( + getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT))); } int family; @@ -180,8 +181,8 @@ PeerInteractionCommand::PeerInteractionCommand dispatcher->setCuid(cuid); dispatcher->setPeer(getPeer()); dispatcher->setDownloadContext(requestGroup_->getDownloadContext().get()); - dispatcher->setRequestTimeout(getOption()-> - getAsInt(PREF_BT_REQUEST_TIMEOUT)); + dispatcher->setRequestTimeout( + std::chrono::seconds(getOption()->getAsInt(PREF_BT_REQUEST_TIMEOUT))); dispatcher->setBtMessageFactory(factory.get()); dispatcher->setRequestGroupMan (getDownloadEngine()->getRequestGroupMan().get()); @@ -227,7 +228,7 @@ PeerInteractionCommand::PeerInteractionCommand (std::move(extensionMessageFactory)); btInteractive->setExtensionMessageRegistry(std::move(exMsgRegistry)); btInteractive->setKeepAliveInterval - (getOption()->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL)); + (std::chrono::seconds(getOption()->getAsInt(PREF_BT_KEEP_ALIVE_INTERVAL))); btInteractive->setRequestGroupMan (getDownloadEngine()->getRequestGroupMan().get()); btInteractive->setBtMessageFactory(std::move(factory)); @@ -307,7 +308,7 @@ bool PeerInteractionCommand::executeInternal() { disableWriteCheckSocket(); setReadCheckSocket(getSocket()); //socket->setBlockingMode(); - setTimeout(getOption()->getAsInt(PREF_BT_TIMEOUT)); + setTimeout(std::chrono::seconds(getOption()->getAsInt(PREF_BT_TIMEOUT))); btInteractive_->initiateHandshake(); sequence_ = INITIATOR_WAIT_HANDSHAKE; break; @@ -403,7 +404,7 @@ void PeerInteractionCommand::onFailure(const Exception& err) { requestGroup_->setLastErrorCode(err.getErrorCode()); requestGroup_->setHaltRequested(true); - getDownloadEngine()->setRefreshInterval(0); + getDownloadEngine()->setRefreshInterval(std::chrono::milliseconds(0)); } bool PeerInteractionCommand::exitBeforeExecute() diff --git a/src/PeerSessionResource.cc b/src/PeerSessionResource.cc index 18ec73ec..1a2fec9a 100644 --- a/src/PeerSessionResource.cc +++ b/src/PeerSessionResource.cc @@ -48,8 +48,8 @@ namespace aria2 { PeerSessionResource::PeerSessionResource(int32_t pieceLength, int64_t totalLength) : bitfieldMan_(make_unique<BitfieldMan>(pieceLength, totalLength)), - lastDownloadUpdate_(0), - lastAmUnchoking_(0), + lastDownloadUpdate_(Timer::zero()), + lastAmUnchoking_(Timer::zero()), dispatcher_(nullptr), amChoking_(true), amInterested_(false), diff --git a/src/PieceStorage.h b/src/PieceStorage.h index 06bccb50..f777500c 100644 --- a/src/PieceStorage.h +++ b/src/PieceStorage.h @@ -254,7 +254,7 @@ public: * Removes have entry if specified seconds have elapsed since its * registration. */ - virtual void removeAdvertisedPiece(time_t elapsed) = 0; + virtual void removeAdvertisedPiece(const std::chrono::seconds& elapsed) = 0; /** * Sets all bits in bitfield to 1. diff --git a/src/ReceiverMSEHandshakeCommand.cc b/src/ReceiverMSEHandshakeCommand.cc index 02205383..441469cd 100644 --- a/src/ReceiverMSEHandshakeCommand.cc +++ b/src/ReceiverMSEHandshakeCommand.cc @@ -63,7 +63,8 @@ ReceiverMSEHandshakeCommand::ReceiverMSEHandshakeCommand sequence_(RECEIVER_IDENTIFY_HANDSHAKE), mseHandshake_(make_unique<MSEHandshake>(cuid, s, e->getOption())) { - setTimeout(e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT)); + setTimeout(std::chrono::seconds( + e->getOption()->getAsInt(PREF_PEER_CONNECTION_TIMEOUT))); mseHandshake_->setWantRead(true); } diff --git a/src/RequestGroup.cc b/src/RequestGroup.cc index e36dbdf3..996ff53f 100644 --- a/src/RequestGroup.cc +++ b/src/RequestGroup.cc @@ -337,7 +337,7 @@ void RequestGroup::createInitialCommand btAnnounce->setPieceStorage(pieceStorage_); btAnnounce->setPeerStorage(peerStorage); btAnnounce->setUserDefinedInterval - (option_->getAsInt(PREF_BT_TRACKER_INTERVAL)); + (std::chrono::seconds(option_->getAsInt(PREF_BT_TRACKER_INTERVAL))); btAnnounce->shuffleAnnounce(); assert(!btRegistry->get(gid_->getNumericId())); @@ -978,7 +978,7 @@ void RequestGroup::releaseRuntimeResource(DownloadEngine* e) peerStorage_ = nullptr; #endif // ENABLE_BITTORRENT if(pieceStorage_) { - pieceStorage_->removeAdvertisedPiece(0); + pieceStorage_->removeAdvertisedPiece(std::chrono::seconds(0)); } // Don't reset segmentMan_ and pieceStorage_ here to provide // progress information via RPC @@ -1129,7 +1129,8 @@ std::shared_ptr<DownloadResult> RequestGroup::createDownloadResult() const res->fileEntries = downloadContext_->getFileEntries(); res->inMemoryDownload = inMemoryDownload_; res->sessionDownloadLength = st.sessionDownloadLength; - res->sessionTime = downloadContext_->calculateSessionTime(); + res->sessionTime = std::chrono::duration_cast<std::chrono::milliseconds>( + downloadContext_->calculateSessionTime()); res->result = downloadResult(); res->followedBy = followedByGIDs_; res->belongsTo = belongsToGID_; @@ -1219,9 +1220,9 @@ void RequestGroup::markInMemoryDownload() inMemoryDownload_ = true; } -void RequestGroup::setTimeout(time_t timeout) +void RequestGroup::setTimeout(std::chrono::seconds timeout) { - timeout_ = timeout; + timeout_ = std::move(timeout); } bool RequestGroup::doesDownloadSpeedExceed() diff --git a/src/RequestGroup.h b/src/RequestGroup.h index 00966748..44f99768 100644 --- a/src/RequestGroup.h +++ b/src/RequestGroup.h @@ -136,7 +136,7 @@ private: Time lastModifiedTime_; // Timeout used for HTTP/FTP downloads. - time_t timeout_; + std::chrono::seconds timeout_; int state_; @@ -444,12 +444,9 @@ public: return inMemoryDownload_; } - void setTimeout(time_t timeout); + void setTimeout(std::chrono::seconds timeout); - time_t getTimeout() const - { - return timeout_; - } + const std::chrono::seconds& getTimeout() const { return timeout_; } // Returns true if current download speed exceeds // maxDownloadSpeedLimit_. Always returns false if diff --git a/src/RequestGroupMan.cc b/src/RequestGroupMan.cc index b118df22..ba4ed963 100644 --- a/src/RequestGroupMan.cc +++ b/src/RequestGroupMan.cc @@ -524,7 +524,7 @@ void RequestGroupMan::fillRequestGroupFromReserver(DownloadEngine* e) } if(count > 0) { e->setNoWait(true); - e->setRefreshInterval(0); + e->setRefreshInterval(std::chrono::milliseconds(0)); A2_LOG_DEBUG(fmt("%d RequestGroup(s) added.", count)); } } @@ -704,10 +704,9 @@ void formatDownloadResultCommon o << std::setw(3) << downloadResult->gid->toAbbrevHex() << "|" << std::setw(4) << status << "|" << std::setw(11); - if(downloadResult->sessionTime > 0) { - o << util::abbrevSize - (downloadResult->sessionDownloadLength*1000/downloadResult->sessionTime)+ - "B/s"; + if(downloadResult->sessionTime.count() > 0) { + o << util::abbrevSize(downloadResult->sessionDownloadLength * 1000 / + downloadResult->sessionTime.count()) << "B/s"; } else { o << "n/a"; } diff --git a/src/RequestSlot.cc b/src/RequestSlot.cc index 08e13fcc..66be9bdc 100644 --- a/src/RequestSlot.cc +++ b/src/RequestSlot.cc @@ -36,12 +36,9 @@ namespace aria2 { -void RequestSlot::setDispatchedTime(time_t sec) { - dispatchedTime_.reset(sec); -} - -bool RequestSlot::isTimeout(time_t timeoutSec) const { - return dispatchedTime_.difference(global::wallclock()) >= timeoutSec; +bool RequestSlot::isTimeout(const std::chrono::seconds& t) const +{ + return dispatchedTime_.difference(global::wallclock()) >= t; } } // namespace aria2 diff --git a/src/RequestSlot.h b/src/RequestSlot.h index e89d9480..2e019631 100644 --- a/src/RequestSlot.h +++ b/src/RequestSlot.h @@ -51,8 +51,12 @@ public: piece_(std::move(piece)) {} - RequestSlot():dispatchedTime_(0), index_(0), begin_(0), length_(0), - blockIndex_(0) + RequestSlot() + : dispatchedTime_(Timer::zero()), + index_(0), + begin_(0), + length_(0), + blockIndex_(0) {} bool operator==(const RequestSlot& requestSlot) const @@ -75,9 +79,7 @@ public: } } - void setDispatchedTime(time_t secFromEpoch); - - bool isTimeout(time_t timeoutSec) const; + bool isTimeout(const std::chrono::seconds& t) const; size_t getIndex() const { return index_; } void setIndex(size_t index) { index_ = index; } @@ -95,6 +97,10 @@ public: { return piece_; } + + // For unit test + void setDispatchedTime(Timer t) { dispatchedTime_ = std::move(t); } + private: Timer dispatchedTime_; size_t index_; diff --git a/src/RpcMethodImpl.cc b/src/RpcMethodImpl.cc index 9dd1d65d..cdd51375 100644 --- a/src/RpcMethodImpl.cc +++ b/src/RpcMethodImpl.cc @@ -391,7 +391,7 @@ std::unique_ptr<ValueBase> removeDownload } else { group->setHaltRequested(true, RequestGroup::USER_REQUEST); } - e->setRefreshInterval(0); + e->setRefreshInterval(std::chrono::milliseconds(0)); } else { if(group->isDependencyResolved()) { e->getRequestGroupMan()->removeReservedGroup(gid); @@ -431,7 +431,7 @@ std::unique_ptr<ValueBase> pauseDownload if(group) { bool reserved = group->getState() == RequestGroup::STATE_WAITING; if(pauseRequestGroup(group, reserved, forcePause)) { - e->setRefreshInterval(0); + e->setRefreshInterval(std::chrono::milliseconds(0)); return createGIDResponse(gid); } } @@ -1306,8 +1306,8 @@ std::unique_ptr<ValueBase> goingShutdown { // Schedule shutdown after 3seconds to give time to client to // receive RPC response. - e->addRoutineCommand(make_unique<TimedHaltCommand> - (e->newCUID(), e, 3, forceHalt)); + e->addRoutineCommand(make_unique<TimedHaltCommand>( + e->newCUID(), e, std::chrono::seconds(3), forceHalt)); A2_LOG_INFO("Scheduled shutdown in 3 seconds."); return createOKResponse(); } diff --git a/src/SaveSessionCommand.cc b/src/SaveSessionCommand.cc index a3b12e54..0740b939 100644 --- a/src/SaveSessionCommand.cc +++ b/src/SaveSessionCommand.cc @@ -44,8 +44,8 @@ namespace aria2 { SaveSessionCommand::SaveSessionCommand -(cuid_t cuid, DownloadEngine* e, time_t interval) - : TimeBasedCommand(cuid, e, interval, true) +(cuid_t cuid, DownloadEngine* e, std::chrono::seconds interval) + : TimeBasedCommand(cuid, e, std::move(interval), true) {} SaveSessionCommand::~SaveSessionCommand() {} diff --git a/src/SaveSessionCommand.h b/src/SaveSessionCommand.h index fcd37bbc..10d9e8f7 100644 --- a/src/SaveSessionCommand.h +++ b/src/SaveSessionCommand.h @@ -42,7 +42,8 @@ namespace aria2 { class SaveSessionCommand : public TimeBasedCommand { public: - SaveSessionCommand(cuid_t cuid, DownloadEngine* e, time_t interval); + SaveSessionCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval); virtual ~SaveSessionCommand(); diff --git a/src/SftpNegotiationCommand.cc b/src/SftpNegotiationCommand.cc index c4600abb..920a1ffb 100644 --- a/src/SftpNegotiationCommand.cc +++ b/src/SftpNegotiationCommand.cc @@ -168,7 +168,7 @@ bool SftpNegotiationCommand::executeInternal() { (getCuid(), getRequest(), getFileEntry(), getRequestGroup(), getDownloadEngine(), getSocket(), std::move(authConfig_)); command->setStartupIdleTime - (getOption()->getAsInt(PREF_STARTUP_IDLE_TIME)); + (std::chrono::seconds(getOption()->getAsInt(PREF_STARTUP_IDLE_TIME))); command->setLowestDownloadSpeedLimit (getOption()->getAsInt(PREF_LOWEST_SPEED_LIMIT)); command->setStatus(Command::STATUS_ONESHOT_REALTIME); diff --git a/src/SpeedCalc.cc b/src/SpeedCalc.cc index ef08dae7..4416c2af 100644 --- a/src/SpeedCalc.cc +++ b/src/SpeedCalc.cc @@ -41,7 +41,9 @@ namespace aria2 { -#define WINDOW_MSEC 15000 +namespace { +constexpr auto WINDOW_TIME = std::chrono::seconds(15); +} // namespace SpeedCalc::SpeedCalc() : accumulatedLength_(0), @@ -58,26 +60,26 @@ void SpeedCalc::reset() maxSpeed_ = 0; } -void SpeedCalc::removeStaleTimeSlot(int64_t now) +void SpeedCalc::removeStaleTimeSlot(const Timer& now) { while(!timeSlots_.empty()) { - if(now - timeSlots_[0].first <= WINDOW_MSEC) { + if(timeSlots_[0].first.difference(now) <= WINDOW_TIME) { break; - } else { - bytesWindow_ -= timeSlots_[0].second; - timeSlots_.pop_front(); } + bytesWindow_ -= timeSlots_[0].second; + timeSlots_.pop_front(); } } int SpeedCalc::calculateSpeed() { - int64_t now = global::wallclock().getTimeInMillis(); + const auto& now = global::wallclock(); removeStaleTimeSlot(now); if(timeSlots_.empty()) { return 0; } - int64_t elapsed = now - timeSlots_[0].first; + auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( + timeSlots_[0].first.difference(now)).count(); if(elapsed <= 0) { elapsed = 1; } @@ -88,9 +90,11 @@ int SpeedCalc::calculateSpeed() void SpeedCalc::update(size_t bytes) { - int64_t now = global::wallclock().getTimeInMillis(); + const auto& now = global::wallclock(); removeStaleTimeSlot(now); - if(timeSlots_.empty() || now/1000 != timeSlots_.back().first/1000) { + if(timeSlots_.empty() || + std::chrono::duration_cast<std::chrono::seconds>( + timeSlots_.back().first.difference(now)) >= std::chrono::seconds(1)) { timeSlots_.push_back(std::make_pair(now, bytes)); } else { timeSlots_.back().second += bytes; @@ -101,7 +105,8 @@ void SpeedCalc::update(size_t bytes) int SpeedCalc::calculateAvgSpeed() const { - int64_t milliElapsed = start_.differenceInMillis(global::wallclock()); + auto milliElapsed = std::chrono::duration_cast<std::chrono::milliseconds>( + start_.difference(global::wallclock())).count(); // if milliElapsed is too small, the average speed is rubbish, better // return 0 if(milliElapsed > 4) { diff --git a/src/SpeedCalc.h b/src/SpeedCalc.h index b337bdcb..ca47833f 100644 --- a/src/SpeedCalc.h +++ b/src/SpeedCalc.h @@ -45,13 +45,13 @@ namespace aria2 { class SpeedCalc { private: - std::deque<std::pair<int64_t, size_t> > timeSlots_; + std::deque<std::pair<Timer, size_t>> timeSlots_; Timer start_; int64_t accumulatedLength_; int64_t bytesWindow_; int maxSpeed_; - void removeStaleTimeSlot(int64_t now); + void removeStaleTimeSlot(const Timer& now); public: SpeedCalc(); diff --git a/src/TimeBasedCommand.cc b/src/TimeBasedCommand.cc index 0be235bb..73753012 100644 --- a/src/TimeBasedCommand.cc +++ b/src/TimeBasedCommand.cc @@ -39,14 +39,14 @@ namespace aria2 { TimeBasedCommand::TimeBasedCommand(cuid_t cuid, DownloadEngine* e, - time_t interval, + std::chrono::seconds interval, bool routineCommand) : Command(cuid), - e_(e), - checkPoint_(global::wallclock()), - interval_(interval), - exit_(false), - routineCommand_(routineCommand) + e_(e), + checkPoint_(global::wallclock()), + interval_(std::move(interval)), + exit_(false), + routineCommand_(routineCommand) {} TimeBasedCommand::~TimeBasedCommand() {} diff --git a/src/TimeBasedCommand.h b/src/TimeBasedCommand.h index 7b26c93b..e5082cad 100644 --- a/src/TimeBasedCommand.h +++ b/src/TimeBasedCommand.h @@ -49,7 +49,7 @@ private: Timer checkPoint_; - time_t interval_; // unit: sec + std::chrono::seconds interval_; /** * setting exit_ to true if this command's job has finished and you want to @@ -73,7 +73,7 @@ protected: exit_ = true; } - time_t getInterval() const + const std::chrono::seconds& getInterval() const { return interval_; } @@ -95,8 +95,8 @@ public: virtual void postProcess() {}; public: - TimeBasedCommand(cuid_t cuid, DownloadEngine* e, time_t interval, - bool routineCommand = false); + TimeBasedCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds interval, bool routineCommand = false); virtual ~TimeBasedCommand(); diff --git a/src/TimeSeedCriteria.cc b/src/TimeSeedCriteria.cc index 5c2a1d6c..8d999448 100644 --- a/src/TimeSeedCriteria.cc +++ b/src/TimeSeedCriteria.cc @@ -37,7 +37,10 @@ namespace aria2 { -TimeSeedCriteria::TimeSeedCriteria(time_t duration):duration_(duration) {} +TimeSeedCriteria::TimeSeedCriteria(std::chrono::seconds duration) + : duration_(std::move(duration)) +{ +} TimeSeedCriteria::~TimeSeedCriteria() {} diff --git a/src/TimeSeedCriteria.h b/src/TimeSeedCriteria.h index bc6bf9af..82685a03 100644 --- a/src/TimeSeedCriteria.h +++ b/src/TimeSeedCriteria.h @@ -36,6 +36,9 @@ #define D_TIME_SEED_CRITERIA_H #include "SeedCriteria.h" + +#include <memory> + #include "TimerA2.h" namespace aria2 { @@ -43,22 +46,22 @@ namespace aria2 { class TimeSeedCriteria : public SeedCriteria { private: // How much time the client does seeding in seconds. - time_t duration_; + std::chrono::seconds duration_; Timer watch_; public: - TimeSeedCriteria(time_t duration); + TimeSeedCriteria(std::chrono::seconds duration); virtual ~TimeSeedCriteria(); virtual void reset() CXX11_OVERRIDE; virtual bool evaluate() CXX11_OVERRIDE; - void setDuration(time_t duration) + void setDuration(std::chrono::seconds duration) { - duration_ = duration; + duration_ = std::move(duration); } - time_t getDuration() const + const std::chrono::seconds& getDuration() const { return duration_; } diff --git a/src/TimedHaltCommand.cc b/src/TimedHaltCommand.cc index da919ef2..1f3470cd 100644 --- a/src/TimedHaltCommand.cc +++ b/src/TimedHaltCommand.cc @@ -44,9 +44,9 @@ namespace aria2 { TimedHaltCommand::TimedHaltCommand (cuid_t cuid, DownloadEngine* e, - time_t secondsToHalt, + std::chrono::seconds secondsToHalt, bool forceHalt) - : TimeBasedCommand(cuid, e, secondsToHalt, true), + : TimeBasedCommand(cuid, e, std::move(secondsToHalt), true), forceHalt_(forceHalt) {} @@ -64,7 +64,7 @@ void TimedHaltCommand::process() { if(!getDownloadEngine()->isHaltRequested()) { A2_LOG_NOTICE(fmt(MSG_TIME_HAS_PASSED, - static_cast<long int>(getInterval()))); + static_cast<long int>(getInterval().count()))); if(forceHalt_) { getDownloadEngine()->requestForceHalt(); } else { diff --git a/src/TimedHaltCommand.h b/src/TimedHaltCommand.h index 46329156..41855078 100644 --- a/src/TimedHaltCommand.h +++ b/src/TimedHaltCommand.h @@ -43,8 +43,8 @@ class TimedHaltCommand:public TimeBasedCommand { private: bool forceHalt_; public: - TimedHaltCommand - (cuid_t cuid, DownloadEngine* e, time_t secondsToHalt, bool forceHalt=false); + TimedHaltCommand(cuid_t cuid, DownloadEngine* e, + std::chrono::seconds secondsToHalt, bool forceHalt = false); virtual ~TimedHaltCommand(); diff --git a/src/TimerA2.cc b/src/TimerA2.cc index 29e5d32f..7c16ba9d 100644 --- a/src/TimerA2.cc +++ b/src/TimerA2.cc @@ -2,7 +2,7 @@ /* * aria2 - The high speed download utility * - * Copyright (C) 2010 Tatsuhiro Tsujikawa + * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -35,141 +35,44 @@ #include "TimerA2.h" -#include <cassert> - -#include "util.h" - namespace aria2 { -Timer::Timer() +Timer::Timer() : tp_(Clock::now()) { reset(); } -Timer::Timer(const Timer& timer):tv_(timer.tv_) {} - -Timer::Timer(time_t sec) +Timer::Timer(const Clock::time_point& tp) : tp_(tp) { - reset(sec); } -Timer::Timer(const struct timeval& tv):tv_(tv) {} - -static bool useClockGettime() +void Timer::reset() { - static timespec ts; - static int r = clock_gettime(CLOCK_MONOTONIC, &ts); - return r == 0; + tp_ = Clock::now(); } -Timer& Timer::operator=(const Timer& timer) +Timer::Clock::duration Timer::difference() const { - if(this != &timer) { - tv_ = timer.tv_; + auto now = Clock::now(); + if (now < tp_) { + return Timer::Clock::duration(std::chrono::seconds(0)); } - return *this; -} -bool Timer::operator<(const Timer& timer) const -{ - return util::difftv(timer.tv_, tv_) > 0; -} - -bool Timer::operator<=(const Timer& timer) const -{ - return util::difftv(timer.tv_, tv_) >= 0; -} - -bool Timer::operator>(const Timer& timer) const -{ - return util::difftv(tv_, timer.tv_) > 0; + return now - tp_; } -static timeval getCurrentTime() +Timer::Clock::duration Timer::difference(const Timer& timer) const { - timeval tv; - if(useClockGettime()) { - timespec ts; - int r = clock_gettime(CLOCK_MONOTONIC, &ts); - assert(r == 0); - tv.tv_sec = ts.tv_sec+2678400; // 1month offset(24*3600*31) - tv.tv_usec = ts.tv_nsec/1000; - } else { - gettimeofday(&tv, nullptr); + if (timer.tp_ < tp_) { + return Timer::Clock::duration(std::chrono::seconds(0)); } - return tv; -} - -void Timer::reset() -{ - tv_ = getCurrentTime(); -} - -void Timer::reset(time_t sec) -{ - tv_.tv_sec = sec; - tv_.tv_usec = 0; -} - -bool Timer::elapsed(time_t sec) const -{ - return - util::difftv(getCurrentTime(), tv_) >= static_cast<int64_t>(sec)*1000000; -} - -bool Timer::elapsedInMillis(int64_t millis) const -{ - return util::difftv(getCurrentTime(), tv_)/1000 >= millis; -} -time_t Timer::difference() const -{ - return util::difftv(getCurrentTime(), tv_)/1000000; -} - -time_t Timer::difference(const timeval& tv) const -{ - return util::difftv(tv, tv_)/1000000; -} - -int64_t Timer::differenceInMillis() const -{ - return util::difftv(getCurrentTime(), tv_)/1000; -} - -int64_t Timer::differenceInMillis(const timeval& tv) const -{ - return util::difftv(tv, tv_)/1000; + return timer.tp_ - tp_; } bool Timer::isZero() const { - return tv_.tv_sec == 0 && tv_.tv_usec == 0; -} - -int64_t Timer::getTimeInMicros() const -{ - return (int64_t)tv_.tv_sec*1000*1000+tv_.tv_usec; -} - -int64_t Timer::getTimeInMillis() const -{ - return (int64_t)tv_.tv_sec*1000+tv_.tv_usec/1000; -} - -time_t Timer::getTime() const -{ - return tv_.tv_sec; -} - -void Timer::advance(time_t sec) -{ - tv_.tv_sec += sec; -} - -bool Timer::monotonicClock() -{ - return useClockGettime(); + return tp_.time_since_epoch() == Clock::duration::zero(); } } // namespace aria2 diff --git a/src/TimerA2.h b/src/TimerA2.h index 83b68faf..3ca4722c 100644 --- a/src/TimerA2.h +++ b/src/TimerA2.h @@ -2,7 +2,7 @@ /* * aria2 - The high speed download utility * - * Copyright (C) 2010 Tatsuhiro Tsujikawa + * Copyright (C) 2015 Tatsuhiro Tsujikawa * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -36,70 +36,66 @@ #define D_TIMER_A2_H #include "common.h" + +#include <chrono> + #include "a2time.h" namespace aria2 { class Timer { -private: - timeval tv_; - - time_t difference(const struct timeval& tv) const; - - int64_t differenceInMillis(const struct timeval& tv) const; public: + using Clock = std::chrono::steady_clock; + // The time value is initialized so that it represents the time at which // this object was created. Timer(); - Timer(const Timer& time); - Timer(time_t sec); - Timer(const struct timeval& tv); + Timer(const Timer& time) = default; + Timer(Timer&& time) = default; - Timer& operator=(const Timer& timer); + template <typename duration> + constexpr Timer(const duration& t) + : tp_(t) + { + } - bool operator<(const Timer& timer) const; + Timer(const Clock::time_point& tp); - bool operator<=(const Timer& timer) const; + Timer& operator=(Timer&& timer) = default; + Timer& operator=(const Timer& timer) = default; - bool operator>(const Timer& timer) const; + bool operator<(const Timer& timer) const { return tp_ < timer.tp_; } + bool operator>(const Timer& timer) const { return timer < *this; } + bool operator<=(const Timer& timer) const { return !(timer < *this); } + bool operator>=(const Timer& timer) const { return !(*this < timer); } void reset(); - void reset(time_t sec); - - bool elapsed(time_t sec) const; - - bool elapsedInMillis(int64_t millis) const; - - time_t difference() const; - - time_t difference(const Timer& timer) const + template <typename duration> + void reset(const duration& t) { - return difference(timer.tv_); + tp_ = Clock::time_point(t); } - int64_t differenceInMillis() const; + Clock::duration difference() const; - int64_t differenceInMillis(const Timer& timer) const - { - return differenceInMillis(timer.tv_); - } + Clock::duration difference(const Timer& timer) const; // Returns true if this object's time value is zero. bool isZero() const; - void advance(time_t sec); - - // Returns this object's time value in seconds. - time_t getTime() const; + template <typename duration> + void advance(const duration& t) + { + tp_ += t; + } - int64_t getTimeInMicros() const; + const Clock::time_point& getTime() const { return tp_; } - int64_t getTimeInMillis() const; + constexpr static Timer zero() { return Timer(std::chrono::seconds(0)); } - // Returns true if this Timer is not affected by system time change. - // Otherwise return false. - static bool monotonicClock(); +private: + Clock::time_point tp_; }; } // namespace aria2 diff --git a/src/TrackerWatcherCommand.cc b/src/TrackerWatcherCommand.cc index 0cb057a4..2826ec54 100644 --- a/src/TrackerWatcherCommand.cc +++ b/src/TrackerWatcherCommand.cc @@ -209,7 +209,7 @@ bool TrackerWatcherCommand::execute() { return true; } else { trackerRequest_->stop(e_); - e_->setRefreshInterval(0); + e_->setRefreshInterval(std::chrono::milliseconds(0)); e_->addCommand(std::unique_ptr<Command>(this)); return false; } @@ -357,7 +357,8 @@ TrackerWatcherCommand::createHTTPAnnRequest(const std::string& uri) // PREF_DRY_RUN=false too. option->put(PREF_USE_HEAD, A2_V_FALSE); // Setting tracker timeouts - rg->setTimeout(option->getAsInt(PREF_BT_TRACKER_TIMEOUT)); + rg->setTimeout( + std::chrono::seconds(option->getAsInt(PREF_BT_TRACKER_TIMEOUT))); option->put(PREF_CONNECT_TIMEOUT, option->get(PREF_BT_TRACKER_CONNECT_TIMEOUT)); option->put(PREF_REUSE_URI, A2_V_FALSE); diff --git a/src/UDPTrackerClient.cc b/src/UDPTrackerClient.cc index c21ae01c..41e52f37 100644 --- a/src/UDPTrackerClient.cc +++ b/src/UDPTrackerClient.cc @@ -368,9 +368,9 @@ namespace { struct TimeoutCheck { bool operator()(const std::shared_ptr<UDPTrackerRequest>& req) const { - int t = req->dispatched.difference(now); + auto t = req->dispatched.difference(now); if(req->failCount == 0) { - if(t >= 15) { + if(t >= std::chrono::seconds(15)) { switch(req->action) { case UDPT_ACT_CONNECT: A2_LOG_INFO(fmt("UDPT resend CONNECT to %s:%u transaction_id=%u", @@ -396,7 +396,7 @@ struct TimeoutCheck { return false; } } else { - if(t >= 60) { + if(t >= std::chrono::minutes(1)) { switch(req->action) { case UDPT_ACT_CONNECT: A2_LOG_INFO(fmt("UDPT timeout CONNECT to %s:%u transaction_id=%u", @@ -475,7 +475,7 @@ UDPTrackerConnection* UDPTrackerClient::getConnectionId return nullptr; } if((*i).second.state == UDPT_CST_CONNECTED && - (*i).second.lastUpdated.difference(now) > 60) { + (*i).second.lastUpdated.difference(now) > std::chrono::minutes(1)) { connectionIdCache_.erase(i); return nullptr; } else { diff --git a/src/UDPTrackerClient.h b/src/UDPTrackerClient.h index fccac0bd..f2bbdce7 100644 --- a/src/UDPTrackerClient.h +++ b/src/UDPTrackerClient.h @@ -62,7 +62,7 @@ struct UDPTrackerConnection { UDPTrackerConnection() : state(UDPT_CST_CONNECTING), connectionId(UDPT_INITIAL_CONNECTION_ID), - lastUpdated(0) + lastUpdated(Timer::zero()) {} UDPTrackerConnection(int state, int64_t connectionId, const Timer& lastUpdated) diff --git a/src/UDPTrackerRequest.cc b/src/UDPTrackerRequest.cc index d1dee383..23a5529b 100644 --- a/src/UDPTrackerRequest.cc +++ b/src/UDPTrackerRequest.cc @@ -45,7 +45,7 @@ UDPTrackerRequest::UDPTrackerRequest() transactionId(0), downloaded(0), left(0), uploaded(0), event(UDPT_EVT_NONE), ip(0), key(0), numWant(0), port(0), extensions(0), state(UDPT_STA_PENDING), error(UDPT_ERR_SUCCESS), - dispatched(0), + dispatched(Timer::zero()), failCount(0) {} diff --git a/src/UTMetadataRequestTracker.cc b/src/UTMetadataRequestTracker.cc index c301b354..0b517568 100644 --- a/src/UTMetadataRequestTracker.cc +++ b/src/UTMetadataRequestTracker.cc @@ -65,33 +65,24 @@ void UTMetadataRequestTracker::remove(size_t index) } namespace { -struct RemoveTimeoutEntry { - RemoveTimeoutEntry(std::vector<size_t>& indexes) - : indexes(indexes) - {} - bool operator()(const UTMetadataRequestTracker::RequestEntry& ent) const - { - if(ent.elapsed(TIMEOUT)) { - A2_LOG_DEBUG(fmt("ut_metadata request timeout. index=%lu", - static_cast<unsigned long>(ent.index_))); - indexes.push_back(ent.index_); - return true; - } else { - return false; - } - } - std::vector<size_t>& indexes; - static const time_t TIMEOUT = 20; -}; +constexpr auto TIMEOUT = std::chrono::seconds(20); } // namespace std::vector<size_t> UTMetadataRequestTracker::removeTimeoutEntry() { std::vector<size_t> indexes; - trackedRequests_.erase(std::remove_if(trackedRequests_.begin(), - trackedRequests_.end(), - RemoveTimeoutEntry(indexes)), - trackedRequests_.end()); + trackedRequests_.erase( + std::remove_if(std::begin(trackedRequests_), std::end(trackedRequests_), + [&indexes](const RequestEntry& ent) { + if (ent.elapsed(TIMEOUT)) { + A2_LOG_DEBUG(fmt("ut_metadata request timeout. index=%lu", + static_cast<unsigned long>(ent.index_))); + indexes.push_back(ent.index_); + return true; + } + return false; + }), + std::end(trackedRequests_)); return indexes; } diff --git a/src/UTMetadataRequestTracker.h b/src/UTMetadataRequestTracker.h index 11b1f557..fc632f16 100644 --- a/src/UTMetadataRequestTracker.h +++ b/src/UTMetadataRequestTracker.h @@ -53,7 +53,7 @@ public: RequestEntry(size_t index):index_(index) {} - bool elapsed(time_t t) const + bool elapsed(const std::chrono::seconds t) const { return dispatchedTime_.difference(global::wallclock()) >= t; } diff --git a/src/UTPexExtensionMessage.cc b/src/UTPexExtensionMessage.cc index f005d307..6d6b7a0f 100644 --- a/src/UTPexExtensionMessage.cc +++ b/src/UTPexExtensionMessage.cc @@ -57,6 +57,8 @@ const size_t DEFAULT_MAX_DROPPED_PEER = 50; const char UTPexExtensionMessage::EXTENSION_NAME[] = "ut_pex"; +constexpr std::chrono::minutes UTPexExtensionMessage::DEFAULT_INTERVAL; + UTPexExtensionMessage::UTPexExtensionMessage(uint8_t extensionMessageID) : extensionMessageID_{extensionMessageID}, peerStorage_{nullptr}, diff --git a/src/UTPexExtensionMessage.h b/src/UTPexExtensionMessage.h index 1489a0f2..90eff9be 100644 --- a/src/UTPexExtensionMessage.h +++ b/src/UTPexExtensionMessage.h @@ -58,7 +58,7 @@ private: PeerStorage* peerStorage_; - time_t interval_; + std::chrono::seconds interval_; size_t maxFreshPeer_; @@ -120,7 +120,7 @@ public: return maxDroppedPeer_; } - static const time_t DEFAULT_INTERVAL = 60; + constexpr static auto DEFAULT_INTERVAL = std::chrono::minutes(1); }; } // namespace aria2 diff --git a/src/UnknownLengthPieceStorage.h b/src/UnknownLengthPieceStorage.h index d39f3cae..57f66dee 100644 --- a/src/UnknownLengthPieceStorage.h +++ b/src/UnknownLengthPieceStorage.h @@ -258,7 +258,9 @@ public: * Removes have entry if specified seconds have elapsed since its * registration. */ - virtual void removeAdvertisedPiece(time_t elapsed) CXX11_OVERRIDE {} + virtual void + removeAdvertisedPiece(const std::chrono::seconds& elapsed) CXX11_OVERRIDE + {} /** * Sets all bits in bitfield to 1. diff --git a/src/WatchProcessCommand.cc b/src/WatchProcessCommand.cc index 0efee39e..f3fa4923 100644 --- a/src/WatchProcessCommand.cc +++ b/src/WatchProcessCommand.cc @@ -70,7 +70,7 @@ WatchProcessCommand::WatchProcessCommand DownloadEngine* e, unsigned int pid, bool forceHalt) - : TimeBasedCommand(cuid, e, 1, true), + : TimeBasedCommand(cuid, e, std::chrono::seconds(1), true), pid_(pid), forceHalt_(forceHalt) {} diff --git a/src/WebSocketSession.cc b/src/WebSocketSession.cc index a85b029d..83a3f7f9 100644 --- a/src/WebSocketSession.cc +++ b/src/WebSocketSession.cc @@ -290,7 +290,8 @@ void WebSocketSession::addTextMessage(const std::string& msg, bool delayed) auto e = getDownloadEngine(); auto cuid = command_->getCuid(); auto c = make_unique<TextMessageCommand>(cuid, command_->getSession(), msg); - e->addCommand(make_unique<DelayedCommand>(cuid, e, 1, std::move(c), false)); + e->addCommand(make_unique<DelayedCommand>(cuid, e, std::chrono::seconds(1), + std::move(c), false)); return; } diff --git a/src/a2time.h b/src/a2time.h index a6a58e35..a561f4e7 100644 --- a/src/a2time.h +++ b/src/a2time.h @@ -37,6 +37,8 @@ #include <time.h> #include <sys/time.h> +#include <chrono> + #ifndef HAVE_LOCALTIME_R # include "localtime_r.h" #endif // HAVE_LOCALTIME_R @@ -76,6 +78,6 @@ #endif // !HAVE_CLOCK_GETTIME // Rounding error in millis -#define A2_DELTA_MILLIS 10 +constexpr auto A2_DELTA_MILLIS = std::chrono::milliseconds(10); #endif // D_A2TIME_H diff --git a/src/aria2api.cc b/src/aria2api.cc index 4aa421e3..c681b9c4 100644 --- a/src/aria2api.cc +++ b/src/aria2api.cc @@ -383,7 +383,7 @@ int removeDownload(Session* session, A2Gid gid, bool force) } else { group->setHaltRequested(true, RequestGroup::USER_REQUEST); } - e->setRefreshInterval(0); + e->setRefreshInterval(std::chrono::milliseconds(0)); } else { if(group->isDependencyResolved()) { e->getRequestGroupMan()->removeReservedGroup(gid); @@ -404,7 +404,7 @@ int pauseDownload(Session* session, A2Gid gid, bool force) if(group) { bool reserved = group->getState() == RequestGroup::STATE_WAITING; if(pauseRequestGroup(group, reserved, force)) { - e->setRefreshInterval(0); + e->setRefreshInterval(std::chrono::milliseconds(0)); return 0; } } |
