-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathepochcache.go
More file actions
461 lines (373 loc) · 13.7 KB
/
Copy pathepochcache.go
File metadata and controls
461 lines (373 loc) · 13.7 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
package beacon
import (
"bytes"
"crypto/md5"
"encoding/binary"
"fmt"
"runtime/debug"
"sort"
"sync"
"time"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/ethereum/go-ethereum/common/lru"
"github.com/ethpandaops/dora/clients/consensus"
)
// epochStatsKey is the primary key for EpochStats entries in cache.
// consists of dependendRoot (32 byte) and epoch (8 byte).
type epochStatsKey [32 + 8]byte
// generate epochStatsKey from epoch and dependentRoot
func getEpochStatsKey(epoch phase0.Epoch, dependentRoot phase0.Root) epochStatsKey {
var key epochStatsKey
copy(key[0:], dependentRoot[:])
binary.LittleEndian.PutUint64(key[32:], uint64(epoch))
return key
}
// epochCache is the cache for EpochStats (epoch status) and epochState (beacon state) structures.
type epochCache struct {
indexer *Indexer
cacheMutex sync.RWMutex // mutex to protect statsMap & stateMap for concurrent read/write
statsMap map[epochStatsKey]*EpochStats // epoch status cache by epochStatsKey
stateMap map[phase0.Root]*epochState // beacon state cache by dependentRoot
loadingChan chan bool // limits concurrent state calls by channel capacity
syncMutex sync.Mutex // mutex to protect syncCache for concurrent access
syncCache []phase0.ValidatorIndex // global sync committee cache for reuse if matching
precomputeLock sync.Mutex // mutex to prevent concurrent precomputing of epoch stats
votesCache *lru.Cache[epochVotesKey, *EpochVotes] // cache for epoch vote aggregations
}
// newEpochCache creates & returns a new instance of epochCache.
// initializes the cache & starts the beacon state loader subroutine.
func newEpochCache(indexer *Indexer) *epochCache {
cache := &epochCache{
indexer: indexer,
statsMap: map[epochStatsKey]*EpochStats{},
stateMap: map[phase0.Root]*epochState{},
loadingChan: make(chan bool, indexer.maxParallelStateCalls),
votesCache: lru.NewCache[epochVotesKey, *EpochVotes](500),
}
// start beacon state loader subroutine
go cache.startLoaderLoop()
return cache
}
// createOrGetEpochStats gets an existing EpochStats entry for the given epoch and dependentRoot or creates a new instance if not found.
func (cache *epochCache) createOrGetEpochStats(epoch phase0.Epoch, dependentRoot phase0.Root, createStateRequest bool) *EpochStats {
cache.cacheMutex.Lock()
defer cache.cacheMutex.Unlock()
statsKey := getEpochStatsKey(epoch, dependentRoot)
epochStats := cache.statsMap[statsKey]
if epochStats == nil {
epochStats = newEpochStats(epoch, dependentRoot)
cache.statsMap[statsKey] = epochStats
}
// get or create beacon state which the epoch status depends on (dependentRoot beacon state)
epochState := cache.stateMap[dependentRoot]
if epochState == nil && !epochStats.ready && createStateRequest {
epochState = newEpochState(dependentRoot)
cache.stateMap[dependentRoot] = epochState
cache.indexer.logger.Infof("added epoch state request for epoch %v (%v) to queue", epoch, dependentRoot.String())
}
if epochState != nil {
epochStats.dependentState = epochState
if epochState.loadingStatus == 2 && !epochStats.ready {
// dependent state is already loaded, process it
go epochStats.processState(cache.indexer, nil)
}
}
return epochStats
}
func (cache *epochCache) addEpochStateRequest(epochStats *EpochStats) {
if epochStats.dependentState != nil {
return
}
cache.cacheMutex.Lock()
defer cache.cacheMutex.Unlock()
epochState := cache.stateMap[epochStats.dependentRoot]
if epochState == nil {
epochState = newEpochState(epochStats.dependentRoot)
cache.stateMap[epochStats.dependentRoot] = epochState
cache.indexer.logger.Infof("added epoch state request for epoch %v (%v) to queue", epochStats.epoch, epochStats.dependentRoot.String())
}
epochStats.dependentState = epochState
}
func (cache *epochCache) getEpochStats(epoch phase0.Epoch, dependentRoot phase0.Root) *EpochStats {
cache.cacheMutex.RLock()
defer cache.cacheMutex.RUnlock()
statsKey := getEpochStatsKey(epoch, dependentRoot)
return cache.statsMap[statsKey]
}
// getPendingEpochStats gets all EpochStats with unloaded epochStates.
func (cache *epochCache) getPendingEpochStats() []*EpochStats {
cache.cacheMutex.Lock()
defer cache.cacheMutex.Unlock()
pendingStats := make([]*EpochStats, 0)
for _, stats := range cache.statsMap {
if stats.dependentState != nil && stats.dependentState.loadingStatus == 0 {
pendingStats = append(pendingStats, stats)
}
}
return pendingStats
}
func (cache *epochCache) getEpochStatsByEpoch(epoch phase0.Epoch) []*EpochStats {
cache.cacheMutex.RLock()
defer cache.cacheMutex.RUnlock()
statsList := []*EpochStats{}
for _, stats := range cache.statsMap {
if stats.epoch == epoch {
statsList = append(statsList, stats)
}
}
return statsList
}
func (cache *epochCache) getEpochStatsBeforeEpoch(epoch phase0.Epoch) []*EpochStats {
cache.cacheMutex.RLock()
defer cache.cacheMutex.RUnlock()
statsList := []*EpochStats{}
for _, stats := range cache.statsMap {
if stats.epoch < epoch {
statsList = append(statsList, stats)
}
}
return statsList
}
// removeEpochStats removes an EpochStats struct from cache.
// stops loading state call if not referenced by another epoch status.
func (cache *epochCache) removeEpochStats(epochStats *EpochStats) {
cache.cacheMutex.Lock()
defer cache.cacheMutex.Unlock()
statsKey := getEpochStatsKey(epochStats.epoch, epochStats.dependentRoot)
if cache.statsMap[statsKey] == nil {
return
}
delete(cache.statsMap, statsKey)
if epochStats.dependentState != nil {
foundOtherStats := false
for _, stats := range cache.statsMap {
if bytes.Equal(stats.dependentRoot[:], epochStats.dependentRoot[:]) {
foundOtherStats = true
break
}
}
if !foundOtherStats {
// no other epoch status depends on this beacon state
epochStats.dependentState.dispose()
delete(cache.stateMap, epochStats.dependentRoot)
}
}
}
func (cache *epochCache) removeEpochStatsByEpoch(epoch phase0.Epoch) {
for _, stats := range cache.getEpochStatsByEpoch(epoch) {
cache.removeEpochStats(stats)
}
}
func (cache *epochCache) removeUnreferencedEpochStates() uint64 {
cache.cacheMutex.Lock()
defer cache.cacheMutex.Unlock()
removed := uint64(0)
for _, state := range cache.stateMap {
found := false
for _, stats := range cache.statsMap {
if stats.dependentState == state {
found = true
break
}
}
if !found {
state.dispose()
delete(cache.stateMap, state.slotRoot)
removed++
}
}
return removed
}
// getOrUpdateSyncCommittee replaces the supplied sync committee with an older sync committee from cache if all properties match.
// heavily reduces memory consumption as sync committee objects are not duplicated for each sync committee request.
func (cache *epochCache) getOrUpdateSyncCommittee(syncCommittee []phase0.ValidatorIndex) []phase0.ValidatorIndex {
cache.syncMutex.Lock()
defer cache.syncMutex.Unlock()
isEqual := false
if len(syncCommittee) == len(cache.syncCache) {
isEqual = true
for i, index := range syncCommittee {
if cache.syncCache[i] != index {
isEqual = false
break
}
}
}
if isEqual {
// all properties match, return reference to old cached entry
return cache.syncCache
}
cache.syncCache = syncCommittee
return syncCommittee
}
func (cache *epochCache) withPrecomputeLock(f func() error) error {
cache.precomputeLock.Lock()
defer cache.precomputeLock.Unlock()
return f()
}
// startLoaderLoop is the entrypoint for the beacon state loader subroutine.
// contains the main loop & crash handler of the subroutine.
func (cache *epochCache) startLoaderLoop() {
defer func() {
if err := recover(); err != nil {
cache.indexer.logger.WithError(err.(error)).Errorf("uncaught panic in indexer.beacon.epochCache.startLoaderLoop subroutine: %v, stack: %v", err, string(debug.Stack()))
time.Sleep(10 * time.Second)
go cache.startLoaderLoop()
}
}()
for {
cache.runLoaderLoop()
time.Sleep(2 * time.Second)
}
}
// runLoaderLoop checks the cache for unloaded epoch states.
// loads the next unloaded state in a subroutine if needed.
// blocks if too many loader subroutines are already running.
func (cache *epochCache) runLoaderLoop() {
// load next epoch stats
pendingStats := cache.getPendingEpochStats()
if len(pendingStats) == 0 {
return
}
// sort by loading priority
// 1. bad states (prefer <= 10 retries)
// 2. high priority states (most recent 2 epochs are always high priority)
// 3. retry count (prefer lower)
// 4. requested by clients count (prefer higher)
// 5. epoch number (prefer higher)
currentEpoch := cache.indexer.consensusPool.GetChainState().CurrentEpoch()
sort.Slice(pendingStats, func(a, b int) bool {
probablyBadA := pendingStats[a].dependentState.retryCount > beaconStateRetryCount
probablyBadB := pendingStats[b].dependentState.retryCount > beaconStateRetryCount
if probablyBadA != probablyBadB {
return probablyBadB
}
highPriorityA := pendingStats[a].dependentState.highPriority || currentEpoch < 2 || pendingStats[a].epoch >= currentEpoch-2
highPriorityB := pendingStats[b].dependentState.highPriority || currentEpoch < 2 || pendingStats[b].epoch >= currentEpoch-2
if highPriorityA != highPriorityB {
return highPriorityA
}
if pendingStats[a].dependentState.retryCount != pendingStats[b].dependentState.retryCount {
return pendingStats[a].dependentState.retryCount < pendingStats[b].dependentState.retryCount
}
if pendingStats[a].dependentState.retryCount != pendingStats[b].dependentState.retryCount {
return pendingStats[a].dependentState.retryCount < pendingStats[b].dependentState.retryCount
}
reqCountA := len(pendingStats[a].requestedBy)
reqCountB := len(pendingStats[b].requestedBy)
if reqCountA != reqCountB {
return reqCountA > reqCountB
}
return pendingStats[a].epoch > pendingStats[b].epoch
})
if cache.indexer.maxParallelStateCalls > 0 {
cache.loadingChan <- true
}
go func() {
defer func() {
if cache.indexer.maxParallelStateCalls > 0 {
<-cache.loadingChan
}
}()
for _, pendingStats := range pendingStats {
if cache.loadEpochStats(pendingStats) {
break
}
}
}()
}
// loadEpochStats loads the supplied unloaded epoch status (the dependent epoch state).
// retires loading from multiple clients, ordered by priority.
// returns true if a epoch state request was done (either successful or failed).
func (cache *epochCache) loadEpochStats(epochStats *EpochStats) bool {
defer func() {
if err := recover(); err != nil {
cache.indexer.logger.WithError(err.(error)).Errorf("uncaught panic in indexer.beacon.epochCache.loadEpochStats subroutine: %v, stack: %v", err, string(debug.Stack()))
}
}()
clients := []*Client{}
preferArchive := epochStats.epoch < cache.indexer.lastFinalizedEpoch
for _, client := range cache.indexer.GetReadyClientsByBlockRoot(epochStats.dependentRoot, preferArchive) {
if client.skipValidators {
continue
}
if client.client.GetStatus() != consensus.ClientStatusOnline && client.client.GetStatus() != consensus.ClientStatusOptimistic {
continue
}
if !cache.indexer.blockCache.isCanonicalBlock(epochStats.dependentRoot, client.headRoot) {
continue
}
clients = append(clients, client)
}
if len(clients) == 0 {
for _, client := range epochStats.getRequestedBy() {
if client.skipValidators {
continue
}
if client.client.GetStatus() != consensus.ClientStatusOnline && client.client.GetStatus() != consensus.ClientStatusOptimistic {
continue
}
clients = append(clients, client)
}
}
if len(clients) == 0 {
cache.indexer.logger.Debugf("no clients available to load epoch %v stats (dep: %v)", epochStats.epoch, epochStats.dependentRoot.String())
epochStats.dependentState.retryCount++
return false
}
sort.Slice(clients, func(a, b int) bool {
cliA := clients[a]
cliB := clients[b]
if cliA.archive != cliB.archive {
if cliA.archive {
return false
} else {
return true
}
}
if cliA.priority != cliB.priority {
if cliA.priority > cliB.priority {
return false
} else {
return true
}
}
hashA := md5.Sum([]byte(fmt.Sprintf("%v-%v", cliA.client.GetIndex(), epochStats.epoch)))
hashB := md5.Sum([]byte(fmt.Sprintf("%v-%v", cliB.client.GetIndex(), epochStats.epoch)))
return bytes.Compare(hashA[:], hashB[:]) < 0
})
client := clients[int(epochStats.dependentState.retryCount)%len(clients)]
log := cache.indexer.logger.WithField("client", client.client.GetName())
if epochStats.dependentState.retryCount > 0 {
log = log.WithField("retry", epochStats.dependentState.retryCount)
}
log.Infof("loading epoch %v stats (dep: %v, req: %v)", epochStats.epoch, epochStats.dependentRoot.String(), len(epochStats.requestedBy))
state, err := epochStats.dependentState.loadState(client.getContext(), client, cache)
if err != nil && epochStats.dependentState.loadingStatus == 0 {
client.logger.Warnf("failed loading epoch %v stats (dep: %v): %v", epochStats.epoch, epochStats.dependentRoot.String(), err)
}
if epochStats.dependentState.loadingStatus != 2 {
// epoch state could not be loaded
epochStats.dependentState.retryCount++
return false
}
var validatorSet []*phase0.Validator
if state != nil {
validatorSet, err = state.Validators()
if err != nil {
cache.indexer.logger.Errorf("error getting validator set from state %v: %v", epochStats.dependentRoot.String(), err)
}
}
dependentStats := []*EpochStats{}
cache.cacheMutex.Lock()
for _, stats := range cache.statsMap {
if stats.dependentState == epochStats.dependentState {
dependentStats = append(dependentStats, stats)
}
}
cache.cacheMutex.Unlock()
for _, stats := range dependentStats {
go stats.processState(cache.indexer, validatorSet)
}
return true
}