2024-06-04 03:20:21 +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
|
|
|
|
|
2024-07-07 16:11:02 +03:00
|
|
|
promOpsProcessed = prometheus.NewCounter(prometheus.CounterOpts{
|
2024-06-04 03:20:21 +03:00
|
|
|
Name: "processed_ops_total",
|
|
|
|
Help: "The total number of processed requests",
|
|
|
|
})
|
|
|
|
|
2024-07-07 16:11:02 +03:00
|
|
|
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)
|
|
|
|
})
|
|
|
|
|
2024-06-04 03:20:21 +03:00
|
|
|
labelStringReplacer *strings.Replacer = strings.NewReplacer(
|
|
|
|
"\"", "",
|
|
|
|
"'", "",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
func setupPrometheus(r *gin.Engine) {
|
|
|
|
_promRegistry = prometheus.NewRegistry()
|
2024-07-07 16:11:02 +03:00
|
|
|
_promRegistry.MustRegister(promOpsProcessed)
|
|
|
|
_promRegistry.MustRegister(promAddr4Count)
|
|
|
|
_promRegistry.MustRegister(promAddr6Count)
|
2024-06-04 03:20:21 +03:00
|
|
|
|
|
|
|
_promHttpHandler = promhttp.HandlerFor(_promRegistry, promhttp.HandlerOpts{
|
|
|
|
Registry: _promRegistry,
|
|
|
|
EnableOpenMetrics: true,
|
|
|
|
ErrorHandling: promhttp.ContinueOnError,
|
|
|
|
ErrorLog: log.Default(),
|
|
|
|
})
|
|
|
|
|
|
|
|
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) {
|
2024-07-07 16:11:02 +03:00
|
|
|
promOpsProcessed.Inc()
|
2024-06-04 03:20:21 +03:00
|
|
|
|
|
|
|
_promHttpHandler.ServeHTTP(c.Writer, c.Request)
|
|
|
|
}
|