-
Notifications
You must be signed in to change notification settings - Fork 6
/
prometheus.go
271 lines (216 loc) · 7.02 KB
/
prometheus.go
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package prometheus
import (
"bytes"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/alibaba/pairec/v2/log"
"github.com/alibaba/pairec/v2/service/metrics"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/expfmt"
)
const (
_ = iota // ignore first value by assigning to blank identifier
KB float64 = 1 << (10 * iota)
MB
)
const defaultSubsystem = "pairec"
const defaultJob = "recommend"
// defaultReqDurBuckets is the buckets for request duration. Here, we use the prometheus defaults
// which are for ~10s request length max: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
var defaultReqDurBuckets = prometheus.DefBuckets
// defaultReqSzBuckets is the buckets for request size. Here we define a spectrom from 1KB thru 1NB up to 10MB.
var defaultReqSzBuckets = []float64{1.0 * KB, 2.0 * KB, 5.0 * KB, 10.0 * KB, 100 * KB, 500 * KB, 1.0 * MB, 2.5 * MB, 5.0 * MB, 10.0 * MB}
// defaultResSzBuckets is the buckets for response size. Here we define a spectrom from 1KB thru 1NB up to 10MB.
var defaultResSzBuckets = []float64{1.0 * KB, 2.0 * KB, 5.0 * KB, 10.0 * KB, 100 * KB, 500 * KB, 1.0 * MB, 2.5 * MB, 5.0 * MB, 10.0 * MB}
type RequestCounterLabelMappingFunc func(req *http.Request) string
// Prometheus contains the metrics gathered by the instance and its path
type Prometheus struct {
reqCnt *prometheus.CounterVec
reqDur, reqSz, resSz *prometheus.HistogramVec
ReqDurBuckets, ReqSzBuckets, ResSzBuckets []float64
Subsystem string
Ppg PushGateway
}
// PushGateway contains the configuration for pushing to a Prometheus pushgateway (optional)
type PushGateway struct {
// Push interval in seconds
//lint:ignore ST1011 renaming would be breaking change
PushIntervalSeconds time.Duration
// Push Gateway URL in format http://domain:port
// where JOBNAME can be any string of your choice
PushGatewayURL string
// pushgateway job name, defaults to "recommend"
Job string
}
// NewPrometheus generates a new set of metrics with a certain subsystem name
func NewPrometheus(options ...PrometheusOption) *Prometheus {
p := &Prometheus{
Subsystem: defaultSubsystem,
ReqDurBuckets: defaultReqDurBuckets,
ReqSzBuckets: defaultReqSzBuckets,
ResSzBuckets: defaultResSzBuckets,
}
for _, option := range options {
option(p)
}
p.registerMetrics()
if p.Ppg.PushGatewayURL != "" && p.Ppg.PushIntervalSeconds > 0 {
p.startPushTicker()
}
return p
}
func (p *Prometheus) Push(pushGatewayURL string, pushIntervalSecs int, job string) {
p.Ppg.PushGatewayURL = pushGatewayURL
p.Ppg.PushIntervalSeconds = time.Duration(pushIntervalSecs)
if job != "" {
p.Ppg.Job = job
} else {
p.Ppg.Job = defaultJob
}
if p.Ppg.PushGatewayURL != "" && p.Ppg.PushIntervalSeconds > 0 {
p.startPushTicker()
}
}
func (p *Prometheus) getMetrics() []byte {
out := &bytes.Buffer{}
metricFamilies, _ := prometheus.DefaultGatherer.Gather()
for i := range metricFamilies {
expfmt.MetricFamilyToText(out, metricFamilies[i])
}
return out.Bytes()
}
func (p *Prometheus) getCustomMetrics() []byte {
out := &bytes.Buffer{}
metricFamilies, _ := metrics.CustomRegister.Gather()
for i := range metricFamilies {
expfmt.MetricFamilyToText(out, metricFamilies[i])
}
return out.Bytes()
}
func (p *Prometheus) getPushGatewayURL() string {
h, _ := os.Hostname()
if p.Ppg.Job == "" {
p.Ppg.Job = "recommend"
}
return p.Ppg.PushGatewayURL + "/metrics/job/" + p.Ppg.Job + "/instance/" + h
}
func (p *Prometheus) sendMetricsToPushGateway(metrics []byte) {
req, err := http.NewRequest("POST", p.getPushGatewayURL(), bytes.NewBuffer(metrics))
if err != nil {
//log.Errorf("failed to create push gateway request: %v", err)
return
}
client := &http.Client{}
if _, err = client.Do(req); err != nil {
log.Error(fmt.Sprintf("Error sending to push gateway: %v", err))
}
}
func (p *Prometheus) startPushTicker() {
ticker := time.NewTicker(time.Second * p.Ppg.PushIntervalSeconds)
go func() {
for range ticker.C {
p.sendMetricsToPushGateway(p.getMetrics())
p.sendMetricsToPushGateway(p.getCustomMetrics())
}
}()
}
func (p *Prometheus) registerMetrics() {
subsystem := p.Subsystem
p.reqCnt = prometheus.NewCounterVec(
prometheus.CounterOpts{
Subsystem: subsystem,
Name: "requests_total",
Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
[]string{"code", "method", "host", "url"},
)
p.reqDur = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Subsystem: subsystem,
Name: "request_duration_seconds",
Help: "The HTTP request latencies in seconds.",
Buckets: p.ReqDurBuckets,
},
[]string{"code", "method", "host", "url"},
)
p.reqSz = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Subsystem: subsystem,
Name: "request_size_bytes",
Help: "The HTTP request sizes in bytes.",
Buckets: p.ReqSzBuckets,
},
[]string{"code", "method", "host", "url"},
)
p.resSz = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Subsystem: subsystem,
Name: "response_size_bytes",
Help: "The HTTP response sizes in bytes.",
Buckets: p.ResSzBuckets,
},
[]string{"code", "method", "host", "url"},
)
collectors := map[string]prometheus.Collector{
"requests_total": p.reqCnt,
"request_duration_seconds": p.reqDur,
"request_size_bytes": p.reqSz,
"response_size_bytes": p.resSz,
}
for name := range collectors {
if err := prometheus.Register(collectors[name]); err != nil {
log.Error(fmt.Sprintf("%s could not be registered in Prometheus: %v", name, err))
}
}
}
type IResponseWriter interface {
http.ResponseWriter
StatusCode() int
Size() int
}
// HandlerFunc defines handler function for middleware
func (p *Prometheus) HandlerFunc(next func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
start := time.Now()
reqSz := computeApproximateRequestSize(request)
next(writer, request)
status := http.StatusOK
var size int
if rw, ok := writer.(IResponseWriter); ok {
status = rw.StatusCode()
size = rw.Size()
}
elapsed := float64(time.Since(start)) / float64(time.Second)
url := request.URL.Path
host := request.Host
statusStr := strconv.Itoa(status)
p.reqDur.WithLabelValues(statusStr, request.Method, host, url).Observe(elapsed)
p.reqCnt.WithLabelValues(statusStr, request.Method, host, url).Inc()
p.reqSz.WithLabelValues(statusStr, request.Method, host, url).Observe(float64(reqSz))
resSz := float64(size)
p.resSz.WithLabelValues(statusStr, request.Method, host, url).Observe(resSz)
}
}
func computeApproximateRequestSize(r *http.Request) int {
s := 0
if r.URL != nil {
s = len(r.URL.Path)
}
s += len(r.Method)
s += len(r.Proto)
for name, values := range r.Header {
s += len(name)
for _, value := range values {
s += len(value)
}
}
s += len(r.Host)
// N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
if r.ContentLength != -1 {
s += int(r.ContentLength)
}
return s
}