powerdns-remote-http-example/prometheus.go

89 lines
2.0 KiB
Go
Raw Normal View History

2024-09-14 09:12:10 +03:00
package main
import (
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// TODO: more metrics
var (
_promRegistry *prometheus.Registry
_promHttpHandler http.Handler
promOpsProcessed = prometheus.NewCounter(prometheus.CounterOpts{
Name: "processed_ops_total",
Help: "The total number of processed requests",
})
promAddr4Count = prometheus.NewGaugeFunc(prometheus.GaugeOpts{
Name: "ipv4_mapped_addr_count",
Help: "The total number of IPv4-mapped addresses",
}, func() float64 {
var x uint32
addr4.Range(func(key, value any) bool {
x++
return true
})
return float64(x)
})
promAddr6Count = prometheus.NewGaugeFunc(prometheus.GaugeOpts{
Name: "ipv6_mapped_addr_count",
Help: "The total number of IPv6-mapped addresses",
}, func() float64 {
var x uint32
addr6.Range(func(key, value any) bool {
x++
return true
})
return float64(x)
})
labelStringReplacer *strings.Replacer = strings.NewReplacer(
"\"", "",
"'", "",
)
)
func setupPrometheus(r *gin.Engine) {
_promRegistry = prometheus.NewRegistry()
_promRegistry.MustRegister(promOpsProcessed)
_promRegistry.MustRegister(promAddr4Count)
_promRegistry.MustRegister(promAddr6Count)
_promHttpHandler = promhttp.HandlerFor(_promRegistry, promhttp.HandlerOpts{
Registry: _promRegistry,
EnableOpenMetrics: true,
ErrorHandling: promhttp.ContinueOnError,
ErrorLog: log.Default(),
DisableCompression: true,
})
r.GET("/metrics", promHttpHandler)
r.GET("/metrics/", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/metrics")
})
}
func promSanitizeLabel(str string, fallback string) string {
out := strings.ToValidUTF8(str, "")
out = labelStringReplacer.Replace(out)
out = strings.TrimSpace(out)
if out == "" {
return fallback
}
return out
}
func promHttpHandler(c *gin.Context) {
promOpsProcessed.Inc()
_promHttpHandler.ServeHTTP(c.Writer, c.Request)
}