p2p-health-bot/stats.go

66 lines
1.6 KiB
Go
Raw Permalink Normal View History

2018-05-24 15:32:39 +00:00
package main
import (
2018-06-15 15:07:48 +00:00
"fmt"
2018-05-24 15:51:16 +00:00
"log"
"net/http"
2018-05-24 15:32:39 +00:00
"time"
2018-05-24 15:51:16 +00:00
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
msgsSent = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "msgs_sent",
Help: "Messages sent by bot",
})
msgsReceived = prometheus.NewGauge(prometheus.GaugeOpts{
Name: "msgs_received",
Help: "Message responses received by bot",
})
msgsLatencies = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "msgs_responses_latency",
2018-06-28 14:40:43 +00:00
Help: "Latencies of responses to bot messages in ms",
Buckets: []float64{100, 500, 1000, 2000, 3000, 4000, 5000, 7500, 10000, 20000, 30000},
}, []string{"bot"})
2018-05-24 15:32:39 +00:00
)
2018-05-24 15:51:16 +00:00
func init() {
// Metrics have to be registered to be exposed
prometheus.MustRegister(msgsSent)
prometheus.MustRegister(msgsReceived)
prometheus.MustRegister(msgsLatencies)
}
2018-05-24 15:32:39 +00:00
// Stats represents messages' statistics.
type Stats struct {
}
2018-06-15 15:07:48 +00:00
// For verifying the service is up
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "OK")
}
2018-05-24 15:32:39 +00:00
// NewStats returns new empty Stats object.
2018-05-24 15:51:16 +00:00
func NewStats(statsPort string) *Stats {
go func() {
http.Handle("/metrics", promhttp.Handler())
2018-06-15 15:07:48 +00:00
// Add most trivial healthcheck
http.HandleFunc("/health", healthHandler)
2018-05-24 15:51:16 +00:00
log.Fatal(http.ListenAndServe(statsPort, nil))
}()
2018-05-24 15:32:39 +00:00
return &Stats{}
}
// AddSent adds information about sent messages.
func (s *Stats) AddSent() {
2018-05-24 15:51:16 +00:00
msgsSent.Inc()
2018-05-24 15:32:39 +00:00
}
// AddRoundtrip adds information about successful message roundtrip.
func (s *Stats) AddRountrip(d time.Duration) {
2018-05-24 15:51:16 +00:00
msgsReceived.Inc()
msgsLatencies.WithLabelValues("default").Observe(float64(d / time.Millisecond))
2018-05-24 15:32:39 +00:00
}