Skip to content

Commit

Permalink
feat: Add cosmos_wallet_balance metric
Browse files Browse the repository at this point in the history
  • Loading branch information
kayano committed Sep 12, 2023
1 parent 2e22139 commit 86abcc9
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 57 deletions.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# relayer_exporter
Prometheus exporter for ibc clients.
Prometheus exporter for ibc clients and wallet balance.
Returns metrics about clients expiration date.
Returns wallet balance for configured addresses.

## Configuration
Exporter needs config file in yaml format like following
Expand All @@ -16,16 +17,26 @@ github:
org: archway-network
repo: networks
dir: _IBC

account:
- address: archway1l2al7y78500h5akvgt8exwnkpmf2zmk8ky9ht3
chainId: constantine-3
denom: aconst
```
During startup it fetches IBC paths from github based on provided config.
If env var GITHUB_TOKEN is provided it will be used to make authenticated requests to GitHub API.
Using provided RPC endpoints it gets clients expiration dates for fetched paths.
For provided accounts it fetches wallet balances using endpoints defined in rpc list.
## Metrics
```
# HELP cosmos_ibc_client_expiry Returns light client expiry in unixtime.
# TYPE cosmos_ibc_client_expiry gauge
cosmos_ibc_client_expiry{client_id="07-tendermint-23",host_chain_id="archway-1",target_chain_id="agoric-3"} 1.695283384e+09
cosmos_ibc_client_expiry{client_id="07-tendermint-75",host_chain_id="agoric-3",target_chain_id="archway-1"} 1.69528327e+09
# HELP cosmos_wallet_balance Returns wallet balance for an address on a chain
# TYPE cosmos_wallet_balance gauge
cosmos_wallet_balance{account="archway1l2al7y78500h5akvgt8exwnkpmf2zmk8ky9ht3",chain_id="constantine-3",denom="aconst"} 4.64e+18
```
6 changes: 6 additions & 0 deletions cmd/relayer_exporter/relayer_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ func main() {
Paths: paths,
}

balancesCollector := collector.WalletBalanceCollector{
RPCs: rpcs,
Accounts: cfg.Accounts,
}

prometheus.MustRegister(clientsCollector)
prometheus.MustRegister(balancesCollector)

http.Handle("/metrics", promhttp.Handler())

Expand Down
5 changes: 5 additions & 0 deletions config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,8 @@ github:
org: archway-network
repo: networks
dir: _IBC

account:
- address: archway1l2al7y78500h5akvgt8exwnkpmf2zmk8ky9ht3
chainId: constantine-3
denom: aconst
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ module github.com/archway-network/relayer_exporter
go 1.21

require (
cosmossdk.io/math v1.0.1
github.com/caarlos0/env/v9 v9.0.0
github.com/cosmos/relayer/v2 v2.4.1
github.com/google/go-cmp v0.5.9
Expand All @@ -24,7 +25,6 @@ require (
cosmossdk.io/depinject v1.0.0-alpha.3 // indirect
cosmossdk.io/errors v1.0.0-beta.7 // indirect
cosmossdk.io/log v1.1.0 // indirect
cosmossdk.io/math v1.0.1 // indirect
cosmossdk.io/tools/rosetta v0.2.1 // indirect
filippo.io/edwards25519 v1.0.0 // indirect
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect
Expand Down
71 changes: 71 additions & 0 deletions pkg/account/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package account

import (
"context"

"cosmossdk.io/math"
"go.uber.org/zap"

"github.com/archway-network/relayer_exporter/pkg/chain"
log "github.com/archway-network/relayer_exporter/pkg/logger"
)

type Account struct {
Address string `yaml:"address"`
Denom string `yaml:"denom"`
ChainID string `yaml:"chainId"`
Balance math.Int
}

func GetAccountsBalances(accounts []Account, rpcs map[string]string) []Account {
num := len(accounts)

out := make(chan Account, num)
defer close(out)

for i := 0; i < num; i++ {
go func(i int) {
account, err := GetAccountBalance(accounts[i], rpcs)
if err != nil {
out <- Account{}

log.Error(err.Error(), zap.Any("account", accounts[i]))

return
}
out <- account
}(i)
}

accountsWithBalance := []Account{}

for i := 0; i < num; i++ {
account := <-out
if account.Address != "" {
accountsWithBalance = append(accountsWithBalance, account)
}
}

return accountsWithBalance
}

func GetAccountBalance(account Account, rpcs map[string]string) (Account, error) {
chain, err := chain.PrepChain(chain.Info{
ChainID: account.ChainID,
RPCAddr: rpcs[account.ChainID],
})
if err != nil {
return Account{}, err
}

ctx := context.Background()

coins, err := chain.ChainProvider.QueryBalanceWithAddress(ctx, account.Address)
if err != nil {
return Account{}, err
}

account.Balance = coins.AmountOf(account.Denom)

return account, nil
}
48 changes: 48 additions & 0 deletions pkg/chain/chain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package chain

import (
"context"

"github.com/cosmos/relayer/v2/relayer"
"github.com/cosmos/relayer/v2/relayer/chains/cosmos"
)

const (
rpcTimeout = "10s"
keyringBackend = "test"
)

type Info struct {
ChainID string
RPCAddr string
ClientID string
}

func PrepChain(cd Info) (*relayer.Chain, error) {
chain := relayer.Chain{}
providerConfig := cosmos.CosmosProviderConfig{
ChainID: cd.ChainID,
Timeout: rpcTimeout,
KeyringBackend: keyringBackend,
RPCAddr: cd.RPCAddr,
}

provider, err := providerConfig.NewProvider(nil, "", false, cd.ChainID)
if err != nil {
return nil, err
}

err = provider.Init(context.Background())
if err != nil {
return nil, err
}

chain.ChainProvider = provider

err = chain.SetPath(&relayer.PathEnd{ClientID: cd.ClientID})
if err != nil {
return nil, err
}

return &chain, nil
}
55 changes: 47 additions & 8 deletions pkg/collector/collector.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package collector

import (
"math/big"

"github.com/archway-network/relayer_exporter/pkg/account"
"github.com/archway-network/relayer_exporter/pkg/ibc"
log "github.com/archway-network/relayer_exporter/pkg/logger"
"github.com/cosmos/relayer/v2/relayer"
Expand All @@ -9,23 +12,36 @@ import (
)

const (
clientExpiryMetricName = "cosmos_ibc_client_expiry"
configuredChainMetricName = "cosmos_relayer_configured_chain"
relayerUpMetricName = "cosmos_relayer_up"
clientExpiryMetricName = "cosmos_ibc_client_expiry"
walletBalanceMetricName = "cosmos_wallet_balance"
)

var clientExpiry = prometheus.NewDesc(
clientExpiryMetricName,
"Returns light client expiry in unixtime.",
[]string{"host_chain_id", "client_id", "target_chain_id"}, nil,
var (
clientExpiry = prometheus.NewDesc(
clientExpiryMetricName,
"Returns light client expiry in unixtime.",
[]string{"host_chain_id", "client_id", "target_chain_id"}, nil,
)
walletBalance = prometheus.NewDesc(
walletBalanceMetricName,
"Returns wallet balance for an address on a chain",
[]string{"account", "chain_id", "denom"}, nil,
)
)

type IBCClientsCollector struct {
RPCs map[string]string
Paths []*relayer.IBCdata
}

func (cc IBCClientsCollector) Describe(_ chan<- *prometheus.Desc) {}
type WalletBalanceCollector struct {
RPCs map[string]string
Accounts []account.Account
}

func (cc IBCClientsCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- clientExpiry
}

func (cc IBCClientsCollector) Collect(ch chan<- prometheus.Metric) {
log.Debug("Start collecting", zap.String("metric", clientExpiryMetricName))
Expand All @@ -50,3 +66,26 @@ func (cc IBCClientsCollector) Collect(ch chan<- prometheus.Metric) {

log.Debug("Stop collecting", zap.String("metric", clientExpiryMetricName))
}

func (wb WalletBalanceCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- walletBalance
}

func (wb WalletBalanceCollector) Collect(ch chan<- prometheus.Metric) {
log.Debug("Start collecting", zap.String("metric", walletBalanceMetricName))

accounts := account.GetAccountsBalances(wb.Accounts, wb.RPCs)

for _, a := range accounts {
// Convert to a big float to get a float64 for metrics
balance, _ := big.NewFloat(0.0).SetInt(a.Balance.BigInt()).Float64()
ch <- prometheus.MustNewConstMetric(
walletBalance,
prometheus.GaugeValue,
balance,
[]string{a.Address, a.ChainID, a.Denom}...,
)
}

log.Debug("Stop collecting", zap.String("metric", walletBalanceMetricName))
}
6 changes: 4 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/google/go-github/v55/github"
"gopkg.in/yaml.v3"

"github.com/archway-network/relayer_exporter/pkg/account"
log "github.com/archway-network/relayer_exporter/pkg/logger"
)

Expand All @@ -22,8 +23,9 @@ type RPC struct {
}

type Config struct {
RPCs []RPC `yaml:"rpc"`
GitHub struct {
Accounts []account.Account `yaml:"account"`
RPCs []RPC `yaml:"rpc"`
GitHub struct {
Org string `yaml:"org"`
Repo string `yaml:"repo"`
IBCDir string `yaml:"dir"`
Expand Down
50 changes: 5 additions & 45 deletions pkg/ibc/ibc.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,12 @@ import (
"fmt"
"time"

"github.com/archway-network/relayer_exporter/pkg/chain"
log "github.com/archway-network/relayer_exporter/pkg/logger"
"github.com/cosmos/relayer/v2/relayer"
"github.com/cosmos/relayer/v2/relayer/chains/cosmos"
"github.com/google/go-cmp/cmp"
)

const (
rpcTimeout = "10s"
keyringBackend = "test"
)

type ChainData struct {
ChainID string
RPCAddr string
ClientID string
}

type ClientsInfo struct {
ChainA *relayer.Chain
ChainAClientInfo relayer.ClientStateInfo
Expand Down Expand Up @@ -66,26 +55,26 @@ func GetClientsInfos(ibcs []*relayer.IBCdata, rpcs map[string]string) []ClientsI
func GetClientsInfo(ibc *relayer.IBCdata, rpcs map[string]string) (ClientsInfo, error) {
clientsInfo := ClientsInfo{}

cdA := ChainData{
cdA := chain.Info{
ChainID: ibc.Chain1.ChainName,
RPCAddr: rpcs[ibc.Chain1.ChainName],
ClientID: ibc.Chain1.ClientID,
}

chainA, err := prepChain(cdA)
chainA, err := chain.PrepChain(cdA)
if err != nil {
return ClientsInfo{}, fmt.Errorf("Error: %w for %v", err, cdA)
}

clientsInfo.ChainA = chainA

cdB := ChainData{
cdB := chain.Info{
ChainID: ibc.Chain2.ChainName,
RPCAddr: rpcs[ibc.Chain2.ChainName],
ClientID: ibc.Chain2.ClientID,
}

chainB, err := prepChain(cdB)
chainB, err := chain.PrepChain(cdB)
if err != nil {
return ClientsInfo{}, fmt.Errorf("Error: %w for %v", err, cdB)
}
Expand All @@ -106,32 +95,3 @@ func GetClientsInfo(ibc *relayer.IBCdata, rpcs map[string]string) (ClientsInfo,

return clientsInfo, nil
}

func prepChain(cd ChainData) (*relayer.Chain, error) {
chain := relayer.Chain{}
providerConfig := cosmos.CosmosProviderConfig{
ChainID: cd.ChainID,
Timeout: rpcTimeout,
KeyringBackend: keyringBackend,
RPCAddr: cd.RPCAddr,
}

provider, err := providerConfig.NewProvider(nil, "", false, cd.ChainID)
if err != nil {
return nil, err
}

err = provider.Init(context.Background())
if err != nil {
return nil, err
}

chain.ChainProvider = provider

err = chain.SetPath(&relayer.PathEnd{ClientID: cd.ClientID})
if err != nil {
return nil, err
}

return &chain, nil
}

0 comments on commit 86abcc9

Please sign in to comment.