forked from solarlabsteam/cosmos-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelegator.go
94 lines (80 loc) · 2.42 KB
/
delegator.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
package main
import (
"context"
"net/http"
"sync"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
querytypes "github.com/cosmos/cosmos-sdk/types/query"
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 DelegatorHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.ClientConn) {
requestStart := time.Now()
sublogger := log.With().
Str("request-id", uuid.New().String()).
Logger()
validatorAddress := r.URL.Query().Get("validator_address")
valAddress, err := sdk.ValAddressFromBech32(validatorAddress)
if err != nil {
sublogger.Error().
Str("validator_address", validatorAddress).
Err(err).
Msg("Could not get validator address")
return
}
delegatorTotalGauge := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "cosmos_validator_delegator_total",
Help: "Number of delegators in validator",
ConstLabels: ConstLabels,
},
[]string{"validator_address"},
)
registry := prometheus.NewRegistry()
registry.MustRegister(delegatorTotalGauge)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
sublogger.Debug().
Str("validator_address", validatorAddress).
Msg("Started querying delegator")
queryStart := time.Now()
stakingClient := stakingtypes.NewQueryClient(grpcConn)
delegatorRes, err := stakingClient.ValidatorDelegations(
context.Background(),
&stakingtypes.QueryValidatorDelegationsRequest{
ValidatorAddr: valAddress.String(),
Pagination: &querytypes.PageRequest{
Limit: Limit,
},
},
)
if err != nil {
sublogger.Error().
Str("validator_address", validatorAddress).
Err(err).
Msg("Could not get delegator")
return
}
sublogger.Debug().
Str("validator_address", validatorAddress).
Float64("request-time", time.Since(queryStart).Seconds()).
Msg("Finished querying delegators")
delegatorTotalGauge.With(prometheus.Labels{
"validator_address": validatorAddress,
}).Set(float64(len(delegatorRes.DelegationResponses)))
}()
wg.Wait()
h := promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
h.ServeHTTP(w, r)
sublogger.Info().
Str("method", "GET").
Str("endpoint", "/metrics/delegator?validator_address="+validatorAddress).
Float64("request-time", time.Since(requestStart).Seconds()).
Msg("Request processed")
}