mirror of
https://gitea.com/gitea/runner.git
synced 2026-11-04 06:25:32 +00:00
Move the log calls in `internal` onto `logging`, and add what the process-wide logger setup and its tests need: `SetTextFormat` with a line filter for secret masking (replacing `report.MaskingFormatter`), `SetReportCaller`, `SetDefault` and `logtest.SetDefault`. After this only the `logging` package imports logrus. Stacked on https://gitea.com/gitea/runner/pulls/1301. Assisted-by: Codet Co-authored-by: bircni <[email protected]> Reviewed-on: https://gitea.com/gitea/runner/pulls/1302 Reviewed-by: bircni <[email protected]>
67 lines
1.9 KiB
Go
67 lines
1.9 KiB
Go
// Copyright 2026 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package metrics
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"gitea.com/gitea/runner/act/common/logging"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
|
)
|
|
|
|
// StartServer starts an HTTP server that serves Prometheus metrics on /metrics
|
|
// and health checks. The server shuts down when ctx is cancelled.
|
|
// Call Init() before StartServer to register metrics with the Registry.
|
|
func StartServer(ctx context.Context, addr string, readiness func() (bool, string)) {
|
|
srv := &http.Server{
|
|
Addr: addr,
|
|
Handler: NewHTTPHandler(readiness),
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
go func() {
|
|
logging.Infof("metrics server listening on %s", addr)
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
logging.WithError(err).Error("metrics server failed")
|
|
}
|
|
}()
|
|
|
|
go func() {
|
|
<-ctx.Done()
|
|
shutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutCtx); err != nil {
|
|
logging.WithError(err).Warn("metrics server shutdown error")
|
|
}
|
|
}()
|
|
}
|
|
|
|
// NewHTTPHandler returns the metrics and health endpoints used by StartServer.
|
|
func NewHTTPHandler(readiness func() (bool, string)) http.Handler {
|
|
mux := http.NewServeMux()
|
|
mux.Handle("/metrics", promhttp.HandlerFor(Registry, promhttp.HandlerOpts{}))
|
|
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte("ok"))
|
|
})
|
|
mux.HandleFunc("/readyz", func(w http.ResponseWriter, _ *http.Request) {
|
|
ready, reason := true, "ok"
|
|
if readiness != nil {
|
|
ready, reason = readiness()
|
|
}
|
|
if !ready {
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
}
|
|
_, _ = w.Write([]byte(reason))
|
|
})
|
|
|
|
return mux
|
|
}
|