/
metrics.go
361 lines (316 loc) · 10.8 KB
/
metrics.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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
package cfg
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
"time"
"github.com/apex/log"
"github.com/kafkaesque-io/pulsar-monitor/src/metering"
"github.com/kafkaesque-io/pulsar-monitor/src/util"
"github.com/prometheus/client_golang/prometheus"
)
var (
metrics = make(map[string]*prometheus.GaugeVec)
summaries = make(map[string]*prometheus.SummaryVec)
counters = make(map[string]*prometheus.CounterVec)
)
const (
funcTopicSubsystem = "func_topic"
pubSubSubsystem = "pubsub"
websocketSubsystem = "websocket"
heartbeatSubsystem = "heartbeat"
downtimeSubsystem = "downtime"
k8sBrokerSubsystem = "k8s_broker"
k8sBookkeeperSubsystem = "k8s_bookkeeper"
k8sZookeeperSubsystem = "k8s_zookeeper"
k8sProxySubsystem = "k8s_proxy"
k8sUndefinedSubsystem = "k8s_undefined"
)
// This is Premetheus data modelling and naming convention
// https://prometheus.io/docs/practices/naming/
// https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels
// TODO add regex evaluation against names [a-zA-Z_:][a-zA-Z0-9_:]*
// TenantsGaugeOpt is the description for rest api tenant counts
func TenantsGaugeOpt() prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "pulsar",
Subsystem: "tenant",
Name: "size",
Help: "Plusar rest api tenant counts",
}
}
// OfflinePodGaugeOpt is offline pods counter
func OfflinePodGaugeOpt(subsystem, desc string) prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "pulsar",
Subsystem: subsystem,
Name: "offline_counter",
Help: desc,
}
}
// SiteLatencyGaugeOpt is the description for hosting site latency gauge
func SiteLatencyGaugeOpt() prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "website",
Subsystem: "webendpoint",
Name: "latency_ms",
Help: "website endpoint monitor and latency in ms",
}
}
// MsgLatencyGaugeOpt is the description for Pulsar message latency gauge
func MsgLatencyGaugeOpt(typeName, desc string) prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "pulsar",
Subsystem: typeName,
Name: "latency_ms",
Help: desc,
}
}
// HeartbeatCounterOpt is the description for heart beat counter
func HeartbeatCounterOpt() prometheus.CounterOpts {
return prometheus.CounterOpts{
Namespace: "pulsar",
Subsystem: "monitor",
Name: "counter",
Help: "Pulsar cluster monitor heartbeat",
}
}
// PubSubDowntimeGaugeOpt is the description for downtime summary
func PubSubDowntimeGaugeOpt() prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "pulsar",
Subsystem: "pubsub",
Name: "downtime_seconds",
Help: "Pulsar pubsub downtime in seconds",
}
}
// FuncLatencyGaugeOpt is the description of Pulsar Function latency gauge
func FuncLatencyGaugeOpt() prometheus.GaugeOpts {
return prometheus.GaugeOpts{
Namespace: "pulsar",
Subsystem: "function",
Name: "latency_ms",
Help: "Plusar message latency in ms",
}
}
// PromGaugeInt registers gauge reading in integer
func PromGaugeInt(opt prometheus.GaugeOpts, cluster string, num int) {
PromGauge(opt, cluster, float64(num))
}
// PromGauge registers gauge reading
func PromGauge(opt prometheus.GaugeOpts, cluster string, num float64) {
key := getMetricKey(opt)
if promMetric, ok := metrics[key]; ok {
promMetric.WithLabelValues(cluster).Set(num)
} else {
newMetric := prometheus.NewGaugeVec(opt, []string{"device"})
prometheus.Register(newMetric)
newMetric.WithLabelValues(cluster).Set(num)
metrics[key] = newMetric
}
}
// PromCounter registers counter and increment
func PromCounter(opt prometheus.CounterOpts, cluster string) {
key := fmt.Sprintf("%s-%s-%s", opt.Namespace, opt.Subsystem, opt.Name)
if promMetric, ok := counters[key]; ok {
promMetric.WithLabelValues(cluster).Inc()
} else {
newMetric := prometheus.NewCounterVec(opt, []string{"device"})
prometheus.Register(newMetric)
newMetric.WithLabelValues(cluster).Inc()
counters[key] = newMetric
}
}
// PromLatencySum expose monitoring metrics to Prometheus
func PromLatencySum(opt prometheus.GaugeOpts, cluster string, latency time.Duration) {
key := getMetricKey(opt)
ms := float64(latency / time.Millisecond)
if promMetric, ok := metrics[key]; ok {
promMetric.WithLabelValues(cluster).Set(ms)
} else {
newMetric := prometheus.NewGaugeVec(opt, []string{"device"})
prometheus.Register(newMetric)
newMetric.WithLabelValues(cluster).Set(ms)
metrics[key] = newMetric
}
if summary, ok := summaries[key]; ok {
summary.WithLabelValues(cluster).Observe(ms)
} else {
newSummary := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: opt.Namespace,
Subsystem: opt.Subsystem,
Name: fmt.Sprintf("%s_hst", opt.Name),
Help: opt.Help,
Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
MaxAge: 30 * time.Minute,
AgeBuckets: 3,
BufCap: 500,
}, []string{"device"})
prometheus.MustRegister(newSummary)
newSummary.WithLabelValues(cluster).Observe(ms)
summaries[key] = newSummary
}
}
func getMetricKey(opt prometheus.GaugeOpts) string {
return fmt.Sprintf("%s-%s-%s", opt.Namespace, opt.Subsystem, opt.Name)
}
// GetGaugeType get the Prometheus Gauge Option based on type/subsystem
func GetGaugeType(nameType string) prometheus.GaugeOpts {
if nameType == funcTopicSubsystem || strings.HasPrefix(nameType, "func_topic") {
return MsgLatencyGaugeOpt(funcTopicSubsystem, "Plusar function input output topic latency in ms")
}
if nameType == websocketSubsystem {
return MsgLatencyGaugeOpt(websocketSubsystem, "Plusar websocket pubsub topic latency in ms")
}
return MsgLatencyGaugeOpt(pubSubSubsystem, "Plusar pubsub message latency in ms")
}
// GetOfflinePodsCounter returns prometheus GaugeOpts for kubernetes cluster pod offline counter
func GetOfflinePodsCounter(subsystem string) prometheus.GaugeOpts {
switch subsystem {
case k8sBookkeeperSubsystem:
return OfflinePodGaugeOpt(k8sBookkeeperSubsystem, "Pulsar k8s clueter bookkeeper pods offline counter")
case k8sBrokerSubsystem:
return OfflinePodGaugeOpt(k8sBrokerSubsystem, "Pulsar k8s clueter broker pods offline counter")
case k8sProxySubsystem:
return OfflinePodGaugeOpt(k8sProxySubsystem, "Pulsar k8s clueter proxy pods offline counter")
case k8sZookeeperSubsystem:
return OfflinePodGaugeOpt(k8sZookeeperSubsystem, "Pulsar k8s clueter zookeeper pods offline counter")
default:
return OfflinePodGaugeOpt(k8sUndefinedSubsystem, "Pulsar k8s clueter undefined pods offline counter")
}
}
// scrapeLocal scrapes the local metrics
func scrapeLocal() ([]byte, error) {
url := "http://localhost" + GetConfig().PrometheusConfig.Port + "/metrics"
newRequest, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Errorf("make http request to scrape self's prometheus %s error %v", url, err)
return []byte{}, err
}
client := &http.Client{}
response, err := client.Do(newRequest)
if response != nil {
defer response.Body.Close()
}
if err != nil {
log.Errorf("scrape self's prometheus %s error %v", url, err)
return []byte{}, err
}
if response.StatusCode != http.StatusOK {
log.Errorf("scrape self's prometheus %s response status code %d", url, response.StatusCode)
return []byte{}, err
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Errorf("scrape self's prometheus %s read response body error %v", url, err)
return []byte{}, err
}
var rc string
scanner := bufio.NewScanner(strings.NewReader(string(body)))
pattern := fmt.Sprintf(`.*pulsar.*`)
for scanner.Scan() {
text := scanner.Text()
matched, err := regexp.MatchString(pattern, text)
if matched && err == nil {
rc = fmt.Sprintf("%s%s\n", rc, text)
}
}
return []byte(strings.TrimSuffix(rc, "\n")), nil
}
// PushToPrometheusProxy pushes exp data to PrometheusProxy
func PushToPrometheusProxy(proxyURL, authKey string) error {
data, err := scrapeLocal()
if err != nil {
return err
}
req, err := http.NewRequest("POST", proxyURL, bytes.NewBuffer(data))
if err != nil {
log.Errorf("push to prometheus proxy %s error NewRe uest request %v", proxyURL, err)
return err
}
req.Header.Set("Authorization", authKey)
client := &http.Client{Timeout: time.Second * 50}
// Send request
resp, err := client.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
log.Errorf("push to prometheus proxy %s error reading request %v", proxyURL, err)
return err
}
if resp.StatusCode != http.StatusOK {
log.Errorf("push to prometheus proxy %s error status code %v", proxyURL, resp.StatusCode)
return fmt.Errorf("push to prometheus proxy %s error status code %v", proxyURL, resp.StatusCode)
}
return nil
}
// PushToPrometheusProxyThread is the daemon thread that scrape and pushes metrics to prometheus proxy
func PushToPrometheusProxyThread() {
promCfg := GetConfig().PrometheusConfig
if promCfg.PrometheusProxyURL == "" || !promCfg.ExposeMetrics {
log.Infof("This process is not configured to push metrics to prometheus proxy.")
return
}
proxyInstanceURL := promCfg.PrometheusProxyURL + "/" + GetConfig().Name
log.Infof("push to prometheus proxy url %s %t", GetConfig().PrometheusConfig.PrometheusProxyURL, promCfg.ExposeMetrics)
go func(url, apikey string) {
ticker := time.NewTicker(10 * time.Second)
PushToPrometheusProxy(url, apikey)
for {
select {
case <-ticker.C:
PushToPrometheusProxy(url, apikey)
}
}
}(proxyInstanceURL, promCfg.PrometheusProxyAPIKey)
}
// BuildTenantsUsageThread is the daemon thread that builds last 30s tenants usage and expose to Prometheus metrics
func BuildTenantsUsageThread() {
token := GetConfig().Token
if token == "" {
log.Errorf("tenants usage exits since no token is specified")
return
}
prefixURL := GetConfig().BrokersConfig.InClusterRESTURL
if prefixURL == "" {
log.Errorf("tenants usage exits since no in-cluster REST URL prefix is specified")
return
}
name := GetConfig().Name
tenantBytesOutAlertLimit := GetConfig().TenantUsageConfig.OutBytesLimit
interval := time.Duration(metering.SamplingIntervalInSeconds) * time.Second
log.Infof("build tenants uages from %s", prefixURL)
go func(url, jwt, cluster string) {
ticker := time.NewTicker(interval)
usage := metering.NewTenantsUsage(url, jwt, cluster, tenantBytesOutAlertLimit)
usage.UpdateUsages()
errStr := usage.ReportHighUsageTenant()
if errStr != "" {
Alert(errStr)
}
// monitor and report over limit tenant's usage
go func() {
alertInterval := util.TimeDuration(GetConfig().TenantUsageConfig.AlertIntervalMinutes, 120, time.Minute)
usageAlertTicker := time.NewTicker(alertInterval)
select {
case <-usageAlertTicker.C:
errStr := usage.ReportHighUsageTenant()
if errStr != "" {
Alert(errStr)
}
}
}()
// calculate tenant usage and send to prometheus
for {
select {
case <-ticker.C:
usage.UpdateUsages()
}
}
}(prefixURL, token, name)
}