Implement metrics collection for API server (#143)

This commit is contained in:
Knut Ahlers 2023-10-23 14:05:20 +02:00 committed by GitHub
parent 1623e09225
commit 5ad6449757
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 402 additions and 95 deletions

46
main.go
View file

@ -19,6 +19,7 @@ import (
file_helpers "github.com/Luzifer/go_helpers/v2/file"
http_helpers "github.com/Luzifer/go_helpers/v2/http"
"github.com/Luzifer/ots/pkg/customization"
"github.com/Luzifer/ots/pkg/metrics"
"github.com/Luzifer/rconfig/v2"
)
@ -99,6 +100,9 @@ func main() {
os.Exit(0)
}
// Initialize metrics collector
collector := metrics.New()
// Initialize index template in order not to parse it multiple times
source, err := assets.ReadFile("index.html")
if err != nil {
@ -111,27 +115,49 @@ func main() {
if err != nil {
logrus.WithError(err).Fatal("initializing storage")
}
api := newAPI(store)
api := newAPI(store, collector)
// Initialize server
r := mux.NewRouter()
r.Use(http_helpers.GzipHandler)
api.Register(r.PathPrefix("/api").Subrouter())
r.HandleFunc("/", handleIndex)
r.PathPrefix("/").HandlerFunc(assetDelivery)
r.Handle("/metrics", metrics.Handler()).
Methods(http.MethodGet).
MatcherFunc(func(r *http.Request, _ *mux.RouteMatch) bool {
return requestInSubnetList(r, cust.MetricsAllowedSubnets)
})
r.HandleFunc("/", handleIndex).
Methods(http.MethodGet)
r.PathPrefix("/").HandlerFunc(assetDelivery).
Methods(http.MethodGet)
var hdl http.Handler = r
hdl = http_helpers.GzipHandler(hdl)
hdl = http_helpers.NewHTTPLogHandlerWithLogger(hdl, logrus.StandardLogger())
server := &http.Server{
Addr: cfg.Listen,
Handler: hdl,
ReadHeaderTimeout: time.Second,
}
// Start periodic stored metrics update (required for multi-instance
// OTS hosting as other instances will create / delete secrets and
// we need to keep up with that)
go func() {
for t := time.NewTicker(time.Minute); ; <-t.C {
updateStoredSecretsCount(store, collector)
}
}()
// Start server
logrus.WithFields(logrus.Fields{
"secret_expiry": time.Duration(cfg.SecretExpiry) * time.Second,
"version": version,
}).Info("ots started")
server := &http.Server{
Addr: cfg.Listen,
Handler: http_helpers.NewHTTPLogHandlerWithLogger(r, logrus.StandardLogger()),
ReadHeaderTimeout: time.Second,
}
if err = server.ListenAndServe(); err != nil {
logrus.WithError(err).Fatal("HTTP server quit unexpectedly")
}