rippled
Loading...
Searching...
No Matches
OverlayImpl.h
1//------------------------------------------------------------------------------
2/*
3 This file is part of rippled: https://github.com/ripple/rippled
4 Copyright (c) 2012, 2013 Ripple Labs Inc.
5
6 Permission to use, copy, modify, and/or distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19
20#ifndef RIPPLE_OVERLAY_OVERLAYIMPL_H_INCLUDED
21#define RIPPLE_OVERLAY_OVERLAYIMPL_H_INCLUDED
22
23#include <xrpld/app/main/Application.h>
24#include <xrpld/core/Job.h>
25#include <xrpld/overlay/Message.h>
26#include <xrpld/overlay/Overlay.h>
27#include <xrpld/overlay/Slot.h>
28#include <xrpld/overlay/detail/Handshake.h>
29#include <xrpld/overlay/detail/TrafficCount.h>
30#include <xrpld/overlay/detail/TxMetrics.h>
31#include <xrpld/peerfinder/PeerfinderManager.h>
32#include <xrpld/rpc/ServerHandler.h>
33#include <xrpl/basics/Resolver.h>
34#include <xrpl/basics/UnorderedContainers.h>
35#include <xrpl/basics/chrono.h>
36#include <xrpl/beast/utility/instrumentation.h>
37#include <xrpl/resource/ResourceManager.h>
38#include <xrpl/server/Handoff.h>
39#include <boost/asio/basic_waitable_timer.hpp>
40#include <boost/asio/ip/tcp.hpp>
41#include <boost/asio/ssl/context.hpp>
42#include <boost/asio/strand.hpp>
43#include <boost/container/flat_map.hpp>
44#include <atomic>
45#include <chrono>
46#include <condition_variable>
47#include <cstdint>
48#include <memory>
49#include <mutex>
50#include <optional>
51#include <unordered_map>
52
53namespace ripple {
54
55class PeerImp;
56class BasicConfig;
57
59{
60public:
61 class Child
62 {
63 protected:
65
66 explicit Child(OverlayImpl& overlay);
67
68 virtual ~Child();
69
70 public:
71 virtual void
72 stop() = 0;
73 };
74
75private:
77 using socket_type = boost::asio::ip::tcp::socket;
78 using address_type = boost::asio::ip::address;
79 using endpoint_type = boost::asio::ip::tcp::endpoint;
80 using error_code = boost::system::error_code;
81
83 {
84 boost::asio::basic_waitable_timer<clock_type> timer_;
85 bool stopping_{false};
86
87 explicit Timer(OverlayImpl& overlay);
88
89 void
90 stop() override;
91
92 void
93 async_wait();
94
95 void
97 };
98
100 boost::asio::io_service& io_service_;
102 boost::asio::io_service::strand strand_;
103 mutable std::recursive_mutex mutex_; // VFALCO use std::mutex
106 boost::container::flat_map<Child*, std::weak_ptr<Child>> list_;
121
123
124 // Transaction reduce-relay metrics
126
127 // A message with the list of manifests we send to peers
129 // Used to track whether we need to update the cached list of manifests
131 // Protects the message and the sequence list of manifests
133
134 //--------------------------------------------------------------------------
135
136public:
138 Application& app,
139 Setup const& setup,
140 ServerHandler& serverHandler,
142 Resolver& resolver,
143 boost::asio::io_service& io_service,
144 BasicConfig const& config,
145 beast::insight::Collector::ptr const& collector);
146
147 OverlayImpl(OverlayImpl const&) = delete;
149 operator=(OverlayImpl const&) = delete;
150
151 void
152 start() override;
153
154 void
155 stop() override;
156
159 {
160 return *m_peerFinder;
161 }
162
165 {
166 return m_resourceManager;
167 }
168
169 Setup const&
170 setup() const
171 {
172 return setup_;
173 }
174
175 Handoff
176 onHandoff(
178 http_request_type&& request,
179 endpoint_type remote_endpoint) override;
180
181 void
182 connect(beast::IP::Endpoint const& remote_endpoint) override;
183
184 int
185 limit() override;
186
188 size() const override;
189
191 json() override;
192
194 getActivePeers() const override;
195
207 std::set<Peer::id_t> const& toSkip,
208 std::size_t& active,
209 std::size_t& disabled,
210 std::size_t& enabledInSkip) const;
211
212 void checkTracking(std::uint32_t) override;
213
215 findPeerByShortID(Peer::id_t const& id) const override;
216
218 findPeerByPublicKey(PublicKey const& pubKey) override;
219
220 void
221 broadcast(protocol::TMProposeSet& m) override;
222
223 void
224 broadcast(protocol::TMValidation& m) override;
225
227 relay(
228 protocol::TMProposeSet& m,
229 uint256 const& uid,
230 PublicKey const& validator) override;
231
233 relay(
234 protocol::TMValidation& m,
235 uint256 const& uid,
236 PublicKey const& validator) override;
237
238 void
239 relay(
240 uint256 const&,
242 std::set<Peer::id_t> const& skip) override;
243
246
247 //--------------------------------------------------------------------------
248 //
249 // OverlayImpl
250 //
251
252 void
254
255 void
257
263 void
265
266 // Called when an active peer is destroyed.
267 void
269
270 // UnaryFunc will be called as
271 // void(std::shared_ptr<PeerImp>&&)
272 //
273 template <class UnaryFunc>
274 void
275 for_each(UnaryFunc&& f) const
276 {
278 {
280
281 // Iterate over a copy of the peer list because peer
282 // destruction can invalidate iterators.
283 wp.reserve(ids_.size());
284
285 for (auto& x : ids_)
286 wp.push_back(x.second);
287 }
288
289 for (auto& w : wp)
290 {
291 if (auto p = w.lock())
292 f(std::move(p));
293 }
294 }
295
296 // Called when TMManifests is received from a peer
297 void
300 std::shared_ptr<PeerImp> const& from);
301
302 static bool
303 isPeerUpgrade(http_request_type const& request);
304
305 template <class Body>
306 static bool
307 isPeerUpgrade(boost::beast::http::response<Body> const& response)
308 {
309 if (!is_upgrade(response))
310 return false;
311 return response.result() ==
312 boost::beast::http::status::switching_protocols;
313 }
314
315 template <class Fields>
316 static bool
317 is_upgrade(boost::beast::http::header<true, Fields> const& req)
318 {
319 if (req.version() < 11)
320 return false;
321 if (req.method() != boost::beast::http::verb::get)
322 return false;
323 if (!boost::beast::http::token_list{req["Connection"]}.exists(
324 "upgrade"))
325 return false;
326 return true;
327 }
328
329 template <class Fields>
330 static bool
331 is_upgrade(boost::beast::http::header<false, Fields> const& req)
332 {
333 if (req.version() < 11)
334 return false;
335 if (!boost::beast::http::token_list{req["Connection"]}.exists(
336 "upgrade"))
337 return false;
338 return true;
339 }
340
341 static std::string
343
344 void
345 reportTraffic(TrafficCount::category cat, bool isInbound, int bytes);
346
347 void
349 {
351 }
352
354 getJqTransOverflow() const override
355 {
356 return jqTransOverflow_;
357 }
358
359 void
361 {
363 }
364
366 getPeerDisconnect() const override
367 {
368 return peerDisconnects_;
369 }
370
371 void
373 {
375 }
376
379 {
381 }
382
384 networkID() const override
385 {
386 return setup_.networkID;
387 }
388
398 void
400 uint256 const& key,
401 PublicKey const& validator,
402 std::set<Peer::id_t>&& peers,
403 protocol::MessageType type);
404
407 void
409 uint256 const& key,
410 PublicKey const& validator,
411 Peer::id_t peer,
412 protocol::MessageType type);
413
419 void
421
423 txMetrics() const override
424 {
425 return txMetrics_.json();
426 }
427
429 template <typename... Args>
430 void
431 addTxMetrics(Args... args)
432 {
433 if (!strand_.running_in_this_thread())
434 return post(
435 strand_,
436 std::bind(&OverlayImpl::addTxMetrics<Args...>, this, args...));
437
438 txMetrics_.addMetrics(args...);
439 }
440
441private:
442 void
443 squelch(
444 PublicKey const& validator,
445 Peer::id_t const id,
446 std::uint32_t squelchDuration) const override;
447
448 void
449 unsquelch(PublicKey const& validator, Peer::id_t id) const override;
450
454 http_request_type const& request,
455 address_type remote_address);
456
460 http_request_type const& request,
461 address_type remote_address,
462 std::string msg);
463
469 bool
470 processCrawl(http_request_type const& req, Handoff& handoff);
471
479 bool
480 processValidatorList(http_request_type const& req, Handoff& handoff);
481
487 bool
488 processHealth(http_request_type const& req, Handoff& handoff);
489
494 bool
495 processRequest(http_request_type const& req, Handoff& handoff);
496
503
510
517
523 getUnlInfo();
524
525 //--------------------------------------------------------------------------
526
527 //
528 // PropertyStream
529 //
530
531 void
532 onWrite(beast::PropertyStream::Map& stream) override;
533
534 //--------------------------------------------------------------------------
535
536 void
537 remove(Child& child);
538
539 void
540 stopChildren();
541
542 void
543 autoConnect();
544
545 void
547
549 void
550 sendTxQueue();
551
554 void
556
557private:
559 {
561 char const* name,
562 beast::insight::Collector::ptr const& collector)
563 : bytesIn(collector->make_gauge(name, "Bytes_In"))
564 , bytesOut(collector->make_gauge(name, "Bytes_Out"))
565 , messagesIn(collector->make_gauge(name, "Messages_In"))
566 , messagesOut(collector->make_gauge(name, "Messages_Out"))
567 {
568 }
573 };
574
575 struct Stats
576 {
577 template <class Handler>
579 Handler const& handler,
580 beast::insight::Collector::ptr const& collector,
581 std::vector<TrafficGauges>&& trafficGauges_)
583 collector->make_gauge("Overlay", "Peer_Disconnects"))
584 , trafficGauges(std::move(trafficGauges_))
585 , hook(collector->make_hook(handler))
586 {
587 }
588
592 };
593
596
597private:
598 void
600 {
601 auto counts = m_traffic.getCounts();
603 XRPL_ASSERT(
604 counts.size() == m_stats.trafficGauges.size(),
605 "ripple::OverlayImpl::collect_metrics : counts size do match");
606
607 for (std::size_t i = 0; i < counts.size(); ++i)
608 {
609 m_stats.trafficGauges[i].bytesIn = counts[i].bytesIn;
610 m_stats.trafficGauges[i].bytesOut = counts[i].bytesOut;
611 m_stats.trafficGauges[i].messagesIn = counts[i].messagesIn;
612 m_stats.trafficGauges[i].messagesOut = counts[i].messagesOut;
613 }
615 }
616};
617
618} // namespace ripple
619
620#endif
T bind(T... args)
Represents a JSON value.
Definition: json_value.h:147
A version-independent IP address and port combination.
Definition: IPEndpoint.h:39
A generic endpoint for log messages.
Definition: Journal.h:59
std::string const & name() const
Returns the name of this source.
A metric for measuring an integral value.
Definition: Gauge.h:40
A reference to a handler for performing polled collection.
Definition: Hook.h:32
Holds unparsed configuration information.
Definition: BasicConfig.h:219
boost::system::error_code error_code
Definition: OverlayImpl.h:80
Json::Value getUnlInfo()
Returns information about the local server's UNL.
void stop() override
static std::string makePrefix(std::uint32_t id)
PeerFinder::Manager & peerFinder()
Definition: OverlayImpl.h:158
boost::asio::ip::tcp::endpoint endpoint_type
Definition: OverlayImpl.h:79
std::atomic< uint64_t > peerDisconnects_
Definition: OverlayImpl.h:119
bool processHealth(http_request_type const &req, Handoff &handoff)
Handles health requests.
boost::asio::ip::address address_type
Definition: OverlayImpl.h:78
static bool is_upgrade(boost::beast::http::header< true, Fields > const &req)
Definition: OverlayImpl.h:317
std::condition_variable_any cond_
Definition: OverlayImpl.h:104
void onWrite(beast::PropertyStream::Map &stream) override
Subclass override.
Json::Value txMetrics() const override
Returns tx reduce-relay metrics.
Definition: OverlayImpl.h:423
void deleteIdlePeers()
Check if peers stopped relaying messages and if slots stopped receiving messages from the validator.
Resolver & m_resolver
Definition: OverlayImpl.h:115
void reportTraffic(TrafficCount::category cat, bool isInbound, int bytes)
void activate(std::shared_ptr< PeerImp > const &peer)
Called when a peer has connected successfully This is called after the peer handshake has been comple...
PeerSequence getActivePeers() const override
Returns a sequence representing the current list of peers.
void start() override
hash_map< std::shared_ptr< PeerFinder::Slot >, std::weak_ptr< PeerImp > > m_peers
Definition: OverlayImpl.h:113
void add_active(std::shared_ptr< PeerImp > const &peer)
std::shared_ptr< Peer > findPeerByPublicKey(PublicKey const &pubKey) override
Returns the peer with the matching public key, or null.
Resource::Manager & m_resourceManager
Definition: OverlayImpl.h:110
std::shared_ptr< Message > manifestMessage_
Definition: OverlayImpl.h:128
std::optional< std::uint32_t > manifestListSeq_
Definition: OverlayImpl.h:130
OverlayImpl & operator=(OverlayImpl const &)=delete
TrafficCount m_traffic
Definition: OverlayImpl.h:112
void squelch(PublicKey const &validator, Peer::id_t const id, std::uint32_t squelchDuration) const override
Squelch handler.
std::shared_ptr< Writer > makeErrorResponse(std::shared_ptr< PeerFinder::Slot > const &slot, http_request_type const &request, address_type remote_address, std::string msg)
reduce_relay::Slots< UptimeClock > slots_
Definition: OverlayImpl.h:122
void deletePeer(Peer::id_t id)
Called when the peer is deleted.
std::shared_ptr< Peer > findPeerByShortID(Peer::id_t const &id) const override
Returns the peer with the matching short id, or null.
std::atomic< Peer::id_t > next_id_
Definition: OverlayImpl.h:116
void incPeerDisconnect() override
Increment and retrieve counters for total peer disconnects, and disconnects we initiate for excessive...
Definition: OverlayImpl.h:360
boost::asio::io_service & io_service_
Definition: OverlayImpl.h:100
void addTxMetrics(Args... args)
Add tx reduce-relay metrics.
Definition: OverlayImpl.h:431
Application & app_
Definition: OverlayImpl.h:99
std::optional< std::uint32_t > networkID() const override
Returns the ID of the network this server is configured for, if any.
Definition: OverlayImpl.h:384
std::weak_ptr< Timer > timer_
Definition: OverlayImpl.h:105
std::atomic< uint64_t > jqTransOverflow_
Definition: OverlayImpl.h:118
metrics::TxMetrics txMetrics_
Definition: OverlayImpl.h:125
void broadcast(protocol::TMProposeSet &m) override
Broadcast a proposal.
void onPeerDeactivate(Peer::id_t id)
std::mutex manifestLock_
Definition: OverlayImpl.h:132
bool processRequest(http_request_type const &req, Handoff &handoff)
Handles non-peer protocol requests.
std::recursive_mutex mutex_
Definition: OverlayImpl.h:103
std::uint64_t getPeerDisconnectCharges() const override
Definition: OverlayImpl.h:378
boost::asio::ip::tcp::socket socket_type
Definition: OverlayImpl.h:77
void remove(std::shared_ptr< PeerFinder::Slot > const &slot)
void sendTxQueue()
Send once a second transactions' hashes aggregated by peers.
std::set< Peer::id_t > relay(protocol::TMProposeSet &m, uint256 const &uid, PublicKey const &validator) override
Relay a proposal.
std::size_t size() const override
The number of active peers on the network Active peers are only those peers that have completed the h...
void unsquelch(PublicKey const &validator, Peer::id_t id) const override
Unsquelch handler.
std::shared_ptr< Writer > makeRedirectResponse(std::shared_ptr< PeerFinder::Slot > const &slot, http_request_type const &request, address_type remote_address)
void for_each(UnaryFunc &&f) const
Definition: OverlayImpl.h:275
static bool isPeerUpgrade(boost::beast::http::response< Body > const &response)
Definition: OverlayImpl.h:307
std::optional< boost::asio::io_service::work > work_
Definition: OverlayImpl.h:101
OverlayImpl(OverlayImpl const &)=delete
Json::Value getOverlayInfo()
Returns information about peers on the overlay network.
Resource::Manager & resourceManager()
Definition: OverlayImpl.h:164
static bool isPeerUpgrade(http_request_type const &request)
Json::Value getServerCounts()
Returns information about the local server's performance counters.
boost::asio::io_service::strand strand_
Definition: OverlayImpl.h:102
void onManifests(std::shared_ptr< protocol::TMManifests > const &m, std::shared_ptr< PeerImp > const &from)
std::unique_ptr< PeerFinder::Manager > m_peerFinder
Definition: OverlayImpl.h:111
std::uint64_t getJqTransOverflow() const override
Definition: OverlayImpl.h:354
void connect(beast::IP::Endpoint const &remote_endpoint) override
Establish a peer connection to the specified endpoint.
Handoff onHandoff(std::unique_ptr< stream_type > &&bundle, http_request_type &&request, endpoint_type remote_endpoint) override
Conditionally accept an incoming HTTP request.
Setup const & setup() const
Definition: OverlayImpl.h:170
std::atomic< uint64_t > peerDisconnectsCharges_
Definition: OverlayImpl.h:120
std::shared_ptr< Message > getManifestsMessage()
hash_map< Peer::id_t, std::weak_ptr< PeerImp > > ids_
Definition: OverlayImpl.h:114
Json::Value getServerInfo()
Returns information about the local server.
bool processValidatorList(http_request_type const &req, Handoff &handoff)
Handles validator list requests.
Json::Value json() override
Return diagnostics on the status of all peers.
std::mutex m_statsMutex
Definition: OverlayImpl.h:595
void checkTracking(std::uint32_t) override
Calls the checkTracking function on each peer.
void incPeerDisconnectCharges() override
Definition: OverlayImpl.h:372
ServerHandler & serverHandler_
Definition: OverlayImpl.h:109
bool processCrawl(http_request_type const &req, Handoff &handoff)
Handles crawl requests.
static bool is_upgrade(boost::beast::http::header< false, Fields > const &req)
Definition: OverlayImpl.h:331
int limit() override
Returns the maximum number of peers we are configured to allow.
void updateSlotAndSquelch(uint256 const &key, PublicKey const &validator, std::set< Peer::id_t > &&peers, protocol::MessageType type)
Updates message count for validator/peer.
void incJqTransOverflow() override
Increment and retrieve counter for transaction job queue overflows.
Definition: OverlayImpl.h:348
beast::Journal const journal_
Definition: OverlayImpl.h:108
boost::container::flat_map< Child *, std::weak_ptr< Child > > list_
Definition: OverlayImpl.h:106
std::uint64_t getPeerDisconnect() const override
Definition: OverlayImpl.h:366
Manages the set of connected peers.
Definition: Overlay.h:52
std::vector< std::shared_ptr< Peer > > PeerSequence
Definition: Overlay.h:79
Maintains a set of IP addresses used for getting into the network.
A public key.
Definition: PublicKey.h:62
Tracks load and resource consumption.
auto const & getCounts() const
An up-to-date copy of all the counters.
Definition: TrafficCount.h:198
Slots is a container for validator's Slot and handles Slot update when a message is received from a v...
Definition: overlay/Slot.h:535
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition: algorithm.h:26
boost::beast::http::request< boost::beast::http::dynamic_body > http_request_type
Definition: Handoff.h:31
STL namespace.
T push_back(T... args)
T reserve(T... args)
Used to indicate the result of a server connection handoff.
Definition: Handoff.h:38
beast::insight::Gauge peerDisconnects
Definition: OverlayImpl.h:589
std::vector< TrafficGauges > trafficGauges
Definition: OverlayImpl.h:590
Stats(Handler const &handler, beast::insight::Collector::ptr const &collector, std::vector< TrafficGauges > &&trafficGauges_)
Definition: OverlayImpl.h:578
beast::insight::Hook hook
Definition: OverlayImpl.h:591
void on_timer(error_code ec)
Definition: OverlayImpl.cpp:91
boost::asio::basic_waitable_timer< clock_type > timer_
Definition: OverlayImpl.h:84
beast::insight::Gauge messagesIn
Definition: OverlayImpl.h:571
beast::insight::Gauge bytesIn
Definition: OverlayImpl.h:569
beast::insight::Gauge messagesOut
Definition: OverlayImpl.h:572
TrafficGauges(char const *name, beast::insight::Collector::ptr const &collector)
Definition: OverlayImpl.h:560
beast::insight::Gauge bytesOut
Definition: OverlayImpl.h:570
std::optional< std::uint32_t > networkID
Definition: Overlay.h:75
Run transaction reduce-relay feature related metrics.
Definition: TxMetrics.h:89
void addMetrics(protocol::MessageType type, std::uint32_t val)
Add protocol message metrics.
Definition: TxMetrics.cpp:30
Json::Value json() const
Get json representation of the metrics.
Definition: TxMetrics.cpp:117