-
Notifications
You must be signed in to change notification settings - Fork 445
/
Copy pathbigtable.go
3094 lines (2560 loc) · 103 KB
/
bigtable.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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package db
import (
"context"
"encoding/binary"
"fmt"
"math"
"math/big"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/gobitfly/eth2-beaconchain-explorer/metrics"
"github.com/gobitfly/eth2-beaconchain-explorer/types"
"github.com/gobitfly/eth2-beaconchain-explorer/utils"
"github.com/lib/pq"
gcp_bigtable "cloud.google.com/go/bigtable"
"github.com/go-redis/redis/v8"
itypes "github.com/gobitfly/eth-rewards/types"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
"golang.org/x/sync/errgroup"
"google.golang.org/api/option"
"google.golang.org/protobuf/proto"
)
var BigtableClient *Bigtable
const (
DEFAULT_FAMILY = "f"
VALIDATOR_BALANCES_FAMILY = "vb"
VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY = "ha"
ATTESTATIONS_FAMILY = "at"
SYNC_COMMITTEES_FAMILY = "sc"
INCOME_DETAILS_COLUMN_FAMILY = "id"
STATS_COLUMN_FAMILY = "stats"
MACHINE_METRICS_COLUMN_FAMILY = "mm"
SERIES_FAMILY = "series"
SUM_COLUMN = "sum"
MAX_CL_BLOCK_NUMBER = 1000000000 - 1
MAX_EL_BLOCK_NUMBER = 1000000000
MAX_EPOCH = 1000000000 - 1
max_block_number_v1 = 1000000000
max_epoch_v1 = 1000000000
MAX_BATCH_MUTATIONS = 100000
DEFAULT_BATCH_INSERTS = 10000
REPORT_TIMEOUT = time.Second * 10
)
type Bigtable struct {
client *gcp_bigtable.Client
tableBeaconchain *gcp_bigtable.Table
tableValidators *gcp_bigtable.Table
tableValidatorsHistory *gcp_bigtable.Table
tableData *gcp_bigtable.Table
tableBlocks *gcp_bigtable.Table
tableMetadataUpdates *gcp_bigtable.Table
tableMetadata *gcp_bigtable.Table
tableMachineMetrics *gcp_bigtable.Table
redisCache RedisClient
LastAttestationCache map[uint64]uint64
LastAttestationCacheMux *sync.Mutex
chainId string
v2SchemaCutOffEpoch uint64
machineMetricsQueuedWritesChan chan (types.BulkMutation)
}
type RedisClient interface {
SCard(ctx context.Context, key string) *redis.IntCmd
SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd
Pipeline() redis.Pipeliner
Get(ctx context.Context, key string) *redis.StringCmd
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd
}
func InitBigtable(project, instance, chainId, redisAddress string) (*Bigtable, error) {
rdc := redis.NewClient(&redis.Options{
Addr: redisAddress,
ReadTimeout: time.Second * 20,
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
if err := rdc.Ping(ctx).Err(); err != nil {
return nil, err
}
return InitBigtableWithCache(ctx, project, instance, chainId, rdc)
}
func InitBigtableWithCache(ctx context.Context, project, instance, chainId string, rdc RedisClient) (*Bigtable, error) {
if utils.Config.Bigtable.Emulator {
if utils.Config.Bigtable.EmulatorHost == "" {
utils.Config.Bigtable.EmulatorHost = "127.0.0.1"
}
logger.Infof("using emulated local bigtable environment, setting BIGTABLE_EMULATOR_HOST env variable to %s:%d", utils.Config.Bigtable.EmulatorHost, utils.Config.Bigtable.EmulatorPort)
err := os.Setenv("BIGTABLE_EMULATOR_HOST", fmt.Sprintf("%s:%d", utils.Config.Bigtable.EmulatorHost, utils.Config.Bigtable.EmulatorPort))
if err != nil {
logger.Fatalf("unable to set bigtable emulator environment variable: %v", err)
}
}
poolSize := 50
btClient, err := gcp_bigtable.NewClient(ctx, project, instance, option.WithGRPCConnectionPool(poolSize))
if err != nil {
return nil, err
}
bt := &Bigtable{
client: btClient,
tableData: btClient.Open("data"),
tableBlocks: btClient.Open("blocks"),
tableMetadataUpdates: btClient.Open("metadata_updates"),
tableMetadata: btClient.Open("metadata"),
tableBeaconchain: btClient.Open("beaconchain"),
tableMachineMetrics: btClient.Open("machine_metrics"),
tableValidators: btClient.Open("beaconchain_validators"),
tableValidatorsHistory: btClient.Open("beaconchain_validators_history"),
chainId: chainId,
redisCache: rdc,
LastAttestationCacheMux: &sync.Mutex{},
v2SchemaCutOffEpoch: utils.Config.Bigtable.V2SchemaCutOffEpoch,
machineMetricsQueuedWritesChan: make(chan types.BulkMutation, MAX_BATCH_MUTATIONS),
}
if utils.Config.Frontend.Enabled { // Only activate machine metrics inserts on frontend / api instances
go bt.commitQueuedMachineMetricWrites()
}
BigtableClient = bt
return bt, nil
}
func (bigtable *Bigtable) commitQueuedMachineMetricWrites() {
// copy the pending mutations over and commit them
batchSize := 10000
muts := types.NewBulkMutations(batchSize)
tmr := time.NewTicker(time.Second * 10)
for {
select {
case mut, ok := <-bigtable.machineMetricsQueuedWritesChan:
if ok {
muts.Keys = append(muts.Keys, mut.Key)
muts.Muts = append(muts.Muts, mut.Mut)
}
if len(muts.Keys) >= batchSize || !ok && len(muts.Keys) > 0 { // commit when batch size is reached or on channel close
logger.Infof("committing %v queued machine metric inserts (trigger=batchSize, ok=%v)", len(muts.Keys), ok)
err := bigtable.WriteBulk(muts, bigtable.tableMachineMetrics, batchSize)
if err == nil {
muts = types.NewBulkMutations(batchSize)
} else {
logger.Errorf("error writing queued machine metrics to bigtable: %v", err)
}
}
if !ok { // insert chan is closed, stop the timer and exit
tmr.Stop()
logger.Infof("stopping batched machine metrics insert")
return
}
case <-tmr.C:
if len(muts.Keys) > 0 {
logger.Infof("committing %v queued machine metric inserts (trigger=timeout)", len(muts.Keys))
err := bigtable.WriteBulk(muts, bigtable.tableMachineMetrics, DEFAULT_BATCH_INSERTS)
if err == nil {
muts = types.NewBulkMutations(batchSize)
} else {
logger.Errorf("error writing queued machine metrics to bigtable: %v", err)
}
}
}
}
}
func (bigtable *Bigtable) Close() {
close(bigtable.machineMetricsQueuedWritesChan)
time.Sleep(time.Second * 5)
bigtable.client.Close()
}
func (bigtable *Bigtable) GetClient() *gcp_bigtable.Client {
return bigtable.client
}
func (bigtable *Bigtable) SaveMachineMetric(process string, userID uint64, machine string, data []byte) error {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
"process": process,
"machine": machine,
"len(data)": len(data),
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
rowKeyData := fmt.Sprintf("u:%s:p:%s:m:%v", bigtable.reversePaddedUserID(userID), process, machine)
ts := gcp_bigtable.Now()
rateLimitKey := fmt.Sprintf("%s:%d", rowKeyData, ts.Time().Minute())
rateLimitKeySetStartTs := time.Now()
keySet, err := bigtable.redisCache.SetNX(ctx, rateLimitKey, "1", time.Minute).Result()
if err != nil {
return err
}
metrics.TaskDuration.WithLabelValues("client_stats_post_save_data_rate_limit_set").Observe(time.Since(rateLimitKeySetStartTs).Seconds())
if !keySet {
return fmt.Errorf("rate limit, last metric insert was less than 1 min ago")
}
// for limiting machines per user, add the machine field to a redis set
// bucket period is 15mins
rateLimitMachineSetStartTs := time.Now()
machineLimitKey := fmt.Sprintf("%s:%d", bigtable.reversePaddedUserID(userID), ts.Time().Minute()%15)
pipe := bigtable.redisCache.Pipeline()
pipe.SAdd(ctx, machineLimitKey, machine)
pipe.Expire(ctx, machineLimitKey, time.Minute*15)
_, err = pipe.Exec(ctx)
if err != nil {
return err
}
metrics.TaskDuration.WithLabelValues("client_stats_post_save_data_rate_limit_machine_set").Observe(time.Since(rateLimitMachineSetStartTs).Seconds())
queueMutationsStartTs := time.Now()
dataMut := gcp_bigtable.NewMutation()
dataMut.Set(MACHINE_METRICS_COLUMN_FAMILY, "v1", ts, data)
bulkMut := types.BulkMutation{ // schedule the mutation for writing
Key: rowKeyData,
Mut: dataMut,
}
bigtable.machineMetricsQueuedWritesChan <- bulkMut
metrics.TaskDuration.WithLabelValues("client_stats_post_save_data_queue_mutation").Observe(time.Since(queueMutationsStartTs).Seconds())
return nil
}
func (bigtable Bigtable) getMachineMetricNamesMap(userID uint64, searchDepth int) (map[string]bool, error) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
rangePrefix := fmt.Sprintf("u:%s:p:", bigtable.reversePaddedUserID(userID))
filter := gcp_bigtable.ChainFilters(
gcp_bigtable.FamilyFilter(MACHINE_METRICS_COLUMN_FAMILY),
gcp_bigtable.LatestNFilter(searchDepth),
gcp_bigtable.TimestampRangeFilter(time.Now().Add(time.Duration(searchDepth*-1)*time.Minute), time.Now()),
gcp_bigtable.StripValueFilter(),
)
machineNames := make(map[string]bool)
err := bigtable.tableMachineMetrics.ReadRows(ctx, gcp_bigtable.PrefixRange(rangePrefix), func(r gcp_bigtable.Row) bool {
success, _, machine, _ := machineMetricRowParts(r.Key())
if !success {
return false
}
machineNames[machine] = true
return true
}, gcp_bigtable.RowFilter(filter))
if err != nil {
return machineNames, err
}
return machineNames, nil
}
func (bigtable Bigtable) GetMachineMetricsMachineNames(userID uint64) ([]string, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
names, err := bigtable.getMachineMetricNamesMap(userID, 300)
if err != nil {
return nil, err
}
result := []string{}
for key := range names {
result = append(result, key)
}
return result, nil
}
func (bigtable Bigtable) GetMachineMetricsMachineCount(userID uint64) (uint64, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
machineLimitKey := fmt.Sprintf("%s:%d", bigtable.reversePaddedUserID(userID), time.Now().Minute()%15)
card, err := bigtable.redisCache.SCard(ctx, machineLimitKey).Result()
if err != nil {
return 0, err
}
return uint64(card), nil
}
func (bigtable Bigtable) GetMachineMetricsNode(userID uint64, limit, offset int) ([]*types.MachineMetricNode, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
"limit": limit,
"offset": offset,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
return getMachineMetrics(bigtable, "beaconnode", userID, limit, offset,
func(data []byte, machine string) *types.MachineMetricNode {
obj := &types.MachineMetricNode{}
err := proto.Unmarshal(data, obj)
if err != nil {
return nil
}
obj.Machine = &machine
return obj
},
)
}
func (bigtable Bigtable) GetMachineMetricsValidator(userID uint64, limit, offset int) ([]*types.MachineMetricValidator, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
"limit": limit,
"offset": offset,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
return getMachineMetrics(bigtable, "validator", userID, limit, offset,
func(data []byte, machine string) *types.MachineMetricValidator {
obj := &types.MachineMetricValidator{}
err := proto.Unmarshal(data, obj)
if err != nil {
return nil
}
obj.Machine = &machine
return obj
},
)
}
func (bigtable Bigtable) GetMachineMetricsSystem(userID uint64, limit, offset int) ([]*types.MachineMetricSystem, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"userId": userID,
"limit": limit,
"offset": offset,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
return getMachineMetrics(bigtable, "system", userID, limit, offset,
func(data []byte, machine string) *types.MachineMetricSystem {
obj := &types.MachineMetricSystem{}
err := proto.Unmarshal(data, obj)
if err != nil {
return nil
}
obj.Machine = &machine
return obj
},
)
}
func getMachineMetrics[T types.MachineMetricSystem | types.MachineMetricNode | types.MachineMetricValidator](bigtable Bigtable, process string, userID uint64, limit, offset int, marshler func(data []byte, machine string) *T) ([]*T, error) {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
rangePrefix := fmt.Sprintf("u:%s:p:%s:m:", bigtable.reversePaddedUserID(userID), process)
res := make([]*T, 0)
if offset <= 0 {
offset = 1
}
filter := gcp_bigtable.ChainFilters(
gcp_bigtable.FamilyFilter(MACHINE_METRICS_COLUMN_FAMILY),
gcp_bigtable.LatestNFilter(limit),
gcp_bigtable.CellsPerRowOffsetFilter(offset),
)
gapSize := getMachineStatsGap(uint64(limit))
err := bigtable.tableMachineMetrics.ReadRows(ctx, gcp_bigtable.PrefixRange(rangePrefix), func(r gcp_bigtable.Row) bool {
success, _, machine, _ := machineMetricRowParts(r.Key())
if !success {
return false
}
var count = -1
for _, ri := range r[MACHINE_METRICS_COLUMN_FAMILY] {
count++
if count%gapSize != 0 {
continue
}
obj := marshler(ri.Value, machine)
if obj == nil {
return false
}
res = append(res, obj)
}
return true
}, gcp_bigtable.RowFilter(filter))
if err != nil {
return nil, err
}
return res, nil
}
func (bigtable Bigtable) GetMachineRowKey(userID uint64, process string, machine string) string {
return fmt.Sprintf("u:%s:p:%s:m:%s", bigtable.reversePaddedUserID(userID), process, machine)
}
// Returns a map[userID]map[machineName]machineData
// machineData contains the latest machine data in CurrentData
// and 5 minute old data in fiveMinuteOldData (defined in limit)
// as well as the insert timestamps of both
func (bigtable Bigtable) GetMachineMetricsForNotifications(rowKeys gcp_bigtable.RowList) (map[uint64]map[string]*types.MachineMetricSystemUser, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"rowKeys": rowKeys,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*200))
defer cancel()
res := make(map[uint64]map[string]*types.MachineMetricSystemUser) // userID -> machine -> data
limit := 5
filter := gcp_bigtable.ChainFilters(
gcp_bigtable.FamilyFilter(MACHINE_METRICS_COLUMN_FAMILY),
gcp_bigtable.LatestNFilter(limit),
)
err := bigtable.tableMachineMetrics.ReadRows(ctx, rowKeys, func(r gcp_bigtable.Row) bool {
success, userID, machine, _ := machineMetricRowParts(r.Key())
if !success {
return false
}
count := 0
for _, ri := range r[MACHINE_METRICS_COLUMN_FAMILY] {
obj := &types.MachineMetricSystem{}
err := proto.Unmarshal(ri.Value, obj)
if err != nil {
return false
}
if _, found := res[userID]; !found {
res[userID] = make(map[string]*types.MachineMetricSystemUser)
}
last, found := res[userID][machine]
if found && count == limit-1 {
res[userID][machine] = &types.MachineMetricSystemUser{
UserID: userID,
Machine: machine,
CurrentData: last.CurrentData,
FiveMinuteOldData: obj,
CurrentDataInsertTs: last.CurrentDataInsertTs,
FiveMinuteOldDataInsertTs: ri.Timestamp.Time().Unix(),
}
} else {
res[userID][machine] = &types.MachineMetricSystemUser{
UserID: userID,
Machine: machine,
CurrentData: obj,
FiveMinuteOldData: nil,
CurrentDataInsertTs: ri.Timestamp.Time().Unix(),
FiveMinuteOldDataInsertTs: 0,
}
}
count++
}
return true
}, gcp_bigtable.RowFilter(filter))
if err != nil {
return nil, err
}
return res, nil
}
func machineMetricRowParts(r string) (bool, uint64, string, string) {
keySplit := strings.Split(r, ":")
userID, err := strconv.ParseUint(keySplit[1], 10, 64)
if err != nil {
logger.Errorf("error parsing slot from row key %v: %v", r, err)
return false, 0, "", ""
}
userID = ^uint64(0) - userID
machine := ""
if len(keySplit) >= 6 {
machine = keySplit[5]
}
process := keySplit[3]
return true, userID, machine, process
}
func (bigtable *Bigtable) SaveValidatorBalances(epoch uint64, validators []*types.Validator) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()
// start := time.Now()
ts := gcp_bigtable.Time(utils.EpochToTime(epoch))
muts := types.NewBulkMutations(len(validators))
highestActiveIndex := uint64(0)
epochKey := bigtable.reversedPaddedEpoch(epoch)
for _, validator := range validators {
if validator.Balance > 0 && validator.Index > highestActiveIndex {
highestActiveIndex = validator.Index
}
balanceEncoded := make([]byte, 8)
binary.LittleEndian.PutUint64(balanceEncoded, validator.Balance)
effectiveBalanceEncoded := uint8(validator.EffectiveBalance / 1e9) // we can encode the effective balance in 1 byte as it is capped at 32ETH and only decrements in 1 ETH steps
combined := append(balanceEncoded, effectiveBalanceEncoded)
mut := &gcp_bigtable.Mutation{}
mut.Set(VALIDATOR_BALANCES_FAMILY, "b", ts, combined)
key := fmt.Sprintf("%s:%s:%s:%s", bigtable.chainId, bigtable.validatorIndexToKey(validator.Index), VALIDATOR_BALANCES_FAMILY, epochKey)
muts.Add(key, mut)
}
err := bigtable.WriteBulk(muts, bigtable.tableValidatorsHistory, MAX_BATCH_MUTATIONS)
if err != nil {
return err
}
// store the highes active validator index for that epoch
highestActiveIndexEncoded := make([]byte, 8)
binary.LittleEndian.PutUint64(highestActiveIndexEncoded, highestActiveIndex)
mut := &gcp_bigtable.Mutation{}
mut.Set(VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY, VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY, ts, highestActiveIndexEncoded)
key := fmt.Sprintf("%s:%s:%s", bigtable.chainId, VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY, epochKey)
err = bigtable.tableValidatorsHistory.Apply(ctx, key, mut)
if err != nil {
return err
}
return nil
}
func (bigtable *Bigtable) SaveAttestationDuties(duties map[types.Slot]map[types.ValidatorIndex][]types.Slot) error {
// Initialize in memory last attestation cache lazily
bigtable.LastAttestationCacheMux.Lock()
if bigtable.LastAttestationCache == nil {
t := time.Now()
var err error
bigtable.LastAttestationCache, err = bigtable.GetLastAttestationSlots([]uint64{})
if err != nil {
bigtable.LastAttestationCacheMux.Unlock()
return err
}
logger.Infof("initialized in memory last attestation slot cache with %v validators in %v", len(bigtable.LastAttestationCache), time.Since(t))
}
bigtable.LastAttestationCacheMux.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5)
defer cancel()
start := time.Now()
mutsInclusionSlot := types.NewBulkMutations(MAX_BATCH_MUTATIONS)
mutLastAttestationSlot := gcp_bigtable.NewMutation()
mutLastAttestationSlotCount := 0
for attestedSlot, validators := range duties {
for validator, inclusions := range validators {
epoch := utils.EpochOfSlot(uint64(attestedSlot))
bigtable.LastAttestationCacheMux.Lock()
if len(inclusions) == 0 { // for missed attestations we write the the attested slot as inclusion slot (attested == included means no attestation duty was performed)
inclusions = append(inclusions, attestedSlot)
}
for _, inclusionSlot := range inclusions {
key := fmt.Sprintf("%s:%s:%s:%s", bigtable.chainId, bigtable.validatorIndexToKey(uint64(validator)), ATTESTATIONS_FAMILY, bigtable.reversedPaddedEpoch(epoch))
mutInclusionSlot := gcp_bigtable.NewMutation()
ts := gcp_bigtable.Time(utils.SlotToTime(uint64(inclusionSlot)))
mutInclusionSlot.Set(ATTESTATIONS_FAMILY, fmt.Sprintf("%d", attestedSlot), ts, []byte{})
mutsInclusionSlot.Add(key, mutInclusionSlot)
if inclusionSlot != MAX_CL_BLOCK_NUMBER && uint64(attestedSlot) > bigtable.LastAttestationCache[uint64(validator)] {
mutLastAttestationSlot.Set(ATTESTATIONS_FAMILY, fmt.Sprintf("%d", validator), gcp_bigtable.Timestamp((attestedSlot)*1000), []byte{})
bigtable.LastAttestationCache[uint64(validator)] = uint64(attestedSlot)
mutLastAttestationSlotCount++
if mutLastAttestationSlotCount == MAX_BATCH_MUTATIONS {
mutStart := time.Now()
err := bigtable.tableValidators.Apply(ctx, fmt.Sprintf("%s:lastAttestationSlot", bigtable.chainId), mutLastAttestationSlot)
if err != nil {
bigtable.LastAttestationCacheMux.Unlock()
return fmt.Errorf("error applying last attestation slot mutations: %v", err)
}
mutLastAttestationSlot = gcp_bigtable.NewMutation()
mutLastAttestationSlotCount = 0
logger.Infof("applied last attestation slot mutations in %v", time.Since(mutStart))
}
}
}
bigtable.LastAttestationCacheMux.Unlock()
}
}
err := bigtable.WriteBulk(mutsInclusionSlot, bigtable.tableValidatorsHistory, MAX_BATCH_MUTATIONS)
if err != nil {
return fmt.Errorf("error writing attestation inclusion slot mutations: %v", err)
}
if mutLastAttestationSlotCount > 0 {
err := bigtable.tableValidators.Apply(ctx, fmt.Sprintf("%s:lastAttestationSlot", bigtable.chainId), mutLastAttestationSlot)
if err != nil {
return fmt.Errorf("error applying last attestation slot mutations: %v", err)
}
}
logger.Infof("exported %v attestations to bigtable in %v", mutsInclusionSlot.Len(), time.Since(start))
return nil
}
// This method is only to be used for migrating the last attestation slot to bigtable and should not be used for any other purpose
func (bigtable *Bigtable) SetLastAttestationSlot(validator uint64, lastAttestationSlot uint64) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
defer cancel()
mutLastAttestationSlot := gcp_bigtable.NewMutation()
mutLastAttestationSlot.Set(ATTESTATIONS_FAMILY, fmt.Sprintf("%d", validator), gcp_bigtable.Timestamp(lastAttestationSlot*1000), []byte{})
err := bigtable.tableValidators.Apply(ctx, fmt.Sprintf("%s:lastAttestationSlot", bigtable.chainId), mutLastAttestationSlot)
if err != nil {
return err
}
return nil
}
func (bigtable *Bigtable) SaveSyncComitteeDuties(duties map[types.Slot]map[types.ValidatorIndex]bool) error {
start := time.Now()
if len(duties) == 0 {
logger.Infof("no sync duties to export")
return nil
}
muts := types.NewBulkMutations(int(utils.Config.Chain.ClConfig.SlotsPerEpoch*utils.Config.Chain.ClConfig.SyncCommitteeSize + 1))
for slot, validators := range duties {
for validator, participated := range validators {
mut := gcp_bigtable.NewMutation()
if participated {
ts := gcp_bigtable.Time(utils.SlotToTime(uint64(slot)).Add(time.Second)) // add 1 second to avoid collisions with duties
mut.Set(SYNC_COMMITTEES_FAMILY, "s", ts, []byte{})
} else {
ts := gcp_bigtable.Time(utils.SlotToTime(uint64(slot)))
mut.Set(SYNC_COMMITTEES_FAMILY, "s", ts, []byte{})
}
key := fmt.Sprintf("%s:%s:%s:%s:%s", bigtable.chainId, bigtable.validatorIndexToKey(uint64(validator)), SYNC_COMMITTEES_FAMILY, bigtable.reversedPaddedEpoch(utils.EpochOfSlot(uint64(slot))), bigtable.reversedPaddedSlot(uint64(slot)))
muts.Add(key, mut)
}
}
err := bigtable.WriteBulk(muts, bigtable.tableValidatorsHistory, MAX_BATCH_MUTATIONS)
if err != nil {
return err
}
logger.Infof("exported %v sync committee duties to bigtable in %v", muts.Len(), time.Since(start))
return nil
}
// GetMaxValidatorindexForEpoch returns the higest validatorindex with a balance at that epoch
// Clickhouse Port: Not required
func (bigtable *Bigtable) GetMaxValidatorindexForEpoch(epoch uint64) (uint64, error) {
return bigtable.getMaxValidatorindexForEpochV2(epoch)
}
func (bigtable *Bigtable) getMaxValidatorindexForEpochV2(epoch uint64) (uint64, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"epoch": epoch,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute*5))
defer cancel()
key := fmt.Sprintf("%s:%s:%s", bigtable.chainId, VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY, bigtable.reversedPaddedEpoch(epoch))
row, err := bigtable.tableValidatorsHistory.ReadRow(ctx, key)
if err != nil {
return 0, err
}
for _, ri := range row[VALIDATOR_HIGHEST_ACTIVE_INDEX_FAMILY] {
return binary.LittleEndian.Uint64(ri.Value), nil
}
return 0, nil
}
// Clickhouse port: Done
func (bigtable *Bigtable) GetValidatorBalanceHistory(validators []uint64, startEpoch uint64, endEpoch uint64) (map[uint64][]*types.ValidatorBalance, error) {
// Disable balance fetching from clickhouse until we have a compatible data set available
// endEpochTs := utils.EpochToTime(endEpoch)
// if utils.Config.ClickHouseEnabled && time.Since(endEpochTs) > utils.Config.ClickhouseDelay { // fetch data from clickhouse instead
// logger.Infof("fetching validator balance history from clickhouse for validators %v, epochs %v - %v", validators, startEpoch, endEpoch)
// return bigtable.getValidatorBalanceHistoryClickhouse(validators, startEpoch, endEpoch)
// } else
if endEpoch < bigtable.v2SchemaCutOffEpoch {
return bigtable.getValidatorBalanceHistoryV1(validators, startEpoch, endEpoch)
} else {
return bigtable.getValidatorBalanceHistoryV2(validators, startEpoch, endEpoch)
}
}
//lint:ignore U1000 will be used later on
func (bigtable *Bigtable) getValidatorBalanceHistoryClickhouse(validators []uint64, startEpoch uint64, endEpoch uint64) (map[uint64][]*types.ValidatorBalance, error) {
startEpochTs := utils.EpochToTime(startEpoch)
endEpochTs := utils.EpochToTime(endEpoch)
type row struct {
ValidatorIndex uint64 `db:"validator_index"`
Epoch uint64 `db:"epoch"`
BalanceStart int64 `db:"balance_start"`
EffectiveBalanceStart int64 `db:"balance_effective_start"`
BalanceEnd int64 `db:"balance_end"`
EffectiveBalanceEnd int64 `db:"balance_effective_end"`
}
rows := []*row{}
query := `
SELECT
validator_index,
epoch AS epoch,
balance_start,
balance_effective_start,
balance_end,
balance_effective_end
FROM validator_dashboard_data_epoch FINAL WHERE epoch_timestamp >= ? AND epoch_timestamp <= ? AND validator_index IN (?) ORDER BY epoch ASC`
err := ClickhouseReaderDb.Select(&rows, query, startEpochTs, endEpochTs, validators)
if err != nil {
logger.Error(err)
return nil, err
}
res := make(map[uint64][]*types.ValidatorBalance, len(validators))
for _, r := range rows {
if res[r.ValidatorIndex] == nil {
res[r.ValidatorIndex] = make([]*types.ValidatorBalance, 0)
}
balance := &types.ValidatorBalance{
Epoch: r.Epoch,
Balance: uint64(r.BalanceEnd),
EffectiveBalance: uint64(r.EffectiveBalanceEnd),
Index: r.ValidatorIndex,
PublicKey: []byte{},
}
res[r.ValidatorIndex] = append(res[r.ValidatorIndex], balance)
}
for validator, att := range res {
sort.Slice(att, func(i, j int) bool {
return att[i].Epoch > att[j].Epoch
})
res[validator] = att
}
return res, nil
}
func (bigtable *Bigtable) getValidatorBalanceHistoryV2(validators []uint64, startEpoch uint64, endEpoch uint64) (map[uint64][]*types.ValidatorBalance, error) {
tmr := time.AfterFunc(REPORT_TIMEOUT, func() {
logger.WithFields(logrus.Fields{
"validators_count": len(validators),
"startEpoch": startEpoch,
"endEpoch": endEpoch,
}).Warnf("%s call took longer than %v", utils.GetCurrentFuncName(), REPORT_TIMEOUT)
})
defer tmr.Stop()
if len(validators) == 0 {
return nil, fmt.Errorf("passing empty validator array is unsupported")
}
batchSize := 1000
concurrency := 10
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Minute*5))
defer cancel()
res := make(map[uint64][]*types.ValidatorBalance, len(validators))
resMux := &sync.Mutex{}
g, gCtx := errgroup.WithContext(ctx)
g.SetLimit(concurrency)
for i := 0; i < len(validators); i += batchSize {
upperBound := i + batchSize
if len(validators) < upperBound {
upperBound = len(validators)
}
vals := validators[i:upperBound]
g.Go(func() error {
select {
case <-gCtx.Done():
return gCtx.Err()
default:
}
ranges := bigtable.getValidatorsEpochRanges(vals, VALIDATOR_BALANCES_FAMILY, startEpoch, endEpoch)
ro := gcp_bigtable.LimitRows(int64(endEpoch-startEpoch+1) * int64(len(vals)))
handleRow := func(r gcp_bigtable.Row) bool {
// logger.Info(r.Key())
keySplit := strings.Split(r.Key(), ":")
epoch, err := strconv.ParseUint(keySplit[3], 10, 64)
if err != nil {
logger.Errorf("error parsing epoch from row key %v: %v", r.Key(), err)
return false
}
validator, err := bigtable.validatorKeyToIndex(keySplit[1])
if err != nil {
logger.Errorf("error parsing validator index from row key %v: %v", r.Key(), err)
return false
}
resMux.Lock()
if res[validator] == nil {
res[validator] = make([]*types.ValidatorBalance, 0)
}
resMux.Unlock()
for _, ri := range r[VALIDATOR_BALANCES_FAMILY] {
balances := ri.Value
balanceBytes := balances[0:8]
balance := binary.LittleEndian.Uint64(balanceBytes)
var effectiveBalance uint64
if len(balances) == 9 { // in new schema the effective balance is encoded in 1 byte
effectiveBalance = uint64(balances[8]) * 1e9
} else {
effectiveBalanceBytes := balances[8:16]
effectiveBalance = binary.LittleEndian.Uint64(effectiveBalanceBytes)
}
resMux.Lock()
res[validator] = append(res[validator], &types.ValidatorBalance{
Epoch: MAX_EPOCH - epoch,
Balance: balance,
EffectiveBalance: effectiveBalance,
Index: validator,
PublicKey: []byte{},
})
resMux.Unlock()
}
return true
}
err := bigtable.tableValidatorsHistory.ReadRows(gCtx, ranges, handleRow, gcp_bigtable.RowFilter(gcp_bigtable.LatestNFilter(1)), ro)
if err != nil {
return err
}
// logrus.Infof("retrieved data for validators %v - %v", vals[0], vals[len(vals)-1])
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return res, nil
}
func (bigtable *Bigtable) getValidatorBalanceHistoryV1(validators []uint64, startEpoch uint64, endEpoch uint64) (map[uint64][]*types.ValidatorBalance, error) {
valLen := len(validators)
getAllThreshold := 1000
validatorMap := make(map[uint64]bool, valLen)
for _, validatorIndex := range validators {
validatorMap[validatorIndex] = true
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*30))
defer cancel()
ranges := bigtable.getEpochRangesV1(startEpoch, endEpoch)
res := make(map[uint64][]*types.ValidatorBalance, valLen)
columnFilters := []gcp_bigtable.Filter{}
if valLen < getAllThreshold {
columnFilters = make([]gcp_bigtable.Filter, 0, valLen)
for _, validator := range validators {
columnFilters = append(columnFilters, gcp_bigtable.ColumnFilter(fmt.Sprintf("%d", validator)))
}
}
filter := gcp_bigtable.ChainFilters(
gcp_bigtable.FamilyFilter(VALIDATOR_BALANCES_FAMILY),
gcp_bigtable.InterleaveFilters(columnFilters...),
)
if len(columnFilters) == 1 { // special case to retrieve data for one validators
filter = gcp_bigtable.ChainFilters(
gcp_bigtable.FamilyFilter(VALIDATOR_BALANCES_FAMILY),
columnFilters[0],
)
}
if len(columnFilters) == 0 { // special case to retrieve data for all validators
filter = gcp_bigtable.FamilyFilter(VALIDATOR_BALANCES_FAMILY)
}
handleRow := func(r gcp_bigtable.Row) bool {
keySplit := strings.Split(r.Key(), ":")
epoch, err := strconv.ParseUint(keySplit[3], 10, 64)
if err != nil {
logger.Errorf("error parsing epoch from row key %v: %v", r.Key(), err)
return false
}