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

chore: backport #138 #140

Merged
merged 2 commits into from
Feb 18, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## Unreleased

### Improvements

- [#138](https://github.com/babylonlabs-io/btc-staker/pull/138) Adds prometheus metrics
configuration to enabled it (disabled by default).

## v0.15.2

* [#127](https://github.com/babylonlabs-io/btc-staker/pull/127) Add support for
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,23 @@ ZMQPubRawBlock = tcp://127.0.0.1:29001
ZMQPubRawTx = tcp://127.0.0.1:29002
```

#### Metrics configuration

by default prometheus metrics are disabled, although it is possible to enabled it
in the config file.

```bash
[metricsconfig]
# if it should be enabled.
Enabled = false

# host of prometheus server.
Host = 127.0.0.1

# port of prometheus server.
ServerPort = 2112
```

To see the complete list of configuration options, check the `stakerd.conf` file.

## 4. Starting staker daemon
Expand Down
6 changes: 4 additions & 2 deletions cmd/stakerd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,10 @@ func main() {
dbBackend,
)

addr := fmt.Sprintf("%s:%d", cfg.MetricsConfig.Host, cfg.MetricsConfig.ServerPort)
metrics.Start(cfgLogger, addr, stakerMetrics.Registry)
if cfg.MetricsConfig.Enabled {
addr := fmt.Sprintf("%s:%d", cfg.MetricsConfig.Host, cfg.MetricsConfig.ServerPort)
metrics.Start(cfgLogger, addr, stakerMetrics.Registry)
}

if err = service.RunUntilShutdown(ctx); err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
Expand Down
22 changes: 14 additions & 8 deletions metrics/prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package metrics
import (
"errors"
"net/http"

//nolint:revive
_ "net/http/pprof"
"regexp"
Expand All @@ -14,18 +15,27 @@ import (
)

func Start(logger *logrus.Logger, addr string, reg *prometheus.Registry) {
go start(logger, addr, reg)
svr := Server(logger, addr, reg)

go func() {
err := svr.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Errorf("prometheus server got err: %v", err)
}
}()
}

func start(logger *logrus.Logger, addr string, reg *prometheus.Registry) {
func Server(logger *logrus.Logger, addr string, reg *prometheus.Registry) *http.Server {
// Add Go module build info.
reg.MustRegister(collectors.NewBuildInfoCollector())
reg.MustRegister(collectors.NewGoCollector(
collectors.WithGoCollectorRuntimeMetrics(collectors.GoRuntimeMetricsRule{Matcher: regexp.MustCompile("/.*")})),
)

mux := http.NewServeMux()

// Expose the registered metrics via HTTP.
http.Handle("/metrics", promhttp.HandlerFor(
mux.Handle("/metrics", promhttp.HandlerFor(
reg,
promhttp.HandlerOpts{
// Opt into OpenMetrics to support exemplars.
Expand All @@ -35,9 +45,5 @@ func start(logger *logrus.Logger, addr string, reg *prometheus.Registry) {

logger.Infof("Successfully started Prometheus metrics server at %s", addr)

err := http.ListenAndServe(addr, nil)

if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Errorf("prometheus server got err: %v", err)
}
return &http.Server{Addr: addr, Handler: mux}
}
48 changes: 48 additions & 0 deletions metrics/prometheus_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package metrics_test

import (
"context"
"fmt"
"io"
"strings"
"testing"

//nolint:revive

"net/http"
"net/http/httptest"
_ "net/http/pprof"

"github.com/stretchr/testify/require"

"github.com/babylonlabs-io/btc-staker/itest/testutil"
"github.com/babylonlabs-io/btc-staker/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
)

func TestMetrics(t *testing.T) {
t.Parallel()
addr := fmt.Sprintf("127.0.0.1:%d", testutil.AllocateUniquePort(t))
testRegistry := prometheus.NewRegistry()

server := metrics.Server(logrus.New(), addr, testRegistry)

// Use httptest to simulate a real HTTP server
testServer := httptest.NewServer(server.Handler)
defer testServer.Close()

req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, testServer.URL+"/metrics", nil)
require.NoError(t, err)

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
defer resp.Body.Close()

fullBody, err := io.ReadAll(resp.Body)
require.NoError(t, err)

bodyString := string(fullBody)
require.True(t, strings.Contains(bodyString, "metrics"))
}
3 changes: 3 additions & 0 deletions stakercfg/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const (

// MetricsConfig defines the server's basic configuration
type MetricsConfig struct {
// Enalbed if the prometheus server should be enabled
Enabled bool `long:"enabled" description:"if it should be enabled."`
// IP of the prometheus server
Host string `long:"host" description:"host of prometheus server."`
// Port of the prometheus server
Expand All @@ -33,6 +35,7 @@ func (cfg *MetricsConfig) Validate() error {

func DefaultMetricsConfig() MetricsConfig {
return MetricsConfig{
Enabled: false,
ServerPort: defaultMetricsServerPort,
Host: defaultMetricsHost,
}
Expand Down
Loading