forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHistoryManagerImpl.cpp
446 lines (398 loc) · 12.1 KB
/
HistoryManagerImpl.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
// Copyright 2014-2015 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
// ASIO is somewhat particular about when it gets included -- it wants to be the
// first to include <windows.h> -- so we try to include it before everything
// else.
#include "util/asio.h"
#include "bucket/BucketList.h"
#include "bucket/BucketManager.h"
#include "crypto/Hex.h"
#include "crypto/SHA.h"
#include "herder/HerderImpl.h"
#include "history/HistoryArchive.h"
#include "history/HistoryArchiveManager.h"
#include "history/HistoryManagerImpl.h"
#include "history/StateSnapshot.h"
#include "historywork/FetchRecentQsetsWork.h"
#include "historywork/PublishWork.h"
#include "historywork/PutSnapshotFilesWork.h"
#include "historywork/RepairMissingBucketsWork.h"
#include "historywork/ResolveSnapshotWork.h"
#include "historywork/WriteSnapshotWork.h"
#include "ledger/LedgerManager.h"
#include "lib/util/format.h"
#include "main/Application.h"
#include "main/Config.h"
#include "medida/meter.h"
#include "medida/metrics_registry.h"
#include "overlay/StellarXDR.h"
#include "process/ProcessManager.h"
#include "util/Logging.h"
#include "util/Math.h"
#include "util/StatusManager.h"
#include "util/TmpDir.h"
#include "work/WorkScheduler.h"
#include "xdrpp/marshal.h"
#include <fstream>
#include <system_error>
namespace stellar
{
using namespace std;
static string kSQLCreateStatement = "CREATE TABLE IF NOT EXISTS publishqueue ("
"ledger INTEGER PRIMARY KEY,"
"state TEXT"
"); ";
void
HistoryManager::dropAll(Database& db)
{
db.getSession() << "DROP TABLE IF EXISTS publishqueue;";
soci::statement st = db.getSession().prepare << kSQLCreateStatement;
st.execute(true);
}
std::unique_ptr<HistoryManager>
HistoryManager::create(Application& app)
{
return std::make_unique<HistoryManagerImpl>(app);
}
HistoryManagerImpl::HistoryManagerImpl(Application& app)
: mApp(app)
, mWorkDir(nullptr)
, mPublishWork(nullptr)
, mPublishSuccess(
app.getMetrics().NewMeter({"history", "publish", "success"}, "event"))
, mPublishFailure(
app.getMetrics().NewMeter({"history", "publish", "failure"}, "event"))
{
}
HistoryManagerImpl::~HistoryManagerImpl()
{
}
uint32_t
HistoryManagerImpl::getCheckpointFrequency() const
{
if (mApp.getConfig().ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING)
{
return 8;
}
else
{
return 64;
}
}
uint32_t
HistoryManagerImpl::checkpointContainingLedger(uint32_t ledger) const
{
return nextCheckpointLedger(ledger + 1) - 1;
}
uint32_t
HistoryManagerImpl::prevCheckpointLedger(uint32_t ledger) const
{
uint32_t freq = getCheckpointFrequency();
return (ledger / freq) * freq;
}
uint32_t
HistoryManagerImpl::nextCheckpointLedger(uint32_t ledger) const
{
uint32_t freq = getCheckpointFrequency();
if (ledger == 0)
return freq;
return (((ledger + freq - 1) / freq) * freq);
}
void
HistoryManagerImpl::logAndUpdatePublishStatus()
{
std::stringstream stateStr;
if (mPublishWork)
{
auto qlen = publishQueueLength();
stateStr << "Publishing " << qlen << " queued checkpoints"
<< " [" << getMinLedgerQueuedToPublish() << "-"
<< getMaxLedgerQueuedToPublish() << "]"
<< ": " << mPublishWork->getStatus();
auto current = stateStr.str();
auto existing = mApp.getStatusManager().getStatusMessage(
StatusCategory::HISTORY_PUBLISH);
if (existing != current)
{
CLOG(INFO, "History") << current;
mApp.getStatusManager().setStatusMessage(
StatusCategory::HISTORY_PUBLISH, current);
}
}
else
{
mApp.getStatusManager().removeStatusMessage(
StatusCategory::HISTORY_PUBLISH);
}
}
size_t
HistoryManagerImpl::publishQueueLength() const
{
uint32_t count;
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT count(ledger) FROM publishqueue;");
auto& st = prep.statement();
st.exchange(soci::into(count));
st.define_and_bind();
st.execute(true);
return count;
}
string const&
HistoryManagerImpl::getTmpDir()
{
if (!mWorkDir)
{
TmpDir t = mApp.getTmpDirManager().tmpDir("history");
mWorkDir = std::make_unique<TmpDir>(std::move(t));
}
return mWorkDir->getName();
}
std::string
HistoryManagerImpl::localFilename(std::string const& basename)
{
return this->getTmpDir() + "/" + basename;
}
HistoryArchiveState
HistoryManagerImpl::getLastClosedHistoryArchiveState() const
{
auto seq = mApp.getLedgerManager().getLastClosedLedgerNum();
auto& bl = mApp.getBucketManager().getBucketList();
return HistoryArchiveState(seq, bl);
}
InferredQuorum
HistoryManagerImpl::inferQuorum(uint32_t ledgerNum)
{
InferredQuorum iq;
CLOG(INFO, "History") << "Starting FetchRecentQsetsWork";
mApp.getWorkScheduler().executeWork<FetchRecentQsetsWork>(iq, ledgerNum);
return iq;
}
uint32_t
HistoryManagerImpl::getMinLedgerQueuedToPublish()
{
uint32_t seq;
soci::indicator minIndicator;
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT min(ledger) FROM publishqueue;");
auto& st = prep.statement();
st.exchange(soci::into(seq, minIndicator));
st.define_and_bind();
st.execute(true);
if (minIndicator == soci::indicator::i_ok)
{
return seq;
}
return 0;
}
uint32_t
HistoryManagerImpl::getMaxLedgerQueuedToPublish()
{
uint32_t seq;
soci::indicator maxIndicator;
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT max(ledger) FROM publishqueue;");
auto& st = prep.statement();
st.exchange(soci::into(seq, maxIndicator));
st.define_and_bind();
st.execute(true);
if (maxIndicator == soci::indicator::i_ok)
{
return seq;
}
return 0;
}
bool
HistoryManagerImpl::maybeQueueHistoryCheckpoint()
{
uint32_t seq = mApp.getLedgerManager().getLastClosedLedgerNum() + 1;
if (seq != nextCheckpointLedger(seq))
{
return false;
}
if (!mApp.getHistoryArchiveManager().hasAnyWritableHistoryArchive())
{
CLOG(DEBUG, "History")
<< "Skipping checkpoint, no writable history archives";
return false;
}
queueCurrentHistory();
return true;
}
void
HistoryManagerImpl::queueCurrentHistory()
{
auto has = getLastClosedHistoryArchiveState();
auto ledger = has.currentLedger;
CLOG(DEBUG, "History") << "Queueing publish state for ledger " << ledger;
auto state = has.toString();
auto timer = mApp.getDatabase().getInsertTimer("publishqueue");
auto prep = mApp.getDatabase().getPreparedStatement(
"INSERT INTO publishqueue (ledger, state) VALUES (:lg, :st);");
auto& st = prep.statement();
st.exchange(soci::use(ledger));
st.exchange(soci::use(state));
st.define_and_bind();
st.execute(true);
// We have now written the current HAS to the database, so
// it's "safe" to crash (at least after the enclosing tx commits);
// but that HAS might have merges running and if we throw it
// away at this point we'll lose the merges and have to restart
// them. So instead we're going to insert the HAS we have in hand
// into the in-memory publish queue in order to preserve those
// merges-in-progress, avoid restarting them.
mPublishQueued++;
mPublishQueueBuckets.addBuckets(has.allBuckets());
}
void
HistoryManagerImpl::takeSnapshotAndPublish(HistoryArchiveState const& has)
{
if (mPublishWork)
{
return;
}
auto ledgerSeq = has.currentLedger;
CLOG(DEBUG, "History") << "Activating publish for ledger " << ledgerSeq;
auto snap = std::make_shared<StateSnapshot>(mApp, has);
// Phase 1: resolve futures in snapshot
auto resolveFutures = std::make_shared<ResolveSnapshotWork>(mApp, snap);
// Phase 2: write snapshot files
auto writeSnap = std::make_shared<WriteSnapshotWork>(mApp, snap);
// Phase 3: update archives
auto putSnap = std::make_shared<PutSnapshotFilesWork>(mApp, snap);
std::vector<std::shared_ptr<BasicWork>> seq{resolveFutures, writeSnap,
putSnap};
mPublishWork = mApp.getWorkScheduler().scheduleWork<PublishWork>(snap, seq);
}
size_t
HistoryManagerImpl::publishQueuedHistory()
{
std::string state;
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT state FROM publishqueue"
" ORDER BY ledger ASC LIMIT 1;");
auto& st = prep.statement();
soci::indicator stateIndicator;
st.exchange(soci::into(state, stateIndicator));
st.define_and_bind();
st.execute(true);
if (st.got_data() && stateIndicator == soci::indicator::i_ok)
{
HistoryArchiveState has;
has.fromString(state);
takeSnapshotAndPublish(has);
return 1;
}
return 0;
}
std::vector<HistoryArchiveState>
HistoryManagerImpl::getPublishQueueStates()
{
std::vector<HistoryArchiveState> states;
std::string state;
auto prep = mApp.getDatabase().getPreparedStatement(
"SELECT state FROM publishqueue;");
auto& st = prep.statement();
st.exchange(soci::into(state));
st.define_and_bind();
st.execute(true);
while (st.got_data())
{
states.emplace_back();
states.back().fromString(state);
st.fetch();
}
return states;
}
PublishQueueBuckets::BucketCount
HistoryManagerImpl::loadBucketsReferencedByPublishQueue()
{
auto states = getPublishQueueStates();
PublishQueueBuckets::BucketCount result{};
for (auto const& s : states)
{
auto sb = s.allBuckets();
for (auto const& b : sb)
{
result[b]++;
}
}
return result;
}
std::vector<std::string>
HistoryManagerImpl::getBucketsReferencedByPublishQueue()
{
if (!mPublishQueueBucketsFilled)
{
mPublishQueueBuckets.setBuckets(loadBucketsReferencedByPublishQueue());
mPublishQueueBucketsFilled = true;
}
std::vector<std::string> buckets;
for (auto const& s : mPublishQueueBuckets.map())
{
buckets.push_back(s.first);
}
return buckets;
}
std::vector<std::string>
HistoryManagerImpl::getMissingBucketsReferencedByPublishQueue()
{
auto states = getPublishQueueStates();
std::set<std::string> buckets;
for (auto const& s : states)
{
auto sb = mApp.getBucketManager().checkForMissingBucketsFiles(s);
buckets.insert(sb.begin(), sb.end());
}
return std::vector<std::string>(buckets.begin(), buckets.end());
}
void
HistoryManagerImpl::historyPublished(
uint32_t ledgerSeq, std::vector<std::string> const& originalBuckets,
bool success)
{
if (success)
{
this->mPublishSuccess.Mark();
auto timer = mApp.getDatabase().getDeleteTimer("publishqueue");
auto prep = mApp.getDatabase().getPreparedStatement(
"DELETE FROM publishqueue WHERE ledger = :lg;");
auto& st = prep.statement();
st.exchange(soci::use(ledgerSeq));
st.define_and_bind();
st.execute(true);
mPublishQueueBuckets.removeBuckets(originalBuckets);
}
else
{
this->mPublishFailure.Mark();
}
mPublishWork.reset();
mApp.postOnMainThread([this]() { this->publishQueuedHistory(); },
"HistoryManagerImpl: publishQueuedHistory");
}
void
HistoryManagerImpl::downloadMissingBuckets(
HistoryArchiveState desiredState,
std::function<void(asio::error_code const& ec)> handler)
{
CLOG(INFO, "History") << "Starting RepairMissingBucketsWork";
mApp.getWorkScheduler().scheduleWork<RepairMissingBucketsWork>(desiredState,
handler);
}
uint64_t
HistoryManagerImpl::getPublishQueueCount()
{
return mPublishQueued;
}
uint64_t
HistoryManagerImpl::getPublishSuccessCount()
{
return mPublishSuccess.count();
}
uint64_t
HistoryManagerImpl::getPublishFailureCount()
{
return mPublishFailure.count();
}
}