forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPeerManager.cpp
More file actions
657 lines (588 loc) · 17.4 KB
/
Copy pathPeerManager.cpp
File metadata and controls
657 lines (588 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "overlay/PeerManager.h"
#include "database/Database.h"
#include "lib/util/stdrandom.h"
#include "main/Application.h"
#include "overlay/RandomPeerSource.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/Math.h"
#include <Tracy.hpp>
#include <algorithm>
#include <cmath>
#include <fmt/format.h>
#include <regex>
#include <soci.h>
#include <vector>
namespace stellar
{
using namespace soci;
enum PeerRecordFlags
{
PEER_RECORD_FLAGS_PREFERRED = 1
};
bool
operator==(PeerRecord const& x, PeerRecord const& y)
{
if (VirtualClock::tmToSystemPoint(x.mNextAttempt) !=
VirtualClock::tmToSystemPoint(y.mNextAttempt))
{
return false;
}
if (x.mNumFailures != y.mNumFailures)
{
return false;
}
return x.mType == y.mType;
}
namespace
{
void
ipToXdr(std::string const& ip, xdr::opaque_array<4U>& ret)
{
std::stringstream ss(ip);
std::string item;
int n = 0;
while (getline(ss, item, '.') && n < 4)
{
ret[n] = static_cast<unsigned char>(atoi(item.c_str()));
n++;
}
if (n != 4)
throw std::runtime_error("ipToXdr: failed on `" + ip + "`");
}
}
PeerAddress
toXdr(PeerBareAddress const& address)
{
PeerAddress result;
result.port = address.getPort();
result.ip.type(IPv4);
ipToXdr(address.getIP(), result.ip.ipv4());
result.numFailures = 0;
return result;
}
constexpr size_t const BATCH_SIZE = 1000;
constexpr size_t const MAX_FAILURES = 10;
PeerManager::PeerManager(Application& app)
: mApp(app)
, mOutboundPeersToSend(std::make_unique<RandomPeerSource>(
*this, RandomPeerSource::maxFailures(MAX_FAILURES, true)))
, mInboundPeersToSend(std::make_unique<RandomPeerSource>(
*this, RandomPeerSource::maxFailures(MAX_FAILURES, false)))
{
}
std::vector<PeerBareAddress>
PeerManager::loadRandomPeers(PeerQuery const& query, size_t size)
{
ZoneScoped;
// BATCH_SIZE should always be bigger, so it should win anyway
size = std::max(size, BATCH_SIZE);
// if we ever start removing peers from db, we may need to enable this
// soci::transaction sqltx(mApp.getDatabase().getMiscSession());
// mApp.getDatabase().setCurrentTransactionReadOnly();
std::vector<std::string> conditions;
if (query.mUseNextAttempt)
{
conditions.push_back("nextattempt <= :nextattempt");
}
if (query.mMaxNumFailures.has_value())
{
conditions.push_back("numfailures <= :maxFailures");
}
if (query.mTypeFilter == PeerTypeFilter::ANY_OUTBOUND)
{
conditions.push_back("type != :inboundType");
}
else
{
conditions.push_back("type = :type");
}
releaseAssert(!conditions.empty());
std::string where = conditions[0];
for (size_t i = 1; i < conditions.size(); i++)
{
where += " AND " + conditions[i];
}
std::tm nextAttempt =
VirtualClock::systemPointToTm(mApp.getClock().system_now());
size_t maxNumFailures{0};
int exactType = static_cast<int>(query.mTypeFilter);
int inboundType = static_cast<int>(PeerType::INBOUND);
auto bindToStatement = [&](soci::statement& st) {
if (query.mUseNextAttempt)
{
st.exchange(soci::use(nextAttempt));
}
if (query.mMaxNumFailures.has_value())
{
maxNumFailures = *query.mMaxNumFailures;
st.exchange(soci::use(maxNumFailures));
}
if (query.mTypeFilter == PeerTypeFilter::ANY_OUTBOUND)
{
st.exchange(soci::use(inboundType));
}
else
{
st.exchange(soci::use(exactType));
}
};
auto result = std::vector<PeerBareAddress>{};
size_t count = countPeers(where, bindToStatement);
if (count == 0)
{
return result;
}
size_t maxOffset = count > size ? count - size : 0;
size_t offset = rand_uniform<size_t>(0, maxOffset);
result = loadPeers(size, offset, where, bindToStatement);
stellar::shuffle(std::begin(result), std::end(result),
getGlobalRandomEngine());
return result;
}
void
PeerManager::removePeersWithManyFailures(size_t minNumFailures,
PeerBareAddress const* address)
{
ZoneScoped;
releaseAssert(threadIsMain());
try
{
auto& db = mApp.getDatabase();
auto sql = std::string{
"DELETE FROM peers WHERE numfailures >= :minNumFailures"};
if (address)
{
sql += " AND ip = :ip";
}
auto prep =
db.getPreparedStatement(sql, mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
st.exchange(use(minNumFailures));
std::string ip;
if (address)
{
ip = address->getIP();
st.exchange(use(ip));
}
st.define_and_bind();
{
auto timer = db.getDeleteTimer("peer");
st.execute(true);
}
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay,
"PeerManager::removePeersWithManyFailures error: {}",
err.what());
}
}
std::vector<PeerBareAddress>
PeerManager::getPeersToSend(size_t size, PeerBareAddress const& address)
{
ZoneScoped;
bool allowPrivate = false;
#ifdef BUILD_TESTS
allowPrivate = mApp.getConfig().ALLOW_PRIVATE_ADDRESSES_FOR_TESTING;
#endif
auto keep = [&](PeerBareAddress const& pba) {
return (allowPrivate || !pba.isPrivate()) && pba != address;
};
auto peers = mOutboundPeersToSend->getRandomPeers(size, keep);
if (peers.size() < size)
{
auto inbound = mInboundPeersToSend->getRandomPeers(
size - static_cast<int>(peers.size()), keep);
std::copy(std::begin(inbound), std::end(inbound),
std::back_inserter(peers));
}
return peers;
}
std::pair<PeerRecord, bool>
PeerManager::load(PeerBareAddress const& address)
{
ZoneScoped;
auto result = PeerRecord{};
auto inDatabase = false;
try
{
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT numfailures, nextattempt, type FROM peers "
"WHERE ip = :v1 AND port = :v2",
mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
st.exchange(into(result.mNumFailures));
st.exchange(into(result.mNextAttempt));
st.exchange(into(result.mType));
std::string ip = address.getIP();
st.exchange(use(ip));
int port = address.getPort();
st.exchange(use(port));
st.define_and_bind();
{
auto timer = mApp.getDatabase().getSelectTimer("peer");
st.execute(true);
inDatabase = st.got_data();
if (!inDatabase)
{
result.mNextAttempt =
VirtualClock::systemPointToTm(mApp.getClock().system_now());
result.mType = static_cast<int>(PeerType::INBOUND);
}
}
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay, "PeerManager::load error: {} on {}", err.what(),
address.toString());
}
return std::make_pair(result, inDatabase);
}
void
PeerManager::store(PeerBareAddress const& address, PeerRecord const& peerRecord,
bool inDatabase)
{
ZoneScoped;
std::string query;
if (inDatabase)
{
query = "UPDATE peers SET "
"nextattempt = :v1, "
"numfailures = :v2, "
"type = :v3 "
"WHERE ip = :v4 AND port = :v5";
}
else
{
query = "INSERT INTO peers "
"(nextattempt, numfailures, type, ip, port) "
"VALUES "
"(:v1, :v2, :v3, :v4, :v5)";
}
try
{
auto prep = mApp.getDatabase().getPreparedStatement(
query, mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
st.exchange(use(peerRecord.mNextAttempt));
st.exchange(use(peerRecord.mNumFailures));
st.exchange(use(peerRecord.mType));
std::string ip = address.getIP();
st.exchange(use(ip));
int port = address.getPort();
st.exchange(use(port));
st.define_and_bind();
{
auto timer = mApp.getDatabase().getUpdateTimer("peer");
st.execute(true);
if (st.get_affected_rows() != 1)
{
CLOG_ERROR(Overlay, "PeerManager::store failed on {}",
address.toString());
}
}
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay, "PeerManager::store error: {} on {}", err.what(),
address.toString());
}
}
void
PeerManager::update(PeerRecord& peer, TypeUpdate type)
{
switch (type)
{
case TypeUpdate::ENSURE_OUTBOUND:
{
if (peer.mType == static_cast<int>(PeerType::INBOUND))
{
peer.mType = static_cast<int>(PeerType::OUTBOUND);
}
break;
}
case TypeUpdate::SET_PREFERRED:
{
peer.mType = static_cast<int>(PeerType::PREFERRED);
break;
}
case TypeUpdate::ENSURE_NOT_PREFERRED:
{
if (peer.mType == static_cast<int>(PeerType::PREFERRED))
{
peer.mType = static_cast<int>(PeerType::OUTBOUND);
}
break;
}
default:
{
throw std::runtime_error(
fmt::format("PeerManager::update: unsupported TypeUpdate: {}",
static_cast<int>(type)));
}
}
}
namespace
{
static std::chrono::seconds
computeBackoff(size_t numFailures)
{
constexpr uint32 const SECONDS_PER_BACKOFF = 10;
constexpr size_t const MAX_BACKOFF_EXPONENT = 10;
uint32 backoffCount = static_cast<uint32>(
std::min<size_t>(MAX_BACKOFF_EXPONENT, numFailures));
auto nsecs =
std::chrono::seconds(static_cast<uint32>(getGlobalRandomEngine()()) %
((1u << backoffCount) * SECONDS_PER_BACKOFF) +
1);
return nsecs;
}
}
void
PeerManager::update(PeerRecord& peer, BackOffUpdate backOff, Application& app)
{
switch (backOff)
{
case BackOffUpdate::HARD_RESET:
{
peer.mNumFailures = 0;
auto nextAttempt = app.getClock().system_now();
peer.mNextAttempt = VirtualClock::systemPointToTm(nextAttempt);
break;
}
case BackOffUpdate::RESET:
case BackOffUpdate::INCREASE:
{
peer.mNumFailures =
backOff == BackOffUpdate::RESET ? 0 : peer.mNumFailures + 1;
auto nextAttempt =
app.getClock().system_now() + computeBackoff(peer.mNumFailures);
peer.mNextAttempt = VirtualClock::systemPointToTm(nextAttempt);
break;
}
default:
{
throw std::runtime_error(
fmt::format("PeerManager::update: unsupported BackOffUpdate: {}",
static_cast<int>(backOff)));
}
}
}
void
PeerManager::ensureExists(PeerBareAddress const& address)
{
ZoneScoped;
auto peer = load(address);
if (!peer.second)
{
CLOG_TRACE(Overlay, "Learned peer {}", address.toString());
store(address, peer.first, peer.second);
}
}
static PeerManager::TypeUpdate
getTypeUpdate(PeerRecord const& peer, PeerType observedType,
bool preferredTypeKnown)
{
PeerManager::TypeUpdate typeUpdate;
bool isPreferredInDB = peer.mType == static_cast<int>(PeerType::PREFERRED);
switch (observedType)
{
case PeerType::PREFERRED:
{
// Always update to preferred
typeUpdate = PeerManager::TypeUpdate::SET_PREFERRED;
break;
}
case PeerType::OUTBOUND:
{
if (isPreferredInDB && preferredTypeKnown)
{
// Downgrade to outbound if peer is definitely not preferred
typeUpdate = PeerManager::TypeUpdate::ENSURE_NOT_PREFERRED;
}
else
{
// Maybe upgrade to outbound, or keep preferred
typeUpdate = PeerManager::TypeUpdate::ENSURE_OUTBOUND;
}
break;
}
case PeerType::INBOUND:
{
// Either keep inbound type, or downgrade preferred to outbound
typeUpdate = PeerManager::TypeUpdate::ENSURE_NOT_PREFERRED;
break;
}
default:
{
throw std::runtime_error(
fmt::format("PeerManager::getTypeUpdate: unsupported PeerType: {}",
static_cast<int>(observedType)));
}
}
return typeUpdate;
}
void
PeerManager::update(PeerBareAddress const& address, PeerType observedType,
bool preferredTypeKnown)
{
ZoneScoped;
auto peer = load(address);
TypeUpdate typeUpdate =
getTypeUpdate(peer.first, observedType, preferredTypeKnown);
update(peer.first, typeUpdate);
store(address, peer.first, peer.second);
}
void
PeerManager::update(PeerBareAddress const& address, BackOffUpdate backOff)
{
ZoneScoped;
auto peer = load(address);
update(peer.first, backOff, mApp);
store(address, peer.first, peer.second);
}
void
PeerManager::update(PeerBareAddress const& address, PeerType observedType,
bool preferredTypeKnown, BackOffUpdate backOff)
{
ZoneScoped;
auto peer = load(address);
TypeUpdate typeUpdate =
getTypeUpdate(peer.first, observedType, preferredTypeKnown);
update(peer.first, typeUpdate);
update(peer.first, backOff, mApp);
store(address, peer.first, peer.second);
}
size_t
PeerManager::countPeers(std::string const& where,
std::function<void(soci::statement&)> const& bind)
{
ZoneScoped;
size_t count = 0;
try
{
std::string sql = "SELECT COUNT(*) FROM peers WHERE " + where;
auto prep = mApp.getDatabase().getPreparedStatement(
sql, mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
bind(st);
st.exchange(into(count));
st.define_and_bind();
st.execute(true);
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay, "countPeers error: {}", err.what());
}
return count;
}
std::vector<PeerBareAddress>
PeerManager::loadPeers(size_t limit, size_t offset, std::string const& where,
std::function<void(soci::statement&)> const& bind)
{
ZoneScoped;
auto result = std::vector<PeerBareAddress>{};
try
{
std::string sql = "SELECT ip, port "
"FROM peers WHERE " +
where + " LIMIT :limit OFFSET :offset";
auto prep = mApp.getDatabase().getPreparedStatement(
sql, mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
bind(st);
st.exchange(use(limit));
st.exchange(use(offset));
std::string ip;
int lport;
st.exchange(into(ip));
st.exchange(into(lport));
st.define_and_bind();
{
auto timer = mApp.getDatabase().getSelectTimer("peer");
st.execute(true);
}
while (st.got_data())
{
if (!ip.empty() && lport > 0)
{
result.emplace_back(ip, static_cast<unsigned short>(lport));
}
st.fetch();
}
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay, "loadPeers error: {}", err.what());
}
return result;
}
void
PeerManager::maybeDropAndCreateNew(SessionWrapper& db)
{
db.session() << "DROP TABLE IF EXISTS peers;";
db.session() << kSQLCreateStatement;
}
std::vector<std::pair<PeerBareAddress, PeerRecord>>
PeerManager::loadAllPeers()
{
ZoneScoped;
std::vector<std::pair<PeerBareAddress, PeerRecord>> result;
std::string sql =
"SELECT ip, port, nextattempt, numfailures, type FROM peers";
try
{
std::string ip;
int port;
PeerRecord record;
auto prep = mApp.getDatabase().getPreparedStatement(
sql, mApp.getDatabase().getMiscSession());
auto& st = prep.statement();
st.exchange(into(ip));
st.exchange(into(port));
st.exchange(into(record.mNextAttempt));
st.exchange(into(record.mNumFailures));
st.exchange(into(record.mType));
st.define_and_bind();
{
auto timer = mApp.getDatabase().getSelectTimer("peer");
st.execute(true);
}
while (st.got_data())
{
PeerBareAddress pba{ip, static_cast<unsigned short>(port)};
result.emplace_back(std::make_pair(pba, record));
st.fetch();
}
}
catch (soci_error& err)
{
CLOG_ERROR(Overlay, "loadPeers error: {}", err.what());
}
return result;
}
void
PeerManager::storePeers(
std::vector<std::pair<PeerBareAddress, PeerRecord>> peers)
{
soci::transaction tx(mApp.getDatabase().getRawMiscSession());
for (auto const& peer : peers)
{
store(peer.first, peer.second, /* inDatabase */ false);
}
tx.commit();
}
char const* PeerManager::kSQLCreateStatement =
"CREATE TABLE peers ("
"ip VARCHAR(15) NOT NULL,"
"port INT DEFAULT 0 CHECK (port > 0 AND port <= 65535) NOT NULL,"
"nextattempt TIMESTAMP NOT NULL,"
"numfailures INT DEFAULT 0 CHECK (numfailures >= 0) NOT NULL,"
"type INT NOT NULL,"
"PRIMARY KEY (ip, port)"
");";
}