Merge branch 'chrono'

pull/251/merge
Tatsuhiro Tsujikawa 2015-06-09 03:59:47 +09:00
commit 2448a8660b
159 changed files with 680 additions and 1151 deletions

View File

@ -879,14 +879,6 @@ AC_CHECK_FUNCS([timegm],
AC_CHECK_FUNCS([daemon], [have_daemon=yes])
AM_CONDITIONAL([HAVE_DAEMON], [test "x$have_daemon" = "xyes"])
AC_CHECK_FUNCS([clock_gettime], [have_clock_gettime=yes])
if test "x$have_clock_gettime" != "xyes"; then
AC_CHECK_FUNCS([mach_absolute_time], [have_mach_absolute_time=yes])
fi
AM_CONDITIONAL([HAVE_MACH_ABSOLUTE_TIME],
[test "x$have_mach_absolute_time" = "xyes"])
AC_CHECK_FUNCS([poll], [have_poll=yes])
AM_CONDITIONAL([HAVE_POLL], [test "x$have_poll" = "xyes"])
@ -897,11 +889,9 @@ case "$host" in
AM_CONDITIONAL([HAVE_GETADDRINFO], true)
dnl defined in ws2tcpip.h, but missing in C:\mingw\lib\libws2_32.a
AM_CONDITIONAL([HAVE_GAI_STRERROR], false)
AM_CONDITIONAL([HAVE_TIMEGETTIME], [test "x$have_clock_gettime" != "xyes"])
;;
*)
AM_CONDITIONAL([MINGW_BUILD], false)
AM_CONDITIONAL([HAVE_TIMEGETTIME], false)
;;
esac

View File

@ -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));

View File

@ -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);

View File

@ -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()));

View File

@ -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());
}

View File

@ -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)
{

View File

@ -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();

View File

@ -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()));
}
}
}
@ -331,7 +336,7 @@ std::string AdaptiveURISelector::getFirstToTestUri
power = (int)pow(2.0, (float)counter);
/* We test the mirror another time if it has not been
* tested since 2^counter days */
if(ss->getLastUpdated().difference() > power*24*60*60) {
if(ss->getLastUpdated().difference() > std::chrono::hours(power * 24)) {
return u;
}
}

View File

@ -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);

View File

@ -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() {}

View File

@ -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();

View File

@ -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_);

View File

@ -81,7 +81,7 @@ private:
DownloadEngine* e_;
Timer startTime_;
Timer timeoutCheck_;
time_t timeout_;
std::chrono::seconds timeout_;
};
} // namespace aria2

View File

@ -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

View File

@ -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

View File

@ -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_),

View File

@ -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),

View File

@ -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);

View File

@ -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));

View File

@ -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();
}
}

View File

@ -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;

View File

@ -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());
}

View File

@ -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,

View File

@ -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() {}

View File

@ -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}
{}

View File

@ -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();

View File

@ -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}

View File

@ -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();

View File

@ -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

View File

@ -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() &&

View File

@ -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;

View File

@ -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));
}
}

View File

@ -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);
}
};

View File

@ -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)}
{}

View File

@ -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);
};

View File

@ -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",

View File

@ -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>{});

View File

@ -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

View File

@ -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

View File

@ -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_);
static_cast<long int>(rtt_.count()));
}
void DHTNode::setID(const unsigned char* id)

View File

@ -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

View File

@ -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}
{}

View File

@ -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();

View File

@ -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

View File

@ -71,7 +71,7 @@ public:
return peerAddrEntries_;
}
void removeStalePeerAddrEntry(time_t timeout);
void removeStalePeerAddrEntry(const std::chrono::seconds& timeout);
bool empty() const;

View File

@ -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();

View File

@ -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;

View File

@ -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);
}
};

View File

@ -131,12 +131,12 @@ void DHTRoutingTableDeserializer::deserialize(const std::string& filename)
// time
if(version == 2) {
READ_CHECK(fp, &temp32, sizeof(temp32));
serializedTime_.setTimeInSec(ntohl(temp32));
serializedTime_.setTimeFromEpoch(ntohl(temp32));
// 4bytes reserved
readBytes(fp, buf, buf.size(), 4);
} else {
READ_CHECK(fp, &temp64, sizeof(temp64));
serializedTime_.setTimeInSec(ntoh64(temp64));
serializedTime_.setTimeFromEpoch(ntoh64(temp64));
}
// localnode

View File

@ -101,7 +101,7 @@ void DHTRoutingTableSerializer::serialize(const std::string& filename)
WRITE_CHECK(fp, header, 8);
// write save date
uint64_t ntime = hton64(Time().getTime());
uint64_t ntime = hton64(Time().getTimeFromEpoch());
WRITE_CHECK(fp, &ntime, sizeof(ntime));
// localnode

View File

@ -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));

View File

@ -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;

View File

@ -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);
}
};

View File

@ -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}
{}

View File

@ -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();

View File

@ -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

View File

@ -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);
}
};

View File

@ -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();
}

View File

@ -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)

View File

@ -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)

View File

@ -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;

View File

@ -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);

View File

@ -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) {}
auto itr = std::find_if(std::begin(haves_), std::end(haves_),
[&elapsed](const HaveEntry& have) {
return have.getRegisteredTime().difference(global::wallclock()) >= elapsed;
});
bool operator()(const HaveEntry& have) {
if(have.getRegisteredTime().difference(global::wallclock()) >= elapsed) {
return true;
} else {
return false;
}
}
};
} // namespace
void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
{
auto itr = std::find_if(haves_.begin(), haves_.end(),
FindElapsedHave(elapsed));
if(itr != haves_.end()) {
if(itr != std::end(haves_)) {
A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
static_cast<unsigned long>(haves_.end()-itr)));
haves_.erase(itr, haves_.end());
static_cast<unsigned long>(std::end(haves_) - itr)));
haves_.erase(itr, std::end(haves_));
}
}

View File

@ -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;

View File

@ -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}
{

View File

@ -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

View File

@ -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)

View File

@ -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>

View File

@ -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.

View File

@ -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

View File

@ -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
{

View File

@ -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)) {

View File

@ -60,8 +60,7 @@ struct DownloadResult
uint64_t sessionDownloadLength;
// milliseconds
int64_t sessionTime;
std::chrono::milliseconds sessionTime;
int64_t totalLength;

View File

@ -257,14 +257,14 @@ bool File::utime(const Time& actime, const Time& modtime) const
{
#if defined(HAVE_UTIMES) && !defined(__MINGW32__)
struct timeval times[2] = {
{ actime.getTime(), 0 },
{ modtime.getTime(), 0 }
{ actime.getTimeFromEpoch(), 0 },
{ modtime.getTimeFromEpoch(), 0 }
};
return utimes(name_.c_str(), times) == 0;
#else // !HAVE_UTIMES
a2utimbuf ub;
ub.actime = actime.getTime();
ub.modtime = modtime.getTime();
ub.actime = actime.getTimeFromEpoch();
ub.modtime = modtime.getTimeFromEpoch();
return a2utime(utf8ToWChar(name_).c_str(), &ub) == 0;
#endif // !HAVE_UTIMES
}

View File

@ -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));

View File

@ -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;

View File

@ -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()) {

View File

@ -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));
}
}
}

View File

@ -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();

View File

@ -232,7 +232,7 @@ std::string HttpRequest::createRequest()
std::string path = getDir();
path += getFile();
auto cookies = cookieStorage_->criteriaFind(getHost(), path,
Time().getTime(),
Time().getTimeFromEpoch(),
getProtocol() == "https");
for(auto c : cookies) {
cookiesValue += c->toString();

View File

@ -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());
}

View File

@ -144,7 +144,7 @@ void HttpResponse::retrieveCookie()
((*r.first).second,
httpRequest_->getHost(),
httpRequest_->getDir(),
now.getTime());
now.getTimeFromEpoch());
}
}

View File

@ -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() &&

View File

@ -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 {

View File

@ -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 {

View File

@ -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();

View File

@ -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;

View File

@ -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_))
{}

View File

@ -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();

View File

@ -675,14 +675,6 @@ if !HAVE_DAEMON
SRCS += daemon.cc daemon.h
endif # !HAVE_DAEMON
if HAVE_TIMEGETTIME
SRCS += clock_gettime_mingw.cc clock_gettime_mingw.h
endif # HAVE_TIMEGETTIME
if HAVE_MACH_ABSOLUTE_TIME
SRCS += clock_gettime_osx.cc clock_gettime_osx.h
endif # HAVE_MACH_ABSOLUTE_TIME
if HAVE_POLL
SRCS += PollEventPoll.cc PollEventPoll.h
endif # HAVE_POLL

View File

@ -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);
@ -217,7 +217,7 @@ int MultiUrlRequestInfo::prepare()
File cookieFile(option_->get(PREF_LOAD_COOKIES));
if(cookieFile.isFile() &&
e_->getCookieStorage()->load(cookieFile.getPath(),
Time().getTime())) {
Time().getTimeFromEpoch())) {
A2_LOG_INFO(fmt("Loaded cookies from '%s'.",
cookieFile.getPath().c_str()));
} else {
@ -273,16 +273,12 @@ 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()) {
e_->getRequestGroupMan()->loadServerStat(serverStatIf);
e_->getRequestGroupMan()->removeStaleServerStat
(option_->getAsInt(PREF_SERVER_STAT_TIMEOUT));
(std::chrono::seconds(option_->getAsInt(PREF_SERVER_STAT_TIMEOUT)));
}
e_->setStatCalc(getStatCalc(option_));
if(uriListParser_) {

View File

@ -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),

View File

@ -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),

View File

@ -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

View File

@ -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()

View File

@ -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),

View File

@ -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.

View File

@ -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);
}

View File

@ -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()

View File

@ -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

Some files were not shown because too many files have changed in this diff Show More