2019-09-10 17:52:45 +02:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
|
|
bolt "go.etcd.io/bbolt"
|
|
|
|
|
2019-09-15 17:43:09 +02:00
|
|
|
"gitea.hashru.nl/dsprenkels/rushlink/db"
|
2019-09-10 17:52:45 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
METRICS_ADDR = "127.0.0.1:58614"
|
|
|
|
)
|
|
|
|
|
|
|
|
func StartMetricsServer() {
|
|
|
|
var (
|
|
|
|
_ = promauto.NewGaugeFunc(prometheus.GaugeOpts{
|
|
|
|
Namespace: "rushlink",
|
|
|
|
Subsystem: "shorten",
|
|
|
|
Name: "urls_total",
|
|
|
|
Help: "The current amount of shortened urls in the database.",
|
|
|
|
}, func() float64 {
|
|
|
|
var metric float64
|
|
|
|
if err := db.DB.View(func(tx *bolt.Tx) error {
|
|
|
|
bucket := tx.Bucket([]byte("shorten"))
|
|
|
|
if bucket == nil {
|
|
|
|
return errors.New("bucket 'shorten' could not be found")
|
|
|
|
}
|
|
|
|
metric = float64(bucket.Stats().KeyN)
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
|
|
log.Printf("error: %v", errors.Wrap(err, "fetching shorten_urls_total metric"))
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return metric
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
router := mux.NewRouter()
|
|
|
|
router.Handle("/metrics", promhttp.Handler()).Methods("GET")
|
|
|
|
srv := &http.Server{
|
|
|
|
Handler: router,
|
|
|
|
Addr: METRICS_ADDR,
|
|
|
|
WriteTimeout: 15 * time.Second,
|
|
|
|
ReadTimeout: 15 * time.Second,
|
|
|
|
}
|
|
|
|
log.Fatal(srv.ListenAndServe())
|
|
|
|
}
|