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
40#include <boost/asio/basic_waitable_timer.hpp>
41#include <boost/asio/ip/tcp.hpp>
42#include <boost/asio/ssl/context.hpp>
43#include <boost/asio/strand.hpp>
44#include <boost/container/flat_map.hpp>
45
46#include <atomic>
47#include <chrono>
48#include <condition_variable>
49#include <cstdint>
50#include <memory>
51#include <mutex>
52#include <optional>
53#include <unordered_map>
54
55namespace ripple {
56
57class PeerImp;
58class BasicConfig;
59
61{
62public:
63 class Child
64 {
65 protected:
67
68 explicit Child(OverlayImpl& overlay);
69
70 virtual ~Child();
71
72 public:
73 virtual void
74 stop() = 0;
75 };
76
77private:
79 using socket_type = boost::asio::ip::tcp::socket;
80 using address_type = boost::asio::ip::address;
81 using endpoint_type = boost::asio::ip::tcp::endpoint;
82 using error_code = boost::system::error_code;
83
85 {
86 boost::asio::basic_waitable_timer<clock_type> timer_;
87 bool stopping_{false};
88
89 explicit Timer(OverlayImpl& overlay);
90
91 void
92 stop() override;
93
94 void
95 async_wait();
96
97 void
99 };
100
102 boost::asio::io_service& io_service_;
104 boost::asio::io_service::strand strand_;
105 mutable std::recursive_mutex mutex_; // VFALCO use std::mutex
108 boost::container::flat_map<Child*, std::weak_ptr<Child>> list_;
123
125
126 // Transaction reduce-relay metrics
128
129 // A message with the list of manifests we send to peers
131 // Used to track whether we need to update the cached list of manifests
133 // Protects the message and the sequence list of manifests
135
136 //--------------------------------------------------------------------------
137
138public:
140 Application& app,
141 Setup const& setup,
142 ServerHandler& serverHandler,
144 Resolver& resolver,
145 boost::asio::io_service& io_service,
146 BasicConfig const& config,
147 beast::insight::Collector::ptr const& collector);
148
149 OverlayImpl(OverlayImpl const&) = delete;
151 operator=(OverlayImpl const&) = delete;
152
153 void
154 start() override;
155
156 void
157 stop() override;
158
161 {
162 return *m_peerFinder;
163 }
164
167 {
168 return m_resourceManager;
169 }
170
171 Setup const&
172 setup() const
173 {
174 return setup_;
175 }
176
177 Handoff
178 onHandoff(
180 http_request_type&& request,
181 endpoint_type remote_endpoint) override;
182
183 void
184 connect(beast::IP::Endpoint const& remote_endpoint) override;
185
186 int
187 limit() override;
188
190 size() const override;
191
193 json() override;
194
196 getActivePeers() const override;
197
209 std::set<Peer::id_t> const& toSkip,
210 std::size_t& active,
211 std::size_t& disabled,
212 std::size_t& enabledInSkip) const;
213
214 void checkTracking(std::uint32_t) override;
215
217 findPeerByShortID(Peer::id_t const& id) const override;
218
220 findPeerByPublicKey(PublicKey const& pubKey) override;
221
222 void
223 broadcast(protocol::TMProposeSet& m) override;
224
225 void
226 broadcast(protocol::TMValidation& m) override;
227
229 relay(
230 protocol::TMProposeSet& m,
231 uint256 const& uid,
232 PublicKey const& validator) override;
233
235 relay(
236 protocol::TMValidation& m,
237 uint256 const& uid,
238 PublicKey const& validator) override;
239
240 void
241 relay(
242 uint256 const&,
244 std::set<Peer::id_t> const& skip) override;
245
248
249 //--------------------------------------------------------------------------
250 //
251 // OverlayImpl
252 //
253
254 void
256
257 void
259
265 void
267
268 // Called when an active peer is destroyed.
269 void
271
272 // UnaryFunc will be called as
273 // void(std::shared_ptr<PeerImp>&&)
274 //
275 template <class UnaryFunc>
276 void
277 for_each(UnaryFunc&& f) const
278 {
280 {
282
283 // Iterate over a copy of the peer list because peer
284 // destruction can invalidate iterators.
285 wp.reserve(ids_.size());
286
287 for (auto& x : ids_)
288 wp.push_back(x.second);
289 }
290
291 for (auto& w : wp)
292 {
293 if (auto p = w.lock())
294 f(std::move(p));
295 }
296 }
297
298 // Called when TMManifests is received from a peer
299 void
302 std::shared_ptr<PeerImp> const& from);
303
304 static bool
305 isPeerUpgrade(http_request_type const& request);
306
307 template <class Body>
308 static bool
309 isPeerUpgrade(boost::beast::http::response<Body> const& response)
310 {
311 if (!is_upgrade(response))
312 return false;
313 return response.result() ==
314 boost::beast::http::status::switching_protocols;
315 }
316
317 template <class Fields>
318 static bool
319 is_upgrade(boost::beast::http::header<true, Fields> const& req)
320 {
321 if (req.version() < 11)
322 return false;
323 if (req.method() != boost::beast::http::verb::get)
324 return false;
325 if (!boost::beast::http::token_list{req["Connection"]}.exists(
326 "upgrade"))
327 return false;
328 return true;
329 }
330
331 template <class Fields>
332 static bool
333 is_upgrade(boost::beast::http::header<false, Fields> const& req)
334 {
335 if (req.version() < 11)
336 return false;
337 if (!boost::beast::http::token_list{req["Connection"]}.exists(
338 "upgrade"))
339 return false;
340 return true;
341 }
342
343 static std::string
345
346 void
347 reportTraffic(TrafficCount::category cat, bool isInbound, int bytes);
348
349 void
351 {
353 }
354
356 getJqTransOverflow() const override
357 {
358 return jqTransOverflow_;
359 }
360
361 void
363 {
365 }
366
368 getPeerDisconnect() const override
369 {
370 return peerDisconnects_;
371 }
372
373 void
375 {
377 }
378
381 {
383 }
384
386 networkID() const override
387 {
388 return setup_.networkID;
389 }
390
400 void
402 uint256 const& key,
403 PublicKey const& validator,
404 std::set<Peer::id_t>&& peers,
405 protocol::MessageType type);
406
409 void
411 uint256 const& key,
412 PublicKey const& validator,
413 Peer::id_t peer,
414 protocol::MessageType type);
415
421 void
423
425 txMetrics() const override
426 {
427 return txMetrics_.json();
428 }
429
431 template <typename... Args>
432 void
433 addTxMetrics(Args... args)
434 {
435 if (!strand_.running_in_this_thread())
436 return post(
437 strand_,
438 std::bind(&OverlayImpl::addTxMetrics<Args...>, this, args...));
439
440 txMetrics_.addMetrics(args...);
441 }
442
443private:
444 void
445 squelch(
446 PublicKey const& validator,
447 Peer::id_t const id,
448 std::uint32_t squelchDuration) const override;
449
450 void
451 unsquelch(PublicKey const& validator, Peer::id_t id) const override;
452
456 http_request_type const& request,
457 address_type remote_address);
458
462 http_request_type const& request,
463 address_type remote_address,
464 std::string msg);
465
471 bool
472 processCrawl(http_request_type const& req, Handoff& handoff);
473
481 bool
482 processValidatorList(http_request_type const& req, Handoff& handoff);
483
489 bool
490 processHealth(http_request_type const& req, Handoff& handoff);
491
496 bool
497 processRequest(http_request_type const& req, Handoff& handoff);
498
505
512
519
525 getUnlInfo();
526
527 //--------------------------------------------------------------------------
528
529 //
530 // PropertyStream
531 //
532
533 void
534 onWrite(beast::PropertyStream::Map& stream) override;
535
536 //--------------------------------------------------------------------------
537
538 void
539 remove(Child& child);
540
541 void
542 stopChildren();
543
544 void
545 autoConnect();
546
547 void
549
551 void
552 sendTxQueue();
553
556 void
558
559private:
561 {
563 char const* name,
564 beast::insight::Collector::ptr const& collector)
565 : bytesIn(collector->make_gauge(name, "Bytes_In"))
566 , bytesOut(collector->make_gauge(name, "Bytes_Out"))
567 , messagesIn(collector->make_gauge(name, "Messages_In"))
568 , messagesOut(collector->make_gauge(name, "Messages_Out"))
569 {
570 }
575 };
576
577 struct Stats
578 {
579 template <class Handler>
581 Handler const& handler,
582 beast::insight::Collector::ptr const& collector,
583 std::vector<TrafficGauges>&& trafficGauges_)
585 collector->make_gauge("Overlay", "Peer_Disconnects"))
586 , trafficGauges(std::move(trafficGauges_))
587 , hook(collector->make_hook(handler))
588 {
589 }
590
594 };
595
598
599private:
600 void
602 {
603 auto counts = m_traffic.getCounts();
605 XRPL_ASSERT(
606 counts.size() == m_stats.trafficGauges.size(),
607 "ripple::OverlayImpl::collect_metrics : counts size do match");
608
609 for (std::size_t i = 0; i < counts.size(); ++i)
610 {
611 m_stats.trafficGauges[i].bytesIn = counts[i].bytesIn;
612 m_stats.trafficGauges[i].bytesOut = counts[i].bytesOut;
613 m_stats.trafficGauges[i].messagesIn = counts[i].messagesIn;
614 m_stats.trafficGauges[i].messagesOut = counts[i].messagesOut;
615 }
617 }
618};
619
620} // namespace ripple
621
622#endif
T bind(T... args)
Represents a JSON value.
Definition: json_value.h:148
A version-independent IP address and port combination.
Definition: IPEndpoint.h:39
A generic endpoint for log messages.
Definition: Journal.h:60
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:218
boost::system::error_code error_code
Definition: OverlayImpl.h:82
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:160
boost::asio::ip::tcp::endpoint endpoint_type
Definition: OverlayImpl.h:81
std::atomic< uint64_t > peerDisconnects_
Definition: OverlayImpl.h:121
bool processHealth(http_request_type const &req, Handoff &handoff)
Handles health requests.
boost::asio::ip::address address_type
Definition: OverlayImpl.h:80
static bool is_upgrade(boost::beast::http::header< true, Fields > const &req)
Definition: OverlayImpl.h:319
std::condition_variable_any cond_
Definition: OverlayImpl.h:106
void onWrite(beast::PropertyStream::Map &stream) override
Subclass override.
Json::Value txMetrics() const override
Returns tx reduce-relay metrics.
Definition: OverlayImpl.h:425
void deleteIdlePeers()
Check if peers stopped relaying messages and if slots stopped receiving messages from the validator.
Resolver & m_resolver
Definition: OverlayImpl.h:117
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:115
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:112
std::shared_ptr< Message > manifestMessage_
Definition: OverlayImpl.h:130
std::optional< std::uint32_t > manifestListSeq_
Definition: OverlayImpl.h:132
OverlayImpl & operator=(OverlayImpl const &)=delete
TrafficCount m_traffic
Definition: OverlayImpl.h:114
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:124
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:118
void incPeerDisconnect() override
Increment and retrieve counters for total peer disconnects, and disconnects we initiate for excessive...
Definition: OverlayImpl.h:362
boost::asio::io_service & io_service_
Definition: OverlayImpl.h:102
void addTxMetrics(Args... args)
Add tx reduce-relay metrics.
Definition: OverlayImpl.h:433
Application & app_
Definition: OverlayImpl.h:101
std::optional< std::uint32_t > networkID() const override
Returns the ID of the network this server is configured for, if any.
Definition: OverlayImpl.h:386
std::weak_ptr< Timer > timer_
Definition: OverlayImpl.h:107
std::atomic< uint64_t > jqTransOverflow_
Definition: OverlayImpl.h:120
metrics::TxMetrics txMetrics_
Definition: OverlayImpl.h:127
void broadcast(protocol::TMProposeSet &m) override
Broadcast a proposal.
void onPeerDeactivate(Peer::id_t id)
std::mutex manifestLock_
Definition: OverlayImpl.h:134
bool processRequest(http_request_type const &req, Handoff &handoff)
Handles non-peer protocol requests.
std::recursive_mutex mutex_
Definition: OverlayImpl.h:105
std::uint64_t getPeerDisconnectCharges() const override
Definition: OverlayImpl.h:380
boost::asio::ip::tcp::socket socket_type
Definition: OverlayImpl.h:79
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:277
static bool isPeerUpgrade(boost::beast::http::response< Body > const &response)
Definition: OverlayImpl.h:309
std::optional< boost::asio::io_service::work > work_
Definition: OverlayImpl.h:103
OverlayImpl(OverlayImpl const &)=delete
Json::Value getOverlayInfo()
Returns information about peers on the overlay network.
Resource::Manager & resourceManager()
Definition: OverlayImpl.h:166
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:104
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:113
std::uint64_t getJqTransOverflow() const override
Definition: OverlayImpl.h:356
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:172
std::atomic< uint64_t > peerDisconnectsCharges_
Definition: OverlayImpl.h:122
std::shared_ptr< Message > getManifestsMessage()
hash_map< Peer::id_t, std::weak_ptr< PeerImp > > ids_
Definition: OverlayImpl.h:116
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:597
void checkTracking(std::uint32_t) override
Calls the checkTracking function on each peer.
void incPeerDisconnectCharges() override
Definition: OverlayImpl.h:374
ServerHandler & serverHandler_
Definition: OverlayImpl.h:111
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:333
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:350
beast::Journal const journal_
Definition: OverlayImpl.h:110
boost::container::flat_map< Child *, std::weak_ptr< Child > > list_
Definition: OverlayImpl.h:108
std::uint64_t getPeerDisconnect() const override
Definition: OverlayImpl.h:368
Manages the set of connected peers.
Definition: Overlay.h:48
std::vector< std::shared_ptr< Peer > > PeerSequence
Definition: Overlay.h:75
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:197
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:33
STL namespace.
T push_back(T... args)
T reserve(T... args)
Used to indicate the result of a server connection handoff.
Definition: Handoff.h:40
beast::insight::Gauge peerDisconnects
Definition: OverlayImpl.h:591
std::vector< TrafficGauges > trafficGauges
Definition: OverlayImpl.h:592
Stats(Handler const &handler, beast::insight::Collector::ptr const &collector, std::vector< TrafficGauges > &&trafficGauges_)
Definition: OverlayImpl.h:580
beast::insight::Hook hook
Definition: OverlayImpl.h:593
void on_timer(error_code ec)
Definition: OverlayImpl.cpp:91
boost::asio::basic_waitable_timer< clock_type > timer_
Definition: OverlayImpl.h:86
beast::insight::Gauge messagesIn
Definition: OverlayImpl.h:573
beast::insight::Gauge bytesIn
Definition: OverlayImpl.h:571
beast::insight::Gauge messagesOut
Definition: OverlayImpl.h:574
TrafficGauges(char const *name, beast::insight::Collector::ptr const &collector)
Definition: OverlayImpl.h:562
beast::insight::Gauge bytesOut
Definition: OverlayImpl.h:572
std::optional< std::uint32_t > networkID
Definition: Overlay.h:71
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