Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add cosmos_wallet_balance metric #12

Merged
merged 6 commits into from
Sep 13, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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",status="success"} 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
46 changes: 46 additions & 0 deletions pkg/account/account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package account

import (
"context"

"cosmossdk.io/math"

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

const (
successStatus = "success"
errorStatus = "error"
)

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

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

ctx := context.Background()
jlehtimaki marked this conversation as resolved.
Show resolved Hide resolved

coins, err := chain.ChainProvider.QueryBalanceWithAddress(ctx, a.Address)
if err != nil {
a.Status = errorStatus

return err
}

a.Balance = coins.AmountOf(a.Denom)
a.Status = successStatus

return 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(info Info) (*relayer.Chain, error) {
chain := relayer.Chain{}
providerConfig := cosmos.CosmosProviderConfig{
ChainID: info.ChainID,
Timeout: rpcTimeout,
KeyringBackend: keyringBackend,
RPCAddr: info.RPCAddr,
}

provider, err := providerConfig.NewProvider(nil, "", false, info.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: info.ClientID})
if err != nil {
return nil, err
}

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

import (
"math/big"
"sync"

"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 +13,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", "status"}, 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 +67,42 @@ 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))

var wg sync.WaitGroup

for _, a := range wb.Accounts {
wg.Add(1)

go func(account account.Account) {
defer wg.Done()

balance := 0.0

err := account.GetBalance(wb.RPCs)
if err != nil {
log.Error(err.Error(), zap.Any("account", account))
} else {
// Convert to a big float to get a float64 for metrics
balance, _ = big.NewFloat(0.0).SetInt(account.Balance.BigInt()).Float64()
}

ch <- prometheus.MustNewConstMetric(
walletBalance,
prometheus.GaugeValue,
balance,
[]string{account.Address, account.ChainID, account.Denom, account.Status}...,
)
}(a)
}

wg.Wait()

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
}