forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPeerManager.cpp
523 lines (463 loc) · 13.3 KB
/
PeerManager.cpp
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
// 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 "crypto/Random.h"
#include "database/Database.h"
#include "main/Application.h"
#include "overlay/RandomPeerSource.h"
#include "overlay/StellarXDR.h"
#include "util/Logging.h"
#include "util/Math.h"
#include "util/must_use.h"
#include <algorithm>
#include <cmath>
#include <lib/util/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::tmToPoint(x.mNextAttempt) !=
VirtualClock::tmToPoint(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 const auto BATCH_SIZE = 1000;
constexpr const auto 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, int size)
{
// 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().getSession());
// mApp.getDatabase().setCurrentTransactionReadOnly();
std::vector<std::string> conditions;
if (query.mUseNextAttempt)
{
conditions.push_back("nextattempt <= :nextattempt");
}
if (query.mMaxNumFailures >= 0)
{
conditions.push_back("numfailures <= :maxFailures");
}
if (query.mTypeFilter == PeerTypeFilter::ANY_OUTBOUND)
{
conditions.push_back("type != :inboundType");
}
else
{
conditions.push_back("type = :type");
}
assert(!conditions.empty());
std::string where = conditions[0];
for (auto i = 1; i < conditions.size(); i++)
{
where += " AND " + conditions[i];
}
std::tm nextAttempt = VirtualClock::pointToTm(mApp.getClock().now());
int maxNumFailures = query.mMaxNumFailures;
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 >= 0)
{
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>{};
auto count = countPeers(where, bindToStatement);
if (count == 0)
{
return result;
}
auto maxOffset = count > size ? count - size : 0;
auto offset = rand_uniform<int>(0, maxOffset);
result = loadPeers(size, offset, where, bindToStatement);
std::shuffle(std::begin(result), std::end(result), gRandomEngine);
return result;
}
void
PeerManager::removePeersWithManyFailures(int minNumFailures,
PeerBareAddress const* address)
{
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);
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(int size, PeerBareAddress const& address)
{
auto keep = [&](PeerBareAddress const& pba) {
return !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)
{
auto result = PeerRecord{};
auto inDatabase = false;
try
{
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT numfailures, nextattempt, type FROM peers "
"WHERE ip = :v1 AND port = :v2");
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::pointToTm(mApp.getClock().now());
result.mType = static_cast<int>(PeerType::INBOUND);
}
}
}
catch (soci_error& err)
{
CLOG(ERROR, "Overlay") << "PeerManager::load error: " << err.what()
<< " on " << address.toString();
}
return std::make_pair(result, inDatabase);
}
void
PeerManager::store(PeerBareAddress const& address, PeerRecord const& peerRecord,
bool inDatabase)
{
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);
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: " << err.what()
<< " on " << address.toString();
}
}
void
PeerManager::update(PeerRecord& peer, TypeUpdate type)
{
switch (type)
{
case TypeUpdate::SET_OUTBOUND:
{
peer.mType = static_cast<int>(PeerType::OUTBOUND);
break;
}
case TypeUpdate::SET_PREFERRED:
{
peer.mType = static_cast<int>(PeerType::PREFERRED);
break;
}
case TypeUpdate::REMOVE_PREFERRED:
{
if (peer.mType == static_cast<int>(PeerType::PREFERRED))
{
peer.mType = static_cast<int>(PeerType::OUTBOUND);
}
break;
}
case TypeUpdate::UPDATE_TO_OUTBOUND:
{
if (peer.mType == static_cast<int>(PeerType::INBOUND))
{
peer.mType = static_cast<int>(PeerType::OUTBOUND);
}
break;
}
default:
{
abort();
}
}
}
namespace
{
static std::chrono::seconds
computeBackoff(int numFailures)
{
constexpr const auto SECONDS_PER_BACKOFF = 10;
constexpr const auto MAX_BACKOFF_EXPONENT = 10;
auto backoffCount = std::min<int32_t>(MAX_BACKOFF_EXPONENT, numFailures);
auto nsecs = std::chrono::seconds(
std::rand() % int(std::pow(2, 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().now();
peer.mNextAttempt = VirtualClock::pointToTm(nextAttempt);
break;
}
case BackOffUpdate::RESET:
case BackOffUpdate::INCREASE:
{
peer.mNumFailures =
backOff == BackOffUpdate::RESET ? 0 : peer.mNumFailures + 1;
auto nextAttempt =
app.getClock().now() + computeBackoff(peer.mNumFailures);
peer.mNextAttempt = VirtualClock::pointToTm(nextAttempt);
break;
}
default:
{
abort();
}
}
}
void
PeerManager::ensureExists(PeerBareAddress const& address)
{
auto peer = load(address);
if (!peer.second)
{
store(address, peer.first, peer.second);
}
}
void
PeerManager::update(PeerBareAddress const& address, TypeUpdate type)
{
auto peer = load(address);
update(peer.first, type);
store(address, peer.first, peer.second);
}
void
PeerManager::update(PeerBareAddress const& address, BackOffUpdate backOff)
{
auto peer = load(address);
update(peer.first, backOff, mApp);
store(address, peer.first, peer.second);
}
void
PeerManager::update(PeerBareAddress const& address, TypeUpdate type,
BackOffUpdate backOff)
{
auto peer = load(address);
update(peer.first, type);
update(peer.first, backOff, mApp);
store(address, peer.first, peer.second);
}
int
PeerManager::countPeers(std::string const& where,
std::function<void(soci::statement&)> const& bind)
{
int count = 0;
try
{
std::string sql = "SELECT COUNT(*) FROM peers WHERE " + where;
auto prep = mApp.getDatabase().getPreparedStatement(sql);
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(int limit, int offset, std::string const& where,
std::function<void(soci::statement&)> const& bind)
{
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);
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::dropAll(Database& db)
{
db.getSession() << "DROP TABLE IF EXISTS peers;";
db.getSession() << kSQLCreateStatement;
}
const char* 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,"
"flags INT NOT NULL,"
"PRIMARY KEY (ip, port)"
");";
}