forked from stellar/go
/
main.go
587 lines (513 loc) · 18.4 KB
/
main.go
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
// Package ingest contains the new ingestion system for horizon.
// It currently runs completely independent of the old one, that means
// that the new system can be ledgers behind/ahead the old system.
package ingest
import (
"context"
"fmt"
"net/http"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/stellar/go/clients/stellarcore"
"github.com/stellar/go/historyarchive"
"github.com/stellar/go/ingest"
"github.com/stellar/go/ingest/ledgerbackend"
"github.com/stellar/go/services/horizon/internal/db2/history"
"github.com/stellar/go/support/db"
"github.com/stellar/go/support/errors"
logpkg "github.com/stellar/go/support/log"
)
const (
// MaxSupportedProtocolVersion defines the maximum supported version of
// the Stellar protocol.
MaxSupportedProtocolVersion = 16
// CurrentVersion reflects the latest version of the ingestion
// algorithm. This value is stored in KV store and is used to decide
// if there's a need to reprocess the ledger state or reingest data.
//
// Version history:
// - 1: Initial version
// - 2: Added the orderbook, offers processors and distributed ingestion.
// - 3: Fixed a bug that could potentialy result in invalid state
// (#1722). Update the version to clear the state.
// - 4: Fixed a bug in AccountSignersChanged method.
// - 5: Added trust lines.
// - 6: Added accounts and accounts data.
// - 7: Fixes a bug in AccountSignersChanged method.
// - 8: Fixes AccountSigners processor to remove preauth tx signer
// when preauth tx is failed.
// - 9: Fixes a bug in asset stats processor that counted unauthorized
// trustlines.
// - 10: Fixes a bug in meta processing (fees are now processed before
// everything else).
// - 11: Protocol 14: CAP-23 and CAP-33.
// - 12: Trigger state rebuild due to `absTime` -> `abs_time` rename
// in ClaimableBalances predicates.
// - 13: Trigger state rebuild to include more than just authorized assets.
// - 14: Trigger state rebuild to include claimable balances in the asset stats processor.
CurrentVersion = 14
// MaxDBConnections is the size of the postgres connection pool dedicated to Horizon ingestion:
// * Ledger ingestion,
// * State verifications,
// * Metrics updates.
MaxDBConnections = 3
defaultCoreCursorName = "HORIZON"
stateVerificationErrorThreshold = 3
)
var log = logpkg.DefaultLogger.WithField("service", "ingest")
type Config struct {
CoreSession *db.Session
StellarCoreURL string
StellarCoreCursor string
EnableCaptiveCore bool
CaptiveCoreBinaryPath string
CaptiveCoreStoragePath string
CaptiveCoreConfigAppendPath string
CaptiveCoreHTTPPort uint
CaptiveCorePeerPort uint
CaptiveCoreLogPath string
RemoteCaptiveCoreURL string
NetworkPassphrase string
HistorySession *db.Session
HistoryArchiveURL string
DisableStateVerification bool
MaxReingestRetries int
ReingestRetryBackoffSeconds int
// The checkpoint frequency will be 64 unless you are using an exotic test setup.
CheckpointFrequency uint32
}
const (
getLastIngestedErrMsg string = "Error getting last ingested ledger"
getIngestVersionErrMsg string = "Error getting ingestion version"
updateLastLedgerIngestErrMsg string = "Error updating last ingested ledger"
commitErrMsg string = "Error committing db transaction"
updateExpStateInvalidErrMsg string = "Error updating state invalid value"
)
type stellarCoreClient interface {
SetCursor(ctx context.Context, id string, cursor int32) error
}
type Metrics struct {
// LocalLedger exposes the last ingested ledger by this ingesting instance.
LocalLatestLedger prometheus.Gauge
// LedgerIngestionDuration exposes timing metrics about the rate and
// duration of ledger ingestion (including updating DB and graph).
LedgerIngestionDuration prometheus.Summary
// StateVerifyDuration exposes timing metrics about the rate and
// duration of state verification.
StateVerifyDuration prometheus.Summary
// StateInvalidGauge exposes state invalid metric. 1 if state is invalid,
// 0 otherwise.
StateInvalidGauge prometheus.GaugeFunc
// LedgerStatsCounter exposes ledger stats counters (like number of ops/changes).
LedgerStatsCounter *prometheus.CounterVec
// ProcessorsRunDuration exposes processors run durations.
ProcessorsRunDuration *prometheus.CounterVec
// CaptiveStellarCoreSynced exposes synced status of Captive Stellar-Core.
// 1 if sync, 0 if not synced, -1 if unable to connect or HTTP server disabled.
CaptiveStellarCoreSynced prometheus.GaugeFunc
}
type System interface {
Run()
Metrics() Metrics
StressTest(numTransactions, changesPerTransaction int) error
VerifyRange(fromLedger, toLedger uint32, verifyState bool) error
ReingestRange(fromLedger, toLedger uint32, force bool) error
BuildGenesisState() error
Shutdown()
}
type system struct {
metrics Metrics
ctx context.Context
cancel context.CancelFunc
config Config
historyQ history.IngestionQ
runner ProcessorRunnerInterface
ledgerBackend ledgerbackend.LedgerBackend
historyAdapter historyArchiveAdapterInterface
stellarCoreClient stellarCoreClient
maxReingestRetries int
reingestRetryBackoffSeconds int
wg sync.WaitGroup
// stateVerificationRunning is true when verification routine is currently
// running.
stateVerificationMutex sync.Mutex
// number of consecutive state verification runs which encountered errors
stateVerificationErrors int
stateVerificationRunning bool
disableStateVerification bool
checkpointManager historyarchive.CheckpointManager
}
func NewSystem(config Config) (System, error) {
ctx, cancel := context.WithCancel(context.Background())
archive, err := historyarchive.Connect(
config.HistoryArchiveURL,
historyarchive.ConnectOptions{
Context: ctx,
NetworkPassphrase: config.NetworkPassphrase,
CheckpointFrequency: config.CheckpointFrequency,
},
)
if err != nil {
cancel()
return nil, errors.Wrap(err, "error creating history archive")
}
var ledgerBackend ledgerbackend.LedgerBackend
if config.EnableCaptiveCore {
if len(config.RemoteCaptiveCoreURL) > 0 {
ledgerBackend, err = ledgerbackend.NewRemoteCaptive(config.RemoteCaptiveCoreURL)
if err != nil {
cancel()
return nil, errors.Wrap(err, "error creating captive core backend")
}
} else {
logger := log.WithField("subservice", "stellar-core")
ledgerBackend, err = ledgerbackend.NewCaptive(
ledgerbackend.CaptiveCoreConfig{
LogPath: config.CaptiveCoreLogPath,
BinaryPath: config.CaptiveCoreBinaryPath,
StoragePath: config.CaptiveCoreStoragePath,
ConfigAppendPath: config.CaptiveCoreConfigAppendPath,
HTTPPort: config.CaptiveCoreHTTPPort,
PeerPort: config.CaptiveCorePeerPort,
NetworkPassphrase: config.NetworkPassphrase,
HistoryArchiveURLs: []string{config.HistoryArchiveURL},
CheckpointFrequency: config.CheckpointFrequency,
LedgerHashStore: ledgerbackend.NewHorizonDBLedgerHashStore(config.HistorySession),
Log: logger,
Context: ctx,
},
)
if err != nil {
cancel()
return nil, errors.Wrap(err, "error creating captive core backend")
}
}
} else {
coreSession := config.CoreSession.Clone()
coreSession.Ctx = ctx
ledgerBackend, err = ledgerbackend.NewDatabaseBackendFromSession(coreSession, config.NetworkPassphrase)
if err != nil {
cancel()
return nil, errors.Wrap(err, "error creating ledger backend")
}
}
historyQ := &history.Q{config.HistorySession.Clone()}
historyQ.Ctx = ctx
historyAdapter := newHistoryArchiveAdapter(archive)
system := &system{
cancel: cancel,
config: config,
ctx: ctx,
disableStateVerification: config.DisableStateVerification,
historyAdapter: historyAdapter,
historyQ: historyQ,
ledgerBackend: ledgerBackend,
maxReingestRetries: config.MaxReingestRetries,
reingestRetryBackoffSeconds: config.ReingestRetryBackoffSeconds,
stellarCoreClient: &stellarcore.Client{
URL: config.StellarCoreURL,
},
runner: &ProcessorRunner{
ctx: ctx,
config: config,
historyQ: historyQ,
historyAdapter: historyAdapter,
ledgerBackend: ledgerBackend,
},
checkpointManager: historyarchive.NewCheckpointManager(config.CheckpointFrequency),
}
system.initMetrics()
return system, nil
}
func (s *system) initMetrics() {
s.metrics.LocalLatestLedger = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "local_latest_ledger",
Help: "sequence number of the latest ledger ingested by this ingesting instance",
})
s.metrics.LedgerIngestionDuration = prometheus.NewSummary(prometheus.SummaryOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "ledger_ingestion_duration_seconds",
Help: "ledger ingestion durations, sliding window = 10m",
})
s.metrics.StateVerifyDuration = prometheus.NewSummary(prometheus.SummaryOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "state_verify_duration_seconds",
Help: "state verification durations, sliding window = 10m",
})
s.metrics.StateInvalidGauge = prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "state_invalid",
Help: "equals 1 if state invalid, 0 otherwise",
},
func() float64 {
invalid, err := s.historyQ.CloneIngestionQ().GetExpStateInvalid()
if err != nil {
log.WithError(err).Error("Error in initMetrics/GetExpStateInvalid")
return 0
}
invalidFloat := float64(0)
if invalid {
invalidFloat = 1
}
return invalidFloat
},
)
s.metrics.LedgerStatsCounter = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "ledger_stats_total",
Help: "counters of different ledger stats",
},
[]string{"type"},
)
s.metrics.ProcessorsRunDuration = prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "processor_run_duration_seconds_total",
Help: "run durations of ingestion processors",
},
[]string{"name"},
)
s.metrics.CaptiveStellarCoreSynced = prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: "horizon", Subsystem: "ingest", Name: "captive_stellar_core_synced",
Help: "1 if sync, 0 if not synced, -1 if unable to connect or HTTP server disabled.",
},
func() float64 {
if !s.config.EnableCaptiveCore || s.config.CaptiveCoreHTTPPort == 0 {
return -1
}
client := stellarcore.Client{
HTTP: &http.Client{
Timeout: 2 * time.Second,
},
URL: fmt.Sprintf("http://localhost:%d", s.config.CaptiveCoreHTTPPort),
}
info, err := client.Info(s.ctx)
if err != nil {
log.WithError(err).Error("Cannot connect to Captive Stellar-Core HTTP server")
return -1
}
if info.IsSynced() {
return 1
} else {
return 0
}
},
)
}
func (s *system) Metrics() Metrics {
return s.metrics
}
// Run starts ingestion system. Ingestion system supports distributed ingestion
// that means that Horizon ingestion can be running on multiple machines and
// only one, random node will lead the ingestion.
//
// It needs to support cartesian product of the following run scenarios cases:
// - Init from empty state (1a) and resuming from existing state (1b).
// - Ingestion system version has been upgraded (2a) or not (2b).
// - Current node is leading ingestion (3a) or not (3b).
//
// We always clear state when ingestion system is upgraded so 2a and 2b are
// included in 1a.
//
// We ensure that only one instance is a leader because in each round instances
// try to acquire a lock on `LastLedgerIngest value in key value store and only
// one instance will be able to acquire it. This happens in both initial processing
// and ledger processing. So this solves 3a and 3b in both 1a and 1b.
//
// Finally, 1a and 1b are tricky because we need to keep the latest version
// of order book graph in memory of each Horizon instance. To solve this:
// * For state init:
// * If instance is a leader, we update the order book graph by running state
// pipeline normally.
// * If instance is NOT a leader, we build a graph from offers present in a
// database. We completely omit state pipeline in this case.
// * For resuming:
// * If instances is a leader, it runs full ledger pipeline, including updating
// a database.
// * If instances is a NOT leader, it runs ledger pipeline without updating a
// a database so order book graph is updated but database is not overwritten.
func (s *system) Run() {
s.runStateMachine(startState{})
}
func (s *system) StressTest(numTransactions, changesPerTransaction int) error {
if numTransactions <= 0 {
return errors.New("transactions must be positive")
}
if changesPerTransaction <= 0 {
return errors.New("changes per transaction must be positive")
}
s.runner.EnableMemoryStatsLogging()
s.runner.SetLedgerBackend(fakeLedgerBackend{
numTransactions: numTransactions,
changesPerTransaction: changesPerTransaction,
})
return s.runStateMachine(stressTestState{})
}
// VerifyRange runs the ingestion pipeline on the range of ledgers. When
// verifyState is true it verifies the state when ingestion is complete.
func (s *system) VerifyRange(fromLedger, toLedger uint32, verifyState bool) error {
return s.runStateMachine(verifyRangeState{
fromLedger: fromLedger,
toLedger: toLedger,
verifyState: verifyState,
})
}
// ReingestRange runs the ingestion pipeline on the range of ledgers ingesting
// history data only.
func (s *system) ReingestRange(fromLedger, toLedger uint32, force bool) error {
run := func() error {
return s.runStateMachine(reingestHistoryRangeState{
fromLedger: fromLedger,
toLedger: toLedger,
force: force,
})
}
err := run()
for retry := 0; err != nil && retry < s.maxReingestRetries; retry++ {
log.Warnf("reingest range [%d, %d] failed (%s), retrying", fromLedger, toLedger, err.Error())
time.Sleep(time.Second * time.Duration(s.reingestRetryBackoffSeconds))
err = run()
}
return err
}
// BuildGenesisState runs the ingestion pipeline on genesis ledger. Transitions
// to stopState when done.
func (s *system) BuildGenesisState() error {
return s.runStateMachine(buildState{
checkpointLedger: 1,
stop: true,
})
}
func (s *system) runStateMachine(cur stateMachineNode) error {
s.wg.Add(1)
defer func() {
s.wg.Done()
s.wg.Wait()
}()
log.WithFields(logpkg.F{"current_state": cur}).Info("Ingestion system initial state")
for {
// Every node in the state machine is responsible for
// creating and disposing its own transaction.
// We should never enter a new state with the transaction
// from the previous state.
if s.historyQ.GetTx() != nil {
panic("unexpected transaction")
}
next, err := cur.run(s)
if err != nil {
logger := log.WithFields(logpkg.F{
"error": err,
"current_state": cur,
"next_state": next.node,
})
if isCancelledError(err) {
// We only expect context.Canceled errors to occur when horizon is shutting down
// so we log these errors using the info log level
logger.Info("Error in ingestion state machine")
} else {
logger.Error("Error in ingestion state machine")
}
}
// Exit after processing shutdownState
if next.node == (stopState{}) {
log.Info("Shut down")
return err
}
select {
case <-s.ctx.Done():
log.Info("Received shut down signal...")
return nil
case <-time.After(next.sleepDuration):
}
log.WithFields(logpkg.F{
"current_state": cur,
"next_state": next.node,
}).Info("Ingestion system state machine transition")
cur = next.node
}
}
func (s *system) maybeVerifyState(lastIngestedLedger uint32) {
stateInvalid, err := s.historyQ.GetExpStateInvalid()
if err != nil && !isCancelledError(err) {
log.WithField("err", err).Error("Error getting state invalid value")
}
// Run verification routine only when...
if !stateInvalid && // state has not been proved to be invalid...
!s.disableStateVerification && // state verification is not disabled...
s.checkpointManager.IsCheckpoint(lastIngestedLedger) { // it's a checkpoint ledger.
s.wg.Add(1)
go func() {
defer s.wg.Done()
err := s.verifyState(true)
if err != nil {
if isCancelledError(err) {
return
}
errorCount := s.incrementStateVerificationErrors()
switch errors.Cause(err).(type) {
case ingest.StateError:
markStateInvalid(s.historyQ, err)
default:
logger := log.WithField("err", err).Warn
if errorCount >= stateVerificationErrorThreshold {
logger = log.WithField("err", err).Error
}
logger("State verification errored")
}
} else {
s.resetStateVerificationErrors()
}
}()
}
}
func (s *system) incrementStateVerificationErrors() int {
s.stateVerificationMutex.Lock()
defer s.stateVerificationMutex.Unlock()
s.stateVerificationErrors++
return s.stateVerificationErrors
}
func (s *system) resetStateVerificationErrors() {
s.stateVerificationMutex.Lock()
defer s.stateVerificationMutex.Unlock()
s.stateVerificationErrors = 0
}
func (s *system) updateCursor(ledgerSequence uint32) error {
if s.stellarCoreClient == nil || s.config.EnableCaptiveCore {
return nil
}
cursor := defaultCoreCursorName
if s.config.StellarCoreCursor != "" {
cursor = s.config.StellarCoreCursor
}
ctx, cancel := context.WithTimeout(s.ctx, time.Second)
defer cancel()
err := s.stellarCoreClient.SetCursor(ctx, cursor, int32(ledgerSequence))
if err != nil {
return errors.Wrap(err, "Setting stellar-core cursor failed")
}
return nil
}
func (s *system) Shutdown() {
log.Info("Shutting down ingestion system...")
s.stateVerificationMutex.Lock()
if s.stateVerificationRunning {
log.Info("Shutting down state verifier...")
}
s.stateVerificationMutex.Unlock()
s.cancel()
// wait for ingestion state machine to terminate
s.wg.Wait()
if err := s.ledgerBackend.Close(); err != nil {
log.WithError(err).Info("could not close ledger backend")
}
}
func markStateInvalid(historyQ history.IngestionQ, err error) {
log.WithField("err", err).Error("STATE IS INVALID!")
q := historyQ.CloneIngestionQ()
if err := q.UpdateExpStateInvalid(true); err != nil {
log.WithField("err", err).Error(updateExpStateInvalidErrMsg)
}
}
func isCancelledError(err error) bool {
cause := errors.Cause(err)
return cause == context.Canceled || cause == db.ErrCancelled
}