forked from a41-official/cosmos-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
661 lines (578 loc) · 19 KB
/
validator.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
package main
import (
"context"
"net/http"
"sort"
"strconv"
"sync"
"time"
"github.com/cosmos/cosmos-sdk/simapp"
sdk "github.com/cosmos/cosmos-sdk/types"
querytypes "github.com/cosmos/cosmos-sdk/types/query"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
)
func ValidatorHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.ClientConn) {
requestStart := time.Now()
sublogger := log.With().
Str("request-id", uuid.New().String()).
Logger()
address := r.URL.Query().Get("address")
myAddress, err := sdk.ValAddressFromBech32(address)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get address")
return
}
validatorDelegationsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_delegations",
Help: "Delegations of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom", "delegated_by"},
)
validatorTokensGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_tokens",
Help: "Tokens of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom"},
)
validatorDelegatorSharesGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_delegators_shares",
Help: "Delegators shares of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom"},
)
validatorCommissionRateGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_commission_rate",
Help: "Commission rate of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
validatorCommissionGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_commission",
Help: "Commission of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom"},
)
validatorRewardsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_rewards",
Help: "Rewards of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom"},
)
validatorUnbondingsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_unbondings",
Help: "Unbondings of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom", "unbonded_by"},
)
validatorRedelegationsGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_redelegations",
Help: "Redelegations of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker", "denom", "redelegated_by", "redelegated_to"},
)
validatorMissedBlocksGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_missed_blocks",
Help: "Missed blocks of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
validatorRankGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_rank",
Help: "Rank of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
validatorIsActiveGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_active",
Help: "1 if the Cosmos-based blockchain validator is in active set, 0 if no",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
validatorStatusGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_status",
Help: "Status of the Cosmos-based blockchain validator",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
validatorJailedGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_jailed",
Help: "1 if the Cosmos-based blockchain validator is jailed, 0 if no",
ConstLabels: ConstLabels,
},
[]string{"address", "moniker"},
)
registry := prometheus.NewRegistry()
registry.MustRegister(validatorDelegationsGauge)
registry.MustRegister(validatorTokensGauge)
registry.MustRegister(validatorDelegatorSharesGauge)
registry.MustRegister(validatorCommissionRateGauge)
registry.MustRegister(validatorCommissionGauge)
registry.MustRegister(validatorRewardsGauge)
registry.MustRegister(validatorUnbondingsGauge)
registry.MustRegister(validatorRedelegationsGauge)
registry.MustRegister(validatorMissedBlocksGauge)
registry.MustRegister(validatorRankGauge)
registry.MustRegister(validatorIsActiveGauge)
registry.MustRegister(validatorStatusGauge)
registry.MustRegister(validatorJailedGauge)
// doing this not in goroutine as we'll need the moniker value later
sublogger.Debug().
Str("address", address).
Msg("Started querying validator")
validatorQueryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
validator, err := stakingClient.Validator(
context.Background(),
&stakingtypes.QueryValidatorRequest{ValidatorAddr: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(validatorQueryStart).Seconds()).
Msg("Finished querying validator")
if value, err := strconv.ParseFloat(validator.Validator.Tokens.String(), 64); err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not parse validator tokens")
} else {
validatorTokensGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom,
}).Set(value / DenomCoefficient)
}
// because cosmos's dec doesn't have .toFloat64() method or whatever and returns everything as int
if value, err := strconv.ParseFloat(validator.Validator.DelegatorShares.String(), 64); err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not parse delegator shares")
} else {
validatorDelegatorSharesGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom,
}).Set(value / DenomCoefficient)
}
// because cosmos's dec doesn't have .toFloat64() method or whatever and returns everything as int
if rate, err := strconv.ParseFloat(validator.Validator.Commission.CommissionRates.Rate.String(), 64); err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not parse commission rate")
} else {
validatorCommissionRateGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
}).Set(rate)
}
validatorStatusGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
}).Set(float64(validator.Validator.Status))
// golang doesn't have a ternary operator, so we have to stick with this ugly solution
var jailed float64
if validator.Validator.Jailed {
jailed = 1
} else {
jailed = 0
}
validatorJailedGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
}).Set(jailed)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator delegations")
queryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
stakingRes, err := stakingClient.ValidatorDelegations(
context.Background(),
&stakingtypes.QueryValidatorDelegationsRequest{ValidatorAddr: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator delegations")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator delegations")
for _, delegation := range stakingRes.DelegationResponses {
value, err := strconv.ParseFloat(delegation.Balance.Amount.String(), 64)
if err != nil {
log.Error().
Err(err).
Str("address", address).
Msg("Could not convert delegation entry")
} else {
validatorDelegationsGauge.With(prometheus.Labels{
"moniker": validator.Validator.Description.Moniker,
"address": delegation.Delegation.ValidatorAddress,
"denom": Denom,
"delegated_by": delegation.Delegation.DelegatorAddress,
}).Set(value / DenomCoefficient)
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator commission")
queryStart := time.Now()
distributionClient := distributiontypes.NewQueryClient(grpcConn)
distributionRes, err := distributionClient.ValidatorCommission(
context.Background(),
&distributiontypes.QueryValidatorCommissionRequest{ValidatorAddress: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator commission")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator commission")
for _, commission := range distributionRes.Commission.Commission {
// because cosmos's dec doesn't have .toFloat64() method or whatever and returns everything as int
value, err := strconv.ParseFloat(commission.Amount.String(), 64)
if err != nil {
log.Error().
Err(err).
Str("address", address).
Msg("Could not get validator commission")
} else {
validatorCommissionGauge.With(prometheus.Labels{
"address": address,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom,
}).Set(value / DenomCoefficient)
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator rewards")
queryStart := time.Now()
distributionClient := distributiontypes.NewQueryClient(grpcConn)
distributionRes, err := distributionClient.ValidatorOutstandingRewards(
context.Background(),
&distributiontypes.QueryValidatorOutstandingRewardsRequest{ValidatorAddress: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator rewards")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator rewards")
for _, reward := range distributionRes.Rewards.Rewards {
// because cosmos's dec doesn't have .toFloat64() method or whatever and returns everything as int
if value, err := strconv.ParseFloat(reward.Amount.String(), 64); err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get reward")
} else {
validatorRewardsGauge.With(prometheus.Labels{
"address": address,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom,
}).Set(value / DenomCoefficient)
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator unbonding delegations")
queryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
stakingRes, err := stakingClient.ValidatorUnbondingDelegations(
context.Background(),
&stakingtypes.QueryValidatorUnbondingDelegationsRequest{ValidatorAddr: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator unbonding delegations")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator unbonding delegations")
for _, unbonding := range stakingRes.UnbondingResponses {
var sum float64 = 0
for _, entry := range unbonding.Entries {
value, err := strconv.ParseFloat(entry.Balance.String(), 64)
if err != nil {
log.Error().
Err(err).
Str("address", address).
Msg("Could not convert unbonding delegation entry")
} else {
sum += value
}
}
validatorUnbondingsGauge.With(prometheus.Labels{
"address": unbonding.ValidatorAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom, // unbonding does not have denom in response for some reason
"unbonded_by": unbonding.DelegatorAddress,
}).Set(sum / DenomCoefficient)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator redelegations")
queryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
stakingRes, err := stakingClient.Redelegations(
context.Background(),
&stakingtypes.QueryRedelegationsRequest{SrcValidatorAddr: myAddress.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get redelegations")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator redelegations")
for _, redelegation := range stakingRes.RedelegationResponses {
var sum float64 = 0
for _, entry := range redelegation.Entries {
value, err := strconv.ParseFloat(entry.Balance.String(), 64)
if err != nil {
log.Error().
Err(err).
Str("address", address).
Msg("Could not convert redelegation entry")
} else {
sum += value
}
}
validatorRedelegationsGauge.With(prometheus.Labels{
"address": redelegation.Redelegation.ValidatorSrcAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": Denom, // redelegation does not have denom in response for some reason
"redelegated_by": redelegation.Redelegation.DelegatorAddress,
"redelegated_to": redelegation.Redelegation.ValidatorDstAddress,
}).Set(sum / DenomCoefficient)
}
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator signing info")
queryStart := time.Now()
encCfg := simapp.MakeTestEncodingConfig()
interfaceRegistry := encCfg.InterfaceRegistry
err := validator.Validator.UnpackInterfaces(interfaceRegistry) // Unpack interfaces, to populate the Anys' cached values
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get unpack validator inferfaces")
}
pubKey, err := validator.Validator.GetConsAddr()
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator pubkey")
}
slashingClient := slashingtypes.NewQueryClient(grpcConn)
slashingRes, err := slashingClient.SigningInfo(
context.Background(),
&slashingtypes.QuerySigningInfoRequest{ConsAddress: pubKey.String()},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get validator signing info")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator signing info")
sublogger.Debug().
Str("address", address).
Int64("missedBlocks", slashingRes.ValSigningInfo.MissedBlocksCounter).
Msg("Finished querying validator signing info")
validatorMissedBlocksGauge.With(prometheus.Labels{
"moniker": validator.Validator.Description.Moniker,
"address": address,
}).Set(float64(slashingRes.ValSigningInfo.MissedBlocksCounter))
}()
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("address", address).
Msg("Started querying validator other validators")
queryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
stakingRes, err := stakingClient.Validators(
context.Background(),
&stakingtypes.QueryValidatorsRequest{
Pagination: &querytypes.PageRequest{
Limit: Limit,
},
},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get other validators")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator other validators")
validators := stakingRes.Validators
// sorting by delegator shares to display rankings
sort.Slice(validators, func(i, j int) bool {
firstShares, firstErr := strconv.ParseFloat(validators[i].DelegatorShares.String(), 64)
secondShares, secondErr := strconv.ParseFloat(validators[j].DelegatorShares.String(), 64)
if firstErr != nil || secondErr != nil {
sublogger.Error().
Err(err).
Msg("Error converting delegator shares for sorting")
return true
}
return firstShares > secondShares
})
var validatorRank int
for index, validatorIterated := range validators {
if validatorIterated.OperatorAddress == validator.Validator.OperatorAddress {
validatorRank = index + 1
break
}
}
if validatorRank == 0 {
sublogger.Warn().
Str("address", address).
Msg("Could not find validator in validators list")
return
}
validatorRankGauge.With(prometheus.Labels{
"moniker": validator.Validator.Description.Moniker,
"address": address,
}).Set(float64(validatorRank))
sublogger.Debug().
Str("address", address).
Msg("Started querying validator params")
queryStart = time.Now()
paramsRes, err := stakingClient.Params(
context.Background(),
&stakingtypes.QueryParamsRequest{},
)
if err != nil {
sublogger.Error().
Str("address", address).
Err(err).
Msg("Could not get params")
return
}
sublogger.Debug().
Str("address", address).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying validator params")
// golang doesn't have a ternary operator, so we have to stick with this ugly solution
var active float64
if validatorRank <= int(paramsRes.Params.MaxValidators) {
active = 1
} else {
active = 0
}
validatorIsActiveGauge.With(prometheus.Labels{
"address": validator.Validator.OperatorAddress,
"moniker": validator.Validator.Description.Moniker,
}).Set(active)
}()
wg.Wait()
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
sublogger.Info().
Str("method", "GET").
Str("endpoint", "/metrics/validator?address="+address).
Float64("request-time", time.Since(requestStart).Seconds()).
Msg("Request processed")
}