File: metric_server.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (197 lines) | stat: -rw-r--r-- 5,157 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
package observability

import (
	"context"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/http/pprof"
	"sync"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v16/internal/tool/httpz"
	"go.uber.org/zap"
)

const (
	defaultMaxRequestDuration = 15 * time.Second
	shutdownTimeout           = defaultMaxRequestDuration
	readTimeout               = 1 * time.Second
	writeTimeout              = defaultMaxRequestDuration
	idleTimeout               = 1 * time.Minute
)

// Probe is the expected type for probe functions
type Probe func(context.Context) error

// NoopProbe is a placeholder probe for convenience
func NoopProbe(context.Context) error {
	return nil
}

func NewProbeRegistry() *ProbeRegistry {
	return &ProbeRegistry{
		liveness:  make(map[string]Probe),
		readiness: make(map[string]Probe),
	}
}

type ProbeRegistry struct {
	mu        sync.RWMutex
	liveness  map[string]Probe
	readiness map[string]Probe
}

type toggleValue struct {
	value int32
}

func (t *toggleValue) SetTrue() {
	atomic.StoreInt32(&t.value, 1)
}

func (t *toggleValue) True() bool {
	return atomic.LoadInt32(&t.value) == 1
}

func (p *ProbeRegistry) RegisterLivenessProbe(key string, probe Probe) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.liveness[key] = probe
}

func (p *ProbeRegistry) RegisterReadinessProbe(key string, probe Probe) {
	p.mu.Lock()
	defer p.mu.Unlock()
	p.readiness[key] = probe
}

func (p *ProbeRegistry) Liveness(ctx context.Context) error {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return execProbeMap(ctx, p.liveness)
}

func (p *ProbeRegistry) Readiness(ctx context.Context) error {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return execProbeMap(ctx, p.readiness)
}

func (p *ProbeRegistry) RegisterReadinessToggle(key string) func() {
	var value toggleValue
	p.RegisterReadinessProbe(key, func(ctx context.Context) error {
		if value.True() {
			return nil
		}
		return errors.New("not ready yet")
	})
	return value.SetTrue
}

func execProbeMap(ctx context.Context, probes map[string]Probe) error {
	for key, probe := range probes {
		err := probe(ctx)
		if err != nil {
			return fmt.Errorf("%s: %w", key, err)
		}
	}
	return nil
}

type MetricServer struct {
	Log *zap.Logger
	Api modshared.Api
	// Name is the name of the application.
	Name                  string
	Listener              net.Listener
	PrometheusUrlPath     string
	LivenessProbeUrlPath  string
	ReadinessProbeUrlPath string
	Gatherer              prometheus.Gatherer
	Registerer            prometheus.Registerer
	ProbeRegistry         *ProbeRegistry
}

func (s *MetricServer) Run(ctx context.Context) error {
	srv := &http.Server{ // nolint: gosec
		Handler:      s.ConstructHandler(), // nolint: contextcheck
		WriteTimeout: writeTimeout,
		ReadTimeout:  readTimeout,
		IdleTimeout:  idleTimeout,
	}
	return httpz.RunServer(ctx, srv, s.Listener, 0, shutdownTimeout)
}

func (s *MetricServer) ConstructHandler() http.Handler {
	mux := http.NewServeMux()
	s.probesHandler(mux) // nolint: contextcheck
	s.pprofHandler(mux)
	s.prometheusHandler(mux)
	return mux
}

func (s *MetricServer) setHeader(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header()[httpz.ServerHeader] = []string{s.Name}
		next.ServeHTTP(w, r)
	})
}

func (s *MetricServer) probesHandler(mux *http.ServeMux) {
	mux.Handle(
		s.LivenessProbeUrlPath,
		s.setHeader(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
			err := s.ProbeRegistry.Liveness(request.Context())
			if err != nil {
				s.logAndCapture(request.Context(), "LivenessProbe failed", err)
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.WriteHeader(http.StatusOK)
		})),
	)
	mux.Handle(
		s.ReadinessProbeUrlPath,
		s.setHeader(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
			err := s.ProbeRegistry.Readiness(request.Context())
			if err != nil {
				s.logAndCapture(request.Context(), "ReadinessProbe failed", err)
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.WriteHeader(http.StatusOK)
		})),
	)
}

func (s *MetricServer) prometheusHandler(mux *http.ServeMux) {
	mux.Handle(
		s.PrometheusUrlPath,
		s.setHeader(promhttp.InstrumentMetricHandler(s.Registerer, promhttp.HandlerFor(s.Gatherer, promhttp.HandlerOpts{
			Timeout: defaultMaxRequestDuration,
		}))),
	)
}

func (s *MetricServer) pprofHandler(mux *http.ServeMux) {
	routes := map[string]func(http.ResponseWriter, *http.Request){
		"/debug/pprof/":        pprof.Index,
		"/debug/pprof/cmdline": pprof.Cmdline,
		"/debug/pprof/profile": pprof.Profile,
		"/debug/pprof/symbol":  pprof.Symbol,
		"/debug/pprof/trace":   pprof.Trace,
	}
	for route, handler := range routes {
		mux.Handle(route, s.setHeader(http.HandlerFunc(handler)))
	}
}

func (s *MetricServer) logAndCapture(ctx context.Context, msg string, err error) {
	s.Api.HandleProcessingError(ctx, s.Log, modshared.NoAgentId, msg, err)
}