Migrate off of posix_time and most uses of C time_t.

This commit is contained in:
Howard Hinnant
2016-04-26 19:32:57 -04:00
committed by Vinnie Falco
parent 2e2a7509cd
commit 5d9e53a37d
26 changed files with 174 additions and 166 deletions

View File

@@ -1467,8 +1467,6 @@
</ClCompile> </ClCompile>
<ClInclude Include="..\..\src\ripple\basics\ThreadName.h"> <ClInclude Include="..\..\src\ripple\basics\ThreadName.h">
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\ripple\basics\Time.h">
</ClInclude>
<ClInclude Include="..\..\src\ripple\basics\ToString.h"> <ClInclude Include="..\..\src\ripple\basics\ToString.h">
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\ripple\basics\UnorderedContainers.h"> <ClInclude Include="..\..\src\ripple\basics\UnorderedContainers.h">

View File

@@ -1935,9 +1935,6 @@
<ClInclude Include="..\..\src\ripple\basics\ThreadName.h"> <ClInclude Include="..\..\src\ripple\basics\ThreadName.h">
<Filter>ripple\basics</Filter> <Filter>ripple\basics</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\ripple\basics\Time.h">
<Filter>ripple\basics</Filter>
</ClInclude>
<ClInclude Include="..\..\src\ripple\basics\ToString.h"> <ClInclude Include="..\..\src\ripple\basics\ToString.h">
<Filter>ripple\basics</Filter> <Filter>ripple\basics</Filter>
</ClInclude> </ClInclude>

View File

@@ -21,12 +21,10 @@
#define RIPPLE_APP_LEDGER_LEDGERTOJSON_H_INCLUDED #define RIPPLE_APP_LEDGER_LEDGERTOJSON_H_INCLUDED
#include <ripple/app/ledger/Ledger.h> #include <ripple/app/ledger/Ledger.h>
#include <ripple/basics/Time.h>
#include <ripple/basics/StringUtilities.h> #include <ripple/basics/StringUtilities.h>
#include <ripple/protocol/JsonFields.h> #include <ripple/protocol/JsonFields.h>
#include <ripple/protocol/STTx.h> #include <ripple/protocol/STTx.h>
#include <ripple/json/Object.h> #include <ripple/json/Object.h>
#include <boost/date_time/posix_time/posix_time.hpp>
namespace ripple { namespace ripple {

View File

@@ -37,6 +37,8 @@
namespace ripple { namespace ripple {
using namespace std::chrono_literals;
enum enum
{ {
// Number of peers to start with // Number of peers to start with
@@ -45,9 +47,6 @@ enum
// Number of peers to add on a timeout // Number of peers to add on a timeout
,peerCountAdd = 2 ,peerCountAdd = 2
// millisecond for each ledger timeout
,ledgerAcquireTimeoutMillis = 2500
// how many timeouts before we giveup // how many timeouts before we giveup
,ledgerTimeoutRetriesMax = 10 ,ledgerTimeoutRetriesMax = 10
@@ -64,9 +63,12 @@ enum
,reqNodes = 8 ,reqNodes = 8
}; };
// millisecond for each ledger timeout
auto constexpr ledgerAcquireTimeout = 2500ms;
InboundLedger::InboundLedger ( InboundLedger::InboundLedger (
Application& app, uint256 const& hash, std::uint32_t seq, fcReason reason, clock_type& clock) Application& app, uint256 const& hash, std::uint32_t seq, fcReason reason, clock_type& clock)
: PeerSet (app, hash, ledgerAcquireTimeoutMillis, false, clock, : PeerSet (app, hash, ledgerAcquireTimeout, false, clock,
app.journal("InboundLedger")) app.journal("InboundLedger"))
, mHaveHeader (false) , mHaveHeader (false)
, mHaveState (false) , mHaveState (false)

View File

@@ -74,8 +74,7 @@ void fillJson(Object& json, bool closed, LedgerInfo const& info, bool bFull)
if (info.closeTime != NetClock::time_point{}) if (info.closeTime != NetClock::time_point{})
{ {
json[jss::close_time_human] = boost::posix_time::to_simple_string ( json[jss::close_time_human] = to_string(info.closeTime);
ptFromSeconds (info.closeTime.time_since_epoch().count()));
if (! getCloseAgree(info)) if (! getCloseAgree(info))
json[jss::close_time_estimated] = true; json[jss::close_time_estimated] = true;
} }

View File

@@ -30,11 +30,13 @@
namespace ripple { namespace ripple {
using namespace std::chrono_literals;
// Timeout interval in milliseconds
auto constexpr TX_ACQUIRE_TIMEOUT = 250ms;
enum enum
{ {
// Timeout interval in milliseconds
TX_ACQUIRE_TIMEOUT = 250,
NORM_TIMEOUTS = 4, NORM_TIMEOUTS = 4,
MAX_TIMEOUTS = 20, MAX_TIMEOUTS = 20,
}; };

View File

@@ -45,7 +45,6 @@
#include <ripple/basics/contract.h> #include <ripple/basics/contract.h>
#include <ripple/basics/Log.h> #include <ripple/basics/Log.h>
#include <ripple/basics/random.h> #include <ripple/basics/random.h>
#include <ripple/basics/Time.h>
#include <ripple/protocol/digest.h> #include <ripple/protocol/digest.h>
#include <ripple/basics/StringUtilities.h> #include <ripple/basics/StringUtilities.h>
#include <ripple/basics/UptimeTimer.h> #include <ripple/basics/UptimeTimer.h>

View File

@@ -28,7 +28,6 @@
#include <ripple/net/InfoSub.h> #include <ripple/net/InfoSub.h>
#include <memory> #include <memory>
#include <ripple/core/Stoppable.h> #include <ripple/core/Stoppable.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <deque> #include <deque>
#include <tuple> #include <tuple>

View File

@@ -1,34 +0,0 @@
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef RIPPLE_BASICS_TIME_H_INCLUDED
#define RIPPLE_BASICS_TIME_H_INCLUDED
#include <boost/date_time/posix_time/posix_time.hpp>
namespace ripple {
// VFALCO TODO Roll this into some utilities header
int iToSeconds (boost::posix_time::ptime ptWhen);
boost::posix_time::ptime ptFromSeconds (int iSeconds);
uint64_t utFromSeconds (int iSeconds);
} // ripple
#endif

View File

@@ -25,6 +25,7 @@
#include <ripple/beast/clock/manual_clock.h> #include <ripple/beast/clock/manual_clock.h>
#include <chrono> #include <chrono>
#include <cstdint> #include <cstdint>
#include <string>
namespace ripple { namespace ripple {
@@ -55,6 +56,9 @@ public:
static bool const is_steady = false; static bool const is_steady = false;
}; };
std::string to_string(NetClock::time_point tp);
std::string to_string(std::chrono::system_clock::time_point tp);
/** A clock for measuring elapsed time. /** A clock for measuring elapsed time.
The epoch is unspecified. The epoch is unspecified.

View File

@@ -18,11 +18,11 @@
//============================================================================== //==============================================================================
#include <BeastConfig.h> #include <BeastConfig.h>
#include <ripple/basics/chrono.h>
#include <ripple/basics/Log.h> #include <ripple/basics/Log.h>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
// VFALCO TODO Use std::chrono
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cassert> #include <cassert>
#include <iostream>
#include <fstream> #include <fstream>
namespace ripple { namespace ripple {
@@ -311,8 +311,7 @@ Logs::format (std::string& output, std::string const& message,
{ {
output.reserve (message.size() + partition.size() + 100); output.reserve (message.size() + partition.size() + 100);
output = boost::posix_time::to_simple_string ( output = to_string(std::chrono::system_clock::now());
boost::posix_time::second_clock::universal_time ());
output += " "; output += " ";
if (! partition.empty ()) if (! partition.empty ())

View File

@@ -18,47 +18,66 @@
//============================================================================== //==============================================================================
#include <BeastConfig.h> #include <BeastConfig.h>
#include <ripple/basics/Time.h> #include <ripple/beast/clock/chrono_util.h>
#include <ripple/basics/chrono.h>
#include <iomanip>
#include <sstream>
#include <tuple>
namespace ripple { namespace ripple {
// VFALCO TODO Tidy this up into a RippleTime object static
std::tuple<int, unsigned, unsigned>
// civil_from_days(int z) noexcept
// Time support
// We have our own epoch.
//
boost::posix_time::ptime ptEpoch ()
{ {
return boost::posix_time::ptime (boost::gregorian::date (2000, boost::gregorian::Jan, 1)); z += 719468;
const int era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097); // [0, 146096]
const unsigned yoe = (doe - doe/1460 + doe/36524 - doe/146096) / 365; // [0, 399]
const int y = static_cast<int>(yoe) + era * 400;
const unsigned doy = doe - (365*yoe + yoe/4 - yoe/100); // [0, 365]
const unsigned mp = (5*doy + 2)/153; // [0, 11]
const unsigned d = doy - (153*mp+2)/5 + 1; // [1, 31]
const unsigned m = mp + (mp < 10 ? 3 : -9); // [1, 12]
return std::tuple<int, unsigned, unsigned>(y + (m <= 2), m, d);
} }
int iToSeconds (boost::posix_time::ptime ptWhen) std::string
to_string(std::chrono::system_clock::time_point tp)
{ {
return ptWhen.is_not_a_date_time () const char* months[] =
? -1 {
: (ptWhen - ptEpoch ()).total_seconds (); "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
using namespace std::chrono;
auto s = floor<seconds>(tp.time_since_epoch());
auto sd = floor<days>(s); // number of days
s -= sd; // time of day in seconds
auto h = floor<hours>(s);
s -= h;
auto m = floor<minutes>(s);
s -= m;
int y;
unsigned mn, d;
std::tie(y, mn, d) = civil_from_days(static_cast<int>(sd.count()));
// Date-time in y/mn/d h:m:s
std::ostringstream str;
str.fill('0');
str.flags(std::ios::dec | std::ios::right);
using std::setw;
str << y << '-' << months[mn-1] << '-' << setw(2) << d << ' '
<< setw(2) << h.count() << ':'
<< setw(2) << m.count() << ':'
<< setw(2) << s.count();
return str.str();
} }
// Convert our time in seconds to a ptime. std::string
boost::posix_time::ptime ptFromSeconds (int iSeconds) to_string(NetClock::time_point tp)
{ {
return iSeconds < 0 using namespace std::chrono;
? boost::posix_time::ptime (boost::posix_time::not_a_date_time) return to_string(system_clock::time_point{tp.time_since_epoch() + 946684800s});
: ptEpoch () + boost::posix_time::seconds (iSeconds);
}
// Convert from our time to UNIX time in seconds.
uint64_t utFromSeconds (int iSeconds)
{
boost::posix_time::time_duration tdDelta =
boost::posix_time::ptime (boost::gregorian::date (2000, boost::gregorian::Jan, 1))
- boost::posix_time::ptime (boost::gregorian::date (1970, boost::gregorian::Jan, 1))
+ boost::posix_time::seconds (iSeconds)
;
return tdDelta.total_seconds ();
} }
} // ripple } // ripple

View File

@@ -20,7 +20,7 @@
#ifndef BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED #ifndef BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED
#define BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED #define BEAST_ASIO_IO_LATENCY_PROBE_H_INCLUDED
#include <boost/asio/deadline_timer.hpp> #include <boost/asio/basic_waitable_timer.hpp>
#include <boost/asio/io_service.hpp> #include <boost/asio/io_service.hpp>
#include <boost/config.hpp> #include <boost/config.hpp>
#include <chrono> #include <chrono>
@@ -43,7 +43,7 @@ private:
std::size_t m_count; std::size_t m_count;
duration const m_period; duration const m_period;
boost::asio::io_service& m_ios; boost::asio::io_service& m_ios;
boost::asio::deadline_timer m_timer; boost::asio::basic_waitable_timer<std::chrono::steady_clock> m_timer;
bool m_cancel; bool m_cancel;
public: public:
@@ -219,11 +219,7 @@ private:
} }
else else
{ {
boost::posix_time::microseconds mms ( m_probe->m_timer.expires_from_now(when - now);
std::chrono::duration_cast <
std::chrono::microseconds> (
when - now).count ());
m_probe->m_timer.expires_from_now (mms);
m_probe->m_timer.async_wait (sample_op <Handler> ( m_probe->m_timer.async_wait (sample_op <Handler> (
m_handler, now, m_repeat, m_probe)); m_handler, now, m_repeat, m_probe));
} }

View File

@@ -20,6 +20,8 @@
#ifndef BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED #ifndef BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED
#define BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED #define BEAST_CHRONO_CHRONO_UTIL_H_INCLUDED
#include <chrono>
// From Howard Hinnant // From Howard Hinnant
// http://home.roadrunner.com/~hinnant/duration_io/chrono_util.html // http://home.roadrunner.com/~hinnant/duration_io/chrono_util.html

View File

@@ -204,7 +204,7 @@ private:
boost::asio::io_service m_io_service; boost::asio::io_service m_io_service;
boost::optional <boost::asio::io_service::work> m_work; boost::optional <boost::asio::io_service::work> m_work;
boost::asio::io_service::strand m_strand; boost::asio::io_service::strand m_strand;
boost::asio::deadline_timer m_timer; boost::asio::basic_waitable_timer<std::chrono::steady_clock> m_timer;
boost::asio::ip::udp::socket m_socket; boost::asio::ip::udp::socket m_socket;
std::deque <std::string> m_data; std::deque <std::string> m_data;
std::recursive_mutex metricsLock_; std::recursive_mutex metricsLock_;
@@ -407,7 +407,8 @@ public:
void set_timer () void set_timer ()
{ {
m_timer.expires_from_now (boost::posix_time::seconds (1)); using namespace std::chrono_literals;
m_timer.expires_from_now(1s);
m_timer.async_wait (std::bind ( m_timer.async_wait (std::bind (
&StatsDCollectorImp::on_timer, this, &StatsDCollectorImp::on_timer, this,
beast::asio::placeholders::error)); beast::asio::placeholders::error));

View File

@@ -42,6 +42,8 @@
namespace ripple { namespace ripple {
using namespace std::chrono_literals;
class Rules; class Rules;
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@@ -144,7 +146,7 @@ public:
bool PEER_PRIVATE = false; // True to ask peers not to relay current IP. bool PEER_PRIVATE = false; // True to ask peers not to relay current IP.
int PEERS_MAX = 0; int PEERS_MAX = 0;
int WEBSOCKET_PING_FREQ = 5 * 60; std::chrono::seconds WEBSOCKET_PING_FREQ = 5min;
// RPC parameters // RPC parameters
Json::Value RPC_STARTUP; Json::Value RPC_STARTUP;

View File

@@ -351,7 +351,7 @@ void Config::loadFromString (std::string const& fileContents)
ELB_SUPPORT = beast::lexicalCastThrow <bool> (strTemp); ELB_SUPPORT = beast::lexicalCastThrow <bool> (strTemp);
if (getSingleSection (secConfig, SECTION_WEBSOCKET_PING_FREQ, strTemp, j_)) if (getSingleSection (secConfig, SECTION_WEBSOCKET_PING_FREQ, strTemp, j_))
WEBSOCKET_PING_FREQ = beast::lexicalCastThrow <int> (strTemp); WEBSOCKET_PING_FREQ = std::chrono::seconds{beast::lexicalCastThrow <int>(strTemp)};
getSingleSection (secConfig, SECTION_SSL_VERIFY_FILE, SSL_VERIFY_FILE, j_); getSingleSection (secConfig, SECTION_SSL_VERIFY_FILE, SSL_VERIFY_FILE, j_);
getSingleSection (secConfig, SECTION_SSL_VERIFY_DIR, SSL_VERIFY_DIR, j_); getSingleSection (secConfig, SECTION_SSL_VERIFY_DIR, SSL_VERIFY_DIR, j_);

View File

@@ -40,20 +40,21 @@ namespace ripple {
static uint8_t SNTPQueryData[48] = static uint8_t SNTPQueryData[48] =
{ 0x1B, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; { 0x1B, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
using namespace std::chrono_literals;
// NTP query frequency - 4 minutes // NTP query frequency - 4 minutes
#define NTP_QUERY_FREQUENCY (4 * 60) auto constexpr NTP_QUERY_FREQUENCY = 4min;
// NTP minimum interval to query same servers - 3 minutes // NTP minimum interval to query same servers - 3 minutes
#define NTP_MIN_QUERY (3 * 60) auto constexpr NTP_MIN_QUERY = 3min;
// NTP sample window (should be odd) // NTP sample window (should be odd)
#define NTP_SAMPLE_WINDOW 9 #define NTP_SAMPLE_WINDOW 9
// NTP timestamp constant // NTP timestamp constant
#define NTP_UNIX_OFFSET 0x83AA7E80 auto constexpr NTP_UNIX_OFFSET = 0x83AA7E80s;
// NTP timestamp validity // NTP timestamp validity
#define NTP_TIMESTAMP_VALID ((NTP_QUERY_FREQUENCY + NTP_MIN_QUERY) * 2) auto constexpr NTP_TIMESTAMP_VALID = (NTP_QUERY_FREQUENCY + NTP_MIN_QUERY) * 2;
// SNTP packet offsets // SNTP packet offsets
#define NTP_OFF_INFO 0 #define NTP_OFF_INFO 0
@@ -73,13 +74,18 @@ class SNTPClientImp
: public SNTPClock : public SNTPClock
{ {
private: private:
template <class Duration>
using sys_time = std::chrono::time_point<clock_type, Duration>;
using sys_seconds = sys_time<std::chrono::seconds>;
struct Query struct Query
{ {
bool replied; bool replied;
time_t sent; // VFALCO time_t, really? sys_seconds sent;
std::uint32_t nonce; std::uint32_t nonce;
Query (time_t j = time_t(-1)) Query (sys_seconds j = sys_seconds::max())
: replied (false) : replied (false)
, sent (j) , sent (j)
{ {
@@ -95,12 +101,12 @@ private:
std::map <boost::asio::ip::udp::endpoint, Query> queries_; std::map <boost::asio::ip::udp::endpoint, Query> queries_;
boost::asio::ip::udp::socket socket_; boost::asio::ip::udp::socket socket_;
boost::asio::deadline_timer timer_; boost::asio::basic_waitable_timer<std::chrono::system_clock> timer_;
boost::asio::ip::udp::resolver resolver_; boost::asio::ip::udp::resolver resolver_;
std::vector<std::pair<std::string, time_t>> servers_; std::vector<std::pair<std::string, sys_seconds>> servers_;
int offset_; std::chrono::seconds offset_;
time_t lastUpdate_; sys_seconds lastUpdate_;
std::deque<int> offsets_; std::deque<std::chrono::seconds> offsets_;
std::vector<uint8_t> buf_; std::vector<uint8_t> buf_;
boost::asio::ip::udp::endpoint ep_; boost::asio::ip::udp::endpoint ep_;
@@ -115,7 +121,7 @@ public:
, timer_ (io_service_) , timer_ (io_service_)
, resolver_ (io_service_) , resolver_ (io_service_)
, offset_ (0) , offset_ (0)
, lastUpdate_ (time_t(-1)) , lastUpdate_ (sys_seconds::max())
, buf_ (256) , buf_ (256)
{ {
} }
@@ -150,7 +156,7 @@ public:
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
for (auto const& item : servers) for (auto const& item : servers)
servers_.emplace_back( servers_.emplace_back(
item, time_t(-1)); item, sys_seconds::max());
} }
queryAll(); queryAll();
@@ -161,8 +167,7 @@ public:
&SNTPClientImp::onRead, this, &SNTPClientImp::onRead, this,
beast::asio::placeholders::error, beast::asio::placeholders::error,
beast::asio::placeholders::bytes_transferred)); beast::asio::placeholders::bytes_transferred));
timer_.expires_from_now( timer_.expires_from_now(NTP_QUERY_FREQUENCY);
boost::posix_time::seconds(NTP_QUERY_FREQUENCY));
timer_.async_wait(std::bind( timer_.async_wait(std::bind(
&SNTPClientImp::onTimer, this, &SNTPClientImp::onTimer, this,
beast::asio::placeholders::error)); beast::asio::placeholders::error));
@@ -177,18 +182,20 @@ public:
now() const override now() const override
{ {
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
auto const when = clock_type::now(); using namespace std::chrono;
if ((lastUpdate_ == (time_t)-1) || auto const when = time_point_cast<seconds>(clock_type::now());
((lastUpdate_ + NTP_TIMESTAMP_VALID) < time(nullptr))) if ((lastUpdate_ == sys_seconds::max()) ||
((lastUpdate_ + NTP_TIMESTAMP_VALID) <
time_point_cast<seconds>(clock_type::now())))
return when; return when;
return when + std::chrono::seconds(offset_); return when + offset_;
} }
duration duration
offset() const override offset() const override
{ {
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
return std::chrono::seconds(offset_); return offset_;
} }
//-------------------------------------------------------------------------- //--------------------------------------------------------------------------
@@ -213,8 +220,7 @@ public:
} }
doQuery (); doQuery ();
timer_.expires_from_now( timer_.expires_from_now(NTP_QUERY_FREQUENCY);
boost::posix_time::seconds (NTP_QUERY_FREQUENCY));
timer_.async_wait(std::bind( timer_.async_wait(std::bind(
&SNTPClientImp::onTimer, this, &SNTPClientImp::onTimer, this,
beast::asio::placeholders::error)); beast::asio::placeholders::error));
@@ -224,6 +230,7 @@ public:
onRead (error_code const& ec, std::size_t bytes_xferd) onRead (error_code const& ec, std::size_t bytes_xferd)
{ {
using namespace boost::asio; using namespace boost::asio;
using namespace std::chrono;
if (ec == error::operation_aborted) if (ec == error::operation_aborted)
return; return;
@@ -253,7 +260,7 @@ public:
{ {
query->second.replied = true; query->second.replied = true;
if (time (nullptr) > (query->second.sent + 1)) if (time_point_cast<seconds>(clock_type::now()) > (query->second.sent + 1s))
{ {
JLOG(j_.warn()) << JLOG(j_.warn()) <<
"SNTP: Late response from " << ep_; "SNTP: Late response from " << ep_;
@@ -289,7 +296,7 @@ public:
void addServer (std::string const& server) void addServer (std::string const& server)
{ {
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
servers_.push_back (std::make_pair (server, time_t(-1))); servers_.push_back (std::make_pair (server, sys_seconds::max()));
} }
void queryAll () void queryAll ()
@@ -302,11 +309,12 @@ public:
bool doQuery () bool doQuery ()
{ {
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
std::vector< std::pair<std::string, time_t> >::iterator best = servers_.end (); auto best = servers_.end ();
for (auto iter = servers_.begin (), end = best; for (auto iter = servers_.begin (), end = best;
iter != end; ++iter) iter != end; ++iter)
if ((best == end) || (iter->second == time_t(-1)) || (iter->second < best->second)) if ((best == end) || (iter->second == sys_seconds::max()) ||
(iter->second < best->second))
best = iter; best = iter;
if (best == servers_.end ()) if (best == servers_.end ())
@@ -316,9 +324,10 @@ public:
return false; return false;
} }
time_t now = time (nullptr); using namespace std::chrono;
auto now = time_point_cast<seconds>(clock_type::now());
if ((best->second != time_t(-1)) && ((best->second + NTP_MIN_QUERY) >= now)) if ((best->second != sys_seconds::max()) && ((best->second + NTP_MIN_QUERY) >= now))
{ {
JLOG(j_.trace()) << JLOG(j_.trace()) <<
"SNTP: All servers recently queried"; "SNTP: All servers recently queried";
@@ -366,9 +375,10 @@ public:
{ {
std::lock_guard<std::mutex> lock (mutex_); std::lock_guard<std::mutex> lock (mutex_);
Query& query = queries_[*sel]; Query& query = queries_[*sel];
time_t now = time (nullptr); using namespace std::chrono;
auto now = time_point_cast<seconds>(clock_type::now());
if ((query.sent == now) || ((query.sent + 1) == now)) if ((query.sent == now) || ((query.sent + 1s) == now))
{ {
// This can happen if the same IP address is reached through multiple names // This can happen if the same IP address is reached through multiple names
JLOG(j_.trace()) << JLOG(j_.trace()) <<
@@ -379,7 +389,11 @@ public:
query.replied = false; query.replied = false;
query.sent = now; query.sent = now;
query.nonce = rand_int<std::uint32_t>(); query.nonce = rand_int<std::uint32_t>();
reinterpret_cast<std::uint32_t*> (SNTPQueryData)[NTP_OFF_XMITTS_INT] = static_cast<std::uint32_t> (time (nullptr)) + NTP_UNIX_OFFSET; // The following line of code will overflow at 2036-02-07 06:28:16 UTC
// due to the 32 bit cast.
reinterpret_cast<std::uint32_t*> (SNTPQueryData)[NTP_OFF_XMITTS_INT] =
static_cast<std::uint32_t>((time_point_cast<seconds>(clock_type::now()) +
NTP_UNIX_OFFSET).time_since_epoch().count());
reinterpret_cast<std::uint32_t*> (SNTPQueryData)[NTP_OFF_XMITTS_FRAC] = query.nonce; reinterpret_cast<std::uint32_t*> (SNTPQueryData)[NTP_OFF_XMITTS_FRAC] = query.nonce;
socket_.async_send_to(buffer(SNTPQueryData, 48), socket_.async_send_to(buffer(SNTPQueryData, 48),
*sel, std::bind (&SNTPClientImp::onSend, this, *sel, std::bind (&SNTPClientImp::onSend, this,
@@ -403,11 +417,12 @@ public:
void processReply () void processReply ()
{ {
using namespace std::chrono;
assert (buf_.size () >= 48); assert (buf_.size () >= 48);
std::uint32_t* recvBuffer = reinterpret_cast<std::uint32_t*> (&buf_.front ()); std::uint32_t* recvBuffer = reinterpret_cast<std::uint32_t*> (&buf_.front ());
unsigned info = ntohl (recvBuffer[NTP_OFF_INFO]); unsigned info = ntohl (recvBuffer[NTP_OFF_INFO]);
int64_t timev = ntohl (recvBuffer[NTP_OFF_RECVTS_INT]); auto timev = seconds{ntohl(recvBuffer[NTP_OFF_RECVTS_INT])};
unsigned stratum = (info >> 16) & 0xff; unsigned stratum = (info >> 16) & 0xff;
if ((info >> 30) == 3) if ((info >> 30) == 3)
@@ -424,8 +439,9 @@ public:
return; return;
} }
std::int64_t now = static_cast<int> (time (nullptr)); using namespace std::chrono;
timev -= now; auto now = time_point_cast<seconds>(clock_type::now());
timev -= now.time_since_epoch();
timev -= NTP_UNIX_OFFSET; timev -= NTP_UNIX_OFFSET;
// add offset to list, replacing oldest one if appropriate // add offset to list, replacing oldest one if appropriate
@@ -448,13 +464,13 @@ public:
// debounce: small corrections likely // debounce: small corrections likely
// do more harm than good // do more harm than good
if ((offset_ == -1) || (offset_ == 1)) if ((offset_ == -1s) || (offset_ == 1s))
offset_ = 0; offset_ = 0s;
if (timev || offset_) if (timev != 0s || offset_ != 0s)
{ {
JLOG(j_.trace()) << "SNTP: Offset is " << timev << JLOG(j_.trace()) << "SNTP: Offset is " << timev.count() <<
", new system offset is " << offset_; ", new system offset is " << offset_.count();
} }
} }
}; };

View File

@@ -23,7 +23,7 @@
#include <ripple/core/Config.h> #include <ripple/core/Config.h>
#include <boost/asio/io_service.hpp> #include <boost/asio/io_service.hpp>
#include <boost/asio/streambuf.hpp> #include <boost/asio/streambuf.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp> #include <chrono>
namespace ripple { namespace ripple {
@@ -46,7 +46,7 @@ public:
const unsigned short port, const unsigned short port,
std::string const& strPath, std::string const& strPath,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete, std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete,
Logs& l); Logs& l);
@@ -57,7 +57,7 @@ public:
const unsigned short port, const unsigned short port,
std::string const& strPath, std::string const& strPath,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete, std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete,
Logs& l); Logs& l);
@@ -68,7 +68,7 @@ public:
const unsigned short port, const unsigned short port,
std::function <void (boost::asio::streambuf& sb, std::string const& strHost)> build, std::function <void (boost::asio::streambuf& sb, std::string const& strHost)> build,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete, std::function <bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> complete,
Logs& l); Logs& l);
}; };

View File

@@ -138,7 +138,7 @@ public:
bool bSSL, bool bSSL,
std::deque<std::string> deqSites, std::deque<std::string> deqSites,
std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> build, std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> build,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function<bool (const boost::system::error_code& ecResult, std::function<bool (const boost::system::error_code& ecResult,
int iStatus, std::string const& strData)> complete) int iStatus, std::string const& strData)> complete)
{ {
@@ -157,7 +157,7 @@ public:
bool bSSL, bool bSSL,
std::deque<std::string> deqSites, std::deque<std::string> deqSites,
std::string const& strPath, std::string const& strPath,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::function<bool (const boost::system::error_code& ecResult, int iStatus,
std::string const& strData)> complete) std::string const& strData)> complete)
{ {
@@ -518,13 +518,13 @@ private:
std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> mBuild; std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> mBuild;
std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> mComplete; std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::string const& strData)> mComplete;
boost::asio::deadline_timer mDeadline; boost::asio::basic_waitable_timer<std::chrono::steady_clock> mDeadline;
// If not success, we are shutting down. // If not success, we are shutting down.
boost::system::error_code mShutdown; boost::system::error_code mShutdown;
std::deque<std::string> mDeqSites; std::deque<std::string> mDeqSites;
boost::posix_time::time_duration mTimeout; std::chrono::seconds mTimeout;
beast::Journal j_; beast::Journal j_;
}; };
@@ -537,7 +537,7 @@ void HTTPClient::get (
const unsigned short port, const unsigned short port,
std::string const& strPath, std::string const& strPath,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::function<bool (const boost::system::error_code& ecResult, int iStatus,
std::string const& strData)> complete, std::string const& strData)> complete,
Logs& l) Logs& l)
@@ -554,7 +554,7 @@ void HTTPClient::get (
const unsigned short port, const unsigned short port,
std::string const& strPath, std::string const& strPath,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::function<bool (const boost::system::error_code& ecResult, int iStatus,
std::string const& strData)> complete, std::string const& strData)> complete,
Logs& l) Logs& l)
@@ -573,7 +573,7 @@ void HTTPClient::request (
const unsigned short port, const unsigned short port,
std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> setRequest, std::function<void (boost::asio::streambuf& sb, std::string const& strHost)> setRequest,
std::size_t responseMax, std::size_t responseMax,
boost::posix_time::time_duration timeout, std::chrono::seconds timeout,
std::function<bool (const boost::system::error_code& ecResult, int iStatus, std::function<bool (const boost::system::error_code& ecResult, int iStatus,
std::string const& strData)> complete, std::string const& strData)> complete,
Logs& l) Logs& l)

View File

@@ -1307,7 +1307,8 @@ void fromNetwork (
// Send request // Send request
const int RPC_REPLY_MAX_BYTES (256*1024*1024); const int RPC_REPLY_MAX_BYTES (256*1024*1024);
const int RPC_NOTIFY_SECONDS (600); using namespace std::chrono_literals;
auto constexpr RPC_NOTIFY = 10min;
auto j = logs.journal ("HTTPClient"); auto j = logs.journal ("HTTPClient");
@@ -1323,7 +1324,7 @@ void fromNetwork (
mapRequestHeaders, mapRequestHeaders,
strPath, std::placeholders::_1, std::placeholders::_2, j), strPath, std::placeholders::_1, std::placeholders::_2, j),
RPC_REPLY_MAX_BYTES, RPC_REPLY_MAX_BYTES,
boost::posix_time::seconds (RPC_NOTIFY_SECONDS), RPC_NOTIFY,
std::bind (&RPCCallImp::onResponse, callbackFuncP, std::bind (&RPCCallImp::onResponse, callbackFuncP,
std::placeholders::_1, std::placeholders::_2, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, j), std::placeholders::_3, j),

View File

@@ -26,7 +26,7 @@
#include <ripple/overlay/Peer.h> #include <ripple/overlay/Peer.h>
#include <ripple/beast/clock/abstract_clock.h> #include <ripple/beast/clock/abstract_clock.h>
#include <ripple/beast/utility/Journal.h> #include <ripple/beast/utility/Journal.h>
#include <boost/asio/deadline_timer.hpp> #include <boost/asio/basic_waitable_timer.hpp>
#include <mutex> #include <mutex>
namespace ripple { namespace ripple {
@@ -119,8 +119,8 @@ private:
protected: protected:
using ScopedLockType = std::unique_lock <std::recursive_mutex>; using ScopedLockType = std::unique_lock <std::recursive_mutex>;
PeerSet (Application& app, uint256 const& hash, int interval, bool txnData, PeerSet (Application& app, uint256 const& hash, std::chrono::milliseconds interval,
clock_type& clock, beast::Journal journal); bool txnData, clock_type& clock, beast::Journal journal);
virtual ~PeerSet() = 0; virtual ~PeerSet() = 0;
@@ -162,7 +162,7 @@ protected:
std::recursive_mutex mLock; std::recursive_mutex mLock;
uint256 mHash; uint256 mHash;
int mTimerInterval; std::chrono::milliseconds mTimerInterval;
int mTimeouts; int mTimeouts;
bool mComplete; bool mComplete;
bool mFailed; bool mFailed;
@@ -171,7 +171,7 @@ protected:
bool mProgress; bool mProgress;
// VFALCO TODO move the responsibility for the timer to a higher level // VFALCO TODO move the responsibility for the timer to a higher level
boost::asio::deadline_timer mTimer; boost::asio::basic_waitable_timer<std::chrono::steady_clock> mTimer;
// VFALCO TODO Verify that these are used in the way that the names suggest. // VFALCO TODO Verify that these are used in the way that the names suggest.
using PeerIdentifier = Peer::id_t; using PeerIdentifier = Peer::id_t;

View File

@@ -26,6 +26,8 @@
namespace ripple { namespace ripple {
using namespace std::chrono_literals;
class InboundLedger; class InboundLedger;
// VFALCO NOTE The txnData constructor parameter is a code smell. // VFALCO NOTE The txnData constructor parameter is a code smell.
@@ -35,7 +37,8 @@ class InboundLedger;
// derived class. Why not just make the timer callback // derived class. Why not just make the timer callback
// function pure virtual? // function pure virtual?
// //
PeerSet::PeerSet (Application& app, uint256 const& hash, int interval, bool txnData, PeerSet::PeerSet (Application& app, uint256 const& hash,
std::chrono::milliseconds interval, bool txnData,
clock_type& clock, beast::Journal journal) clock_type& clock, beast::Journal journal)
: app_ (app) : app_ (app)
, m_journal (journal) , m_journal (journal)
@@ -50,7 +53,7 @@ PeerSet::PeerSet (Application& app, uint256 const& hash, int interval, bool txnD
, mTimer (app_.getIOService ()) , mTimer (app_.getIOService ())
{ {
mLastAction = m_clock.now(); mLastAction = m_clock.now();
assert ((mTimerInterval > 10) && (mTimerInterval < 30000)); assert ((mTimerInterval > 10ms) && (mTimerInterval < 30s));
} }
PeerSet::~PeerSet () PeerSet::~PeerSet ()
@@ -70,7 +73,7 @@ bool PeerSet::insert (Peer::ptr const& ptr)
void PeerSet::setTimer () void PeerSet::setTimer ()
{ {
mTimer.expires_from_now (boost::posix_time::milliseconds (mTimerInterval)); mTimer.expires_from_now(mTimerInterval);
mTimer.async_wait (std::bind (&PeerSet::timerEntry, pmDowncast (), mTimer.async_wait (std::bind (&PeerSet::timerEntry, pmDowncast (),
beast::asio::placeholders::error, m_journal)); beast::asio::placeholders::error, m_journal));
} }

View File

@@ -36,10 +36,15 @@ std::string getHTTPHeaderTimestamp ()
char buffer[96]; char buffer[96];
time_t now; time_t now;
time (&now); time (&now);
struct tm* now_gmt = gmtime (&now); struct tm now_gmt{};
#ifndef _MSC_VER
gmtime_r(&now, &now_gmt);
#else
gmtime_s(&now_gmt, &now);
#endif
strftime (buffer, sizeof (buffer), strftime (buffer, sizeof (buffer),
"Date: %a, %d %b %Y %H:%M:%S +0000\r\n", "Date: %a, %d %b %Y %H:%M:%S +0000\r\n",
now_gmt); &now_gmt);
return std::string (buffer); return std::string (buffer);
} }

View File

@@ -113,7 +113,7 @@ private:
std::deque <std::string> m_receiveQueue; std::deque <std::string> m_receiveQueue;
NetworkOPs& m_netOPs; NetworkOPs& m_netOPs;
boost::asio::io_service& m_io_service; boost::asio::io_service& m_io_service;
boost::asio::deadline_timer m_pingTimer; boost::asio::basic_waitable_timer<std::chrono::system_clock> m_pingTimer;
bool m_sentPing = false; bool m_sentPing = false;
bool m_receiveQueueRunning = false; bool m_receiveQueueRunning = false;
@@ -122,7 +122,7 @@ private:
handler_type& m_handler; handler_type& m_handler;
weak_connection_ptr m_connection; weak_connection_ptr m_connection;
int pingFreq_; std::chrono::seconds pingFreq_;
beast::Journal j_; beast::Journal j_;
}; };
@@ -155,7 +155,7 @@ ConnectionImpl <WebSocket>::ConnectionImpl (
, j_ (app.journal ("ConnectionImpl")) , j_ (app.journal ("ConnectionImpl"))
{ {
// VFALCO Disabled since it might cause hangs // VFALCO Disabled since it might cause hangs
pingFreq_ = 0; pingFreq_ = std::chrono::seconds{0};
if (! m_forwardedFor.empty() || ! m_user.empty()) if (! m_forwardedFor.empty() || ! m_user.empty())
{ {

View File

@@ -74,13 +74,13 @@ boost::asio::io_service::strand& WebSocket02::getStrand (Connection& con)
template <> template <>
void ConnectionImpl <WebSocket02>::setPingTimer () void ConnectionImpl <WebSocket02>::setPingTimer ()
{ {
if (pingFreq_ <= 0) using namespace std::chrono_literals;
if (pingFreq_ <= 0s)
return; return;
connection_ptr ptr = m_connection.lock (); connection_ptr ptr = m_connection.lock ();
if (ptr) if (ptr)
{ {
this->m_pingTimer.expires_from_now ( this->m_pingTimer.expires_from_now(pingFreq_);
boost::posix_time::seconds (pingFreq_));
this->m_pingTimer.async_wait ( this->m_pingTimer.async_wait (
ptr->get_strand ().wrap ( ptr->get_strand ().wrap (