http.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package server
  13. import (
  14. "context"
  15. "fmt"
  16. "net/http"
  17. "time"
  18. "github.com/prometheus/client_golang/prometheus"
  19. "github.com/prometheus/client_golang/prometheus/promhttp"
  20. ctrl "sigs.k8s.io/controller-runtime"
  21. )
  22. const (
  23. // DefaultMetricsPort is the default port for the HTTP metrics server
  24. DefaultMetricsPort = 8081
  25. // DefaultMetricsPath is the default path for the metrics endpoint
  26. DefaultMetricsPath = "/metrics"
  27. )
  28. var metricsLog = ctrl.Log.WithName("metrics-server")
  29. // MetricsServer serves Prometheus metrics via HTTP
  30. type MetricsServer struct {
  31. server *http.Server
  32. registry *prometheus.Registry
  33. }
  34. // NewMetricsServer creates a new HTTP metrics server
  35. func NewMetricsServer(port int, registry *prometheus.Registry) *MetricsServer {
  36. if registry == nil {
  37. registry = prometheus.NewRegistry()
  38. }
  39. mux := http.NewServeMux()
  40. mux.Handle(DefaultMetricsPath, promhttp.HandlerFor(registry, promhttp.HandlerOpts{
  41. ErrorHandling: promhttp.ContinueOnError,
  42. }))
  43. // Add health check endpoint
  44. mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
  45. w.WriteHeader(http.StatusOK)
  46. w.Write([]byte("ok"))
  47. })
  48. server := &http.Server{
  49. Addr: fmt.Sprintf(":%d", port),
  50. Handler: mux,
  51. ReadHeaderTimeout: 10 * time.Second,
  52. ReadTimeout: 30 * time.Second,
  53. WriteTimeout: 30 * time.Second,
  54. IdleTimeout: 90 * time.Second,
  55. }
  56. return &MetricsServer{
  57. server: server,
  58. registry: registry,
  59. }
  60. }
  61. // Start starts the HTTP metrics server
  62. func (m *MetricsServer) Start(ctx context.Context) error {
  63. metricsLog.Info("Starting metrics server", "addr", m.server.Addr, "path", DefaultMetricsPath)
  64. // Start server in goroutine
  65. errChan := make(chan error, 1)
  66. go func() {
  67. if err := m.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  68. errChan <- fmt.Errorf("metrics server error: %w", err)
  69. }
  70. }()
  71. // Wait for context cancellation or server error
  72. select {
  73. case <-ctx.Done():
  74. metricsLog.Info("Shutting down metrics server")
  75. shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  76. defer cancel()
  77. if err := m.server.Shutdown(shutdownCtx); err != nil {
  78. return fmt.Errorf("metrics server shutdown error: %w", err)
  79. }
  80. return nil
  81. case err := <-errChan:
  82. return err
  83. }
  84. }
  85. // GetRegistry returns the Prometheus registry
  86. func (m *MetricsServer) GetRegistry() *prometheus.Registry {
  87. return m.registry
  88. }