Skip to content

Commit

Permalink
Expose prometheus metrics at /metrics endpoint (#168)
Browse files Browse the repository at this point in the history
Co-authored-by: Baptiste Lefrancois <[email protected]>
  • Loading branch information
lebaptiste and Baptiste Lefrancois authored Jul 8, 2020
1 parent 5b98ac2 commit 70e8798
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 9 deletions.
12 changes: 3 additions & 9 deletions components/metrics/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,15 @@ func ServeHTTP(addr string, registry *prometheus.Registry) (cancel func()) {
})
server := http.Server{
Addr: addr,
Handler: handler,
Handler: router,
}

go func() {
err := server.ListenAndServe()
if err != nil {
if err != http.ErrServerClosed {
panic(err)
}
}()

wait := make(chan struct{})
go func() {
<-wait
server.Close()
}()

return func() { close(wait) }
return func() { _ = server.Close() }
}
65 changes: 65 additions & 0 deletions components/metrics/http_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package metrics_test

import (
"net/http"
"testing"
"time"

"github.com/ThreeDotsLabs/watermill/components/metrics"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)

func TestCreateRegistryAndServeHTTP_metrics_endpoint(t *testing.T) {
reg, cancel := metrics.CreateRegistryAndServeHTTP(":8090")
defer cancel()
err := reg.Register(prometheus.NewBuildInfoCollector())
if err != nil {
t.Fatal(errors.Wrap(err, "registration of prometheus build info collector failed"))
}
waitServerReady(t, "http://localhost:8090")
resp, err := http.DefaultClient.Get("http://localhost:8090/metrics")
if resp != nil {
defer resp.Body.Close()
}

if err != nil {
t.Fatal(errors.Wrap(err, "call to metrics endpoint failed"))
}
assert.NotNil(t, resp)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}

func TestCreateRegistryAndServeHTTP_unknown_endpoint(t *testing.T) {
reg, cancel := metrics.CreateRegistryAndServeHTTP(":8091")
defer cancel()
err := reg.Register(prometheus.NewBuildInfoCollector())
if err != nil {
t.Error(errors.Wrap(err, "registration of prometheus build info collector failed"))
}
waitServerReady(t, "http://localhost:8091")
resp, err := http.DefaultClient.Get("http://localhost:8091/unknown")
if resp != nil {
defer resp.Body.Close()
}

if err != nil {
t.Fatal(errors.Wrap(err, "call to unknown endpoint failed"))
}
assert.NotNil(t, resp)
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
}

// server might have small delay before being able to server traffic
func waitServerReady(t *testing.T, addr string) {
for i := 0; i < 50; i++ {
_, err := http.DefaultClient.Get(addr)
// assume server ready when no err anymore
if err == nil {
return
}
time.Sleep(100 * time.Millisecond)
continue
}
}

0 comments on commit 70e8798

Please sign in to comment.