Debian Codegraph @

exporter/info.go

raw symbols SCIP
1 package exporter
2
3 import (
4 "errors"
5 "fmt"
6 "regexp"
7 "strconv"
8 "strings"
9 "time"
10
11 "github.com/prometheus/client_golang/prometheus"
12 log "github.com/sirupsen/logrus"
13 )
14
15 // precompiled regexps
16
17 // keydb multimaster
18 /*
19 master_host:kdb0.server.local
20 master_port:6377
21 master_1_host:kdb1.server.local
22 master_1_port:6377
23 */
24 var reMasterHost = regexp.MustCompile(`^master(_[0-9]+)?_host`)
25 var reMasterPort = regexp.MustCompile(`^master(_[0-9]+)?_port`)
26 var reMasterLinkStatus = regexp.MustCompile(`^master(_[0-9]+)?_link_status`)
27
28 // info fieldKey:fieldValue -> metric redis_fieldKey{master_host, master_port} fieldValue
29 var reMasterDirect = regexp.MustCompile(`^(master(_[0-9]+)?_(last_io_seconds_ago|sync_in_progress)|slave_repl_offset)`)
30
31 // numbered slaves
32 /*
33 slave0:ip=10.254.11.1,port=6379,state=online,offset=1751844676,lag=0
34 slave1:ip=10.254.11.2,port=6379,state=online,offset=1751844222,lag=0
35 */
36
37 var reSlave = regexp.MustCompile(`^slave\d+`)
38
39 const (
40 InstanceRoleSlave = "slave"
41 )
42
43 func extractVal(s string) (val float64, err error) {
44 split := strings.Split(s, "=")
45 if len(split) != 2 {
46 return 0, fmt.Errorf("nope")
47 }
48 val, err = strconv.ParseFloat(split[1], 64)
49 if err != nil {
50 return 0, fmt.Errorf("nope")
51 }
52 return
53 }
54
55 func extractPercentileVal(s string) (percentile float64, val float64, err error) {
56 split := strings.Split(s, "=")
57 if len(split) != 2 {
58 return
59 }
60 if len(split[0]) == 0 {
61 err = fmt.Errorf("empty percentile key")
62 return
63 }
64 percentile, err = strconv.ParseFloat(split[0][1:], 64)
65 if err != nil {
66 return
67 }
68 val, err = strconv.ParseFloat(split[1], 64)
69 return
70 }
71
72 // returns the role of the instance we're scraping (master or slave)
73 func (e *Exporter) extractInfoMetrics(ch chan<- prometheus.Metric, info string, dbCount int) string {
74 keyValues := map[string]string{}
75 handledDBs := map[string]bool{}
76 cmdCount := map[string]uint64{}
77 cmdSum := map[string]float64{}
78 cmdLatencyMap := map[string]map[float64]float64{}
79
80 fieldClass := ""
81 lines := strings.Split(info, "\n")
82 masterHost := ""
83 masterPort := ""
84 for _, line := range lines {
85 line = strings.TrimSpace(line)
86 log.Debugf("info: %s", line)
87 if len(line) > 0 && strings.HasPrefix(line, "# ") {
88 fieldClass = line[2:]
89 log.Debugf("set fieldClass: %s", fieldClass)
90 continue
91 }
92
93 if (len(line) < 2) || (!strings.Contains(line, ":")) {
94 continue
95 }
96
97 split := strings.SplitN(line, ":", 2)
98 fieldKey := split[0]
99 fieldValue := split[1]
100
101 keyValues[fieldKey] = fieldValue
102
103 if reMasterHost.MatchString(fieldKey) {
104 masterHost = fieldValue
105 }
106
107 if reMasterPort.MatchString(fieldKey) {
108 masterPort = fieldValue
109 }
110
111 switch fieldClass {
112
113 case "Replication":
114 if ok := e.handleMetricsReplication(ch, masterHost, masterPort, fieldKey, fieldValue); ok {
115 continue
116 }
117
118 case "Server":
119 e.handleMetricsServer(ch, fieldKey, fieldValue)
120
121 case "Commandstats":
122 cmd, calls, usecsTotal := e.handleMetricsCommandStats(ch, fieldKey, fieldValue)
123 cmdCount[cmd] = uint64(calls)
124 cmdSum[cmd] = usecsTotal
125 continue
126
127 case "Latencystats":
128 e.handleMetricsLatencyStats(fieldKey, fieldValue, cmdLatencyMap)
129 continue
130
131 case "Errorstats":
132 e.handleMetricsErrorStats(ch, fieldKey, fieldValue)
133 continue
134
135 case "Keyspace":
136 if keysTotal, keysEx, avgTTL, keysCached, ok := parseDBKeyspaceString(fieldKey, fieldValue); ok {
137 dbName := fieldKey
138
139 e.registerConstMetricGauge(ch, "db_keys", keysTotal, dbName)
140 e.registerConstMetricGauge(ch, "db_keys_expiring", keysEx, dbName)
141 if keysCached > -1 {
142 e.registerConstMetricGauge(ch, "db_keys_cached", keysCached, dbName)
143 }
144 if avgTTL > -1 {
145 e.registerConstMetricGauge(ch, "db_avg_ttl_seconds", avgTTL, dbName)
146 }
147 handledDBs[dbName] = true
148 continue
149 }
150
151 case "Sentinel":
152 e.handleMetricsSentinel(ch, fieldKey, fieldValue)
153 }
154
155 if !e.includeMetric(fieldKey) {
156 continue
157 }
158
159 e.parseAndRegisterConstMetric(ch, fieldKey, fieldValue)
160 }
161
162 // To be able to generate the latency summaries we need the count and sum that we get
163 // from #Commandstats processing and the percentile info that we get from the #Latencystats processing
164 e.generateCommandLatencySummaries(ch, cmdLatencyMap, cmdCount, cmdSum)
165
166 if e.options.InclMetricsForEmptyDatabases {
167 for dbIndex := range dbCount {
168 dbName := "db" + strconv.Itoa(dbIndex)
169 if _, exists := handledDBs[dbName]; !exists {
170 e.registerConstMetricGauge(ch, "db_keys", 0, dbName)
171 e.registerConstMetricGauge(ch, "db_keys_expiring", 0, dbName)
172 }
173 }
174 }
175
176 instanceRole := keyValues["role"]
177
178 lbls := []string{"role", "redis_version", "redis_build_id", "redis_mode", "os", "maxmemory_policy", "tcp_port", "run_id", "process_id", "master_replid"}
179 lblVals := []string{
180 instanceRole,
181 keyValues["redis_version"],
182 keyValues["redis_build_id"],
183 keyValues["redis_mode"],
184 keyValues["os"],
185 keyValues["maxmemory_policy"],
186 keyValues["tcp_port"],
187 keyValues["run_id"],
188 keyValues["process_id"],
189 keyValues["master_replid"],
190 }
191 if valkeyVersion, ok := keyValues["valkey_version"]; ok {
192 lbls = append(lbls, "valkey_version")
193 lblVals = append(lblVals, valkeyVersion)
194 }
195 if valkeyReleaseStage, ok := keyValues["valkey_release_stage"]; ok {
196 lbls = append(lbls, "valkey_release_stage")
197 lblVals = append(lblVals, valkeyReleaseStage)
198 }
199
200 e.createMetricDescription("instance_info", lbls)
201 e.registerConstMetricGauge(ch, "instance_info", 1, lblVals...)
202
203 if instanceRole == InstanceRoleSlave {
204 e.registerConstMetricGauge(ch, "slave_info", 1,
205 keyValues["master_host"],
206 keyValues["master_port"],
207 keyValues["slave_read_only"])
208 }
209
210 return instanceRole
211 }
212
213 func (e *Exporter) generateCommandLatencySummaries(ch chan<- prometheus.Metric, cmdLatencyMap map[string]map[float64]float64, cmdCount map[string]uint64, cmdSum map[string]float64) {
214 for cmd, latencyMap := range cmdLatencyMap {
215 count, okCount := cmdCount[cmd]
216 sum, okSum := cmdSum[cmd]
217 if okCount && okSum {
218 e.createMetricDescription("latency_percentiles_usec", []string{"cmd"})
219 e.registerConstSummary(ch, "latency_percentiles_usec", count, sum, latencyMap, cmd)
220 }
221 }
222 }
223
224 func (e *Exporter) extractClusterInfoMetrics(ch chan<- prometheus.Metric, info string) {
225 lines := strings.SplitSeq(info, "\r\n")
226
227 for line := range lines {
228 log.Debugf("info: %s", line)
229
230 split := strings.Split(line, ":")
231 if len(split) != 2 {
232 continue
233 }
234 fieldKey := split[0]
235 fieldValue := split[1]
236
237 if !e.includeMetric(fieldKey) {
238 continue
239 }
240 e.parseAndRegisterConstMetric(ch, fieldKey, fieldValue)
241 }
242 }
243
244 /*
245 valid example: db0:keys=1,expires=0,avg_ttl=0,cached_keys=0
246 */
247 func parseDBKeyspaceString(inputKey string, inputVal string) (keysTotal float64, keysExpiringTotal float64, avgTTL float64, keysCachedTotal float64, ok bool) {
248 log.Debugf("parseDBKeyspaceString inputKey: [%s] inputVal: [%s]", inputKey, inputVal)
249
250 if !strings.HasPrefix(inputKey, "db") {
251 log.Debugf("parseDBKeyspaceString inputKey not starting with 'db': [%s]", inputKey)
252 return
253 }
254
255 split := strings.Split(inputVal, ",")
256 if len(split) < 2 {
257 log.Debugf("parseDBKeyspaceString strings.Split(inputVal) invalid: %#v", split)
258 return
259 }
260
261 var err error
262 if keysTotal, err = extractVal(split[0]); err != nil {
263 log.Debugf("parseDBKeyspaceString extractVal(split[0]) invalid, err: %s", err)
264 return
265 }
266 if keysExpiringTotal, err = extractVal(split[1]); err != nil {
267 log.Debugf("parseDBKeyspaceString extractVal(split[1]) invalid, err: %s", err)
268 return
269 }
270
271 avgTTL = -1
272 if len(split) > 2 {
273 if avgTTL, err = extractVal(split[2]); err != nil {
274 log.Debugf("parseDBKeyspaceString extractVal(split[2]) invalid, err: %s", err)
275 return
276 }
277 avgTTL /= 1000
278 }
279
280 keysCachedTotal = -1
281 if len(split) > 3 {
282 if keysCachedTotal, err = extractVal(split[3]); err != nil {
283 log.Debugf("parseDBKeyspaceString extractVal(split[3]) invalid, err: %s", err)
284 return
285 }
286 }
287
288 ok = true
289 return
290 }
291
292 /*
293 slave0:ip=10.254.11.1,port=6379,state=online,offset=1751844676,lag=0
294 slave1:ip=10.254.11.2,port=6379,state=online,offset=1751844222,lag=0
295 */
296 func parseConnectedSlaveString(slaveName string, keyValues string) (offset float64, ip string, port string, state string, lag float64, ok bool) {
297 ok = false
298 if !reSlave.MatchString(slaveName) {
299 return
300 }
301 connectedkeyValues := make(map[string]string)
302 for kvPart := range strings.SplitSeq(keyValues, ",") {
303 x := strings.Split(kvPart, "=")
304 if len(x) != 2 {
305 log.Debugf("Invalid format for connected slave string, got: %s", kvPart)
306 return
307 }
308 connectedkeyValues[x[0]] = x[1]
309 }
310 offset, err := strconv.ParseFloat(connectedkeyValues["offset"], 64)
311 if err != nil {
312 log.Debugf("Can not parse connected slave offset, got: %s", connectedkeyValues["offset"])
313 return
314 }
315
316 if lagStr, exists := connectedkeyValues["lag"]; !exists {
317 // Prior to Redis 3.0, "lag" property does not exist
318 lag = -1
319 } else {
320 lag, err = strconv.ParseFloat(lagStr, 64)
321 if err != nil {
322 log.Debugf("Can not parse connected slave lag, got: %s", lagStr)
323 return
324 }
325 }
326
327 ok = true
328 ip = connectedkeyValues["ip"]
329 port = connectedkeyValues["port"]
330 state = connectedkeyValues["state"]
331
332 return
333 }
334
335 func (e *Exporter) handleMetricsReplication(ch chan<- prometheus.Metric, masterHost string, masterPort string, fieldKey string, fieldValue string) bool {
336 // only slaves have this field
337 if reMasterLinkStatus.MatchString(fieldKey) {
338 if fieldValue == "up" {
339 e.registerConstMetricGauge(ch, "master_link_up", 1, masterHost, masterPort)
340 } else {
341 e.registerConstMetricGauge(ch, "master_link_up", 0, masterHost, masterPort)
342 }
343 return true
344 }
345
346 if reMasterDirect.MatchString(fieldKey) {
347 if strings.HasSuffix(fieldKey, "last_io_seconds_ago") {
348 fieldKey = "master_last_io_seconds_ago"
349 } else if strings.HasSuffix(fieldKey, "sync_in_progress") {
350 fieldKey = "master_sync_in_progress"
351 }
352 val, _ := strconv.Atoi(fieldValue)
353 e.registerConstMetricGauge(ch, fieldKey, float64(val), masterHost, masterPort)
354 return true
355 }
356
357 // not a slave, try extracting master metrics
358 if slaveOffset, slaveIP, slavePort, slaveState, slaveLag, ok := parseConnectedSlaveString(fieldKey, fieldValue); ok {
359 e.registerConstMetricGauge(ch,
360 "connected_slave_offset_bytes",
361 slaveOffset,
362 slaveIP, slavePort, slaveState,
363 )
364
365 if slaveLag > -1 {
366 e.registerConstMetricGauge(ch,
367 "connected_slave_lag_seconds",
368 slaveLag,
369 slaveIP, slavePort, slaveState,
370 )
371 }
372 return true
373 }
374
375 return false
376 }
377
378 func (e *Exporter) handleMetricsServer(ch chan<- prometheus.Metric, fieldKey string, fieldValue string) {
379 if fieldKey == "uptime_in_seconds" {
380 if uptime, err := strconv.ParseFloat(fieldValue, 64); err == nil {
381 e.registerConstMetricGauge(ch, "start_time_seconds", float64(time.Now().Unix())-uptime)
382 }
383 }
384
385 if fieldKey == "configured_hz" {
386 if hz, err := strconv.ParseInt(fieldValue, 10, 64); err == nil {
387 e.registerConstMetricGauge(ch, "configured_hz", float64(hz))
388 }
389 }
390
391 if fieldKey == "hz" {
392 if hz, err := strconv.ParseInt(fieldValue, 10, 64); err == nil {
393 e.registerConstMetricGauge(ch, "hz", float64(hz))
394 }
395 }
396 }
397
398 func parseMetricsCommandStats(fieldKey string, fieldValue string) (cmd string, calls float64, rejectedCalls float64, failedCalls float64, usecTotal float64, extendedStats bool, errorOut error) {
399 /*
400 There are 2 formats. (One before Redis 6.2 and one after it)
401 Format before v6.2:
402 cmdstat_get:calls=21,usec=175,usec_per_call=8.33
403 cmdstat_set:calls=61,usec=3139,usec_per_call=51.46
404 cmdstat_setex:calls=75,usec=1260,usec_per_call=16.80
405 cmdstat_georadius_ro:calls=75,usec=1260,usec_per_call=16.80
406 Format from v6.2 forward:
407 cmdstat_get:calls=21,usec=175,usec_per_call=8.33,rejected_calls=0,failed_calls=0
408 cmdstat_set:calls=61,usec=3139,usec_per_call=51.46,rejected_calls=0,failed_calls=0
409 cmdstat_setex:calls=75,usec=1260,usec_per_call=16.80,rejected_calls=0,failed_calls=0
410 cmdstat_georadius_ro:calls=75,usec=1260,usec_per_call=16.80,rejected_calls=0,failed_calls=0
411
412 broken up like this:
413 fieldKey = cmdstat_get
414 fieldValue= calls=21,usec=175,usec_per_call=8.33
415 */
416
417 const cmdPrefix = "cmdstat_"
418 extendedStats = false
419
420 if !strings.HasPrefix(fieldKey, cmdPrefix) {
421 errorOut = errors.New("invalid fieldKey")
422 return
423 }
424 cmd = strings.TrimPrefix(fieldKey, cmdPrefix)
425
426 splitValue := strings.Split(fieldValue, ",")
427 splitLen := len(splitValue)
428 if splitLen < 3 {
429 errorOut = errors.New("invalid fieldValue")
430 return
431 }
432
433 // internal error variable
434 var err error
435 calls, err = extractVal(splitValue[0])
436 if err != nil {
437 errorOut = errors.New("invalid splitValue[0]")
438 return
439 }
440
441 usecTotal, err = extractVal(splitValue[1])
442 if err != nil {
443 errorOut = errors.New("invalid splitValue[1]")
444 return
445 }
446
447 // pre 6.2 did not include rejected/failed calls stats so if we have less than 5 tokens we're done here
448 if splitLen < 5 {
449 return
450 }
451
452 rejectedCalls, err = extractVal(splitValue[3])
453 if err != nil {
454 errorOut = errors.New("invalid rejected_calls while parsing splitValue[3]")
455 return
456 }
457
458 failedCalls, err = extractVal(splitValue[4])
459 if err != nil {
460 errorOut = errors.New("invalid failed_calls while parsing splitValue[4]")
461 return
462 }
463 extendedStats = true
464 return
465 }
466
467 func parseMetricsLatencyStats(fieldKey string, fieldValue string) (cmd string, percentileMap map[float64]float64, errorOut error) {
468 /*
469 # Latencystats
470 latency_percentiles_usec_rpop:p50=0.001,p99=1.003,p99.9=4.015
471 latency_percentiles_usec_zadd:p50=0.001,p99=1.003,p99.9=4.015
472 latency_percentiles_usec_hset:p50=0.001,p99=1.003,p99.9=3.007
473 latency_percentiles_usec_set:p50=0.001,p99=1.003,p99.9=4.015
474 latency_percentiles_usec_lpop:p50=0.001,p99=1.003,p99.9=4.015
475 latency_percentiles_usec_lpush:p50=0.001,p99=1.003,p99.9=4.015
476 latency_percentiles_usec_lrange:p50=17.023,p99=21.119,p99.9=27.007
477 latency_percentiles_usec_get:p50=0.001,p99=1.003,p99.9=3.007
478 latency_percentiles_usec_mset:p50=1.003,p99=1.003,p99.9=1.003
479 latency_percentiles_usec_spop:p50=0.001,p99=1.003,p99.9=1.003
480 latency_percentiles_usec_incr:p50=0.001,p99=1.003,p99.9=3.007
481 latency_percentiles_usec_rpush:p50=0.001,p99=1.003,p99.9=4.015
482 latency_percentiles_usec_zpopmin:p50=0.001,p99=1.003,p99.9=3.007
483 latency_percentiles_usec_config|resetstat:p50=280.575,p99=280.575,p99.9=280.575
484 latency_percentiles_usec_config|get:p50=8.031,p99=27.007,p99.9=27.007
485 latency_percentiles_usec_ping:p50=0.001,p99=1.003,p99.9=1.003
486 latency_percentiles_usec_sadd:p50=0.001,p99=1.003,p99.9=3.007
487
488 broken up like this:
489 fieldKey = latency_percentiles_usec_ping
490 fieldValue= p50=0.001,p99=1.003,p99.9=3.007
491 */
492
493 const cmdPrefix = "latency_percentiles_usec_"
494 percentileMap = map[float64]float64{}
495
496 if !strings.HasPrefix(fieldKey, cmdPrefix) {
497 errorOut = errors.New("invalid fieldKey")
498 return
499 }
500 cmd = strings.TrimPrefix(fieldKey, cmdPrefix)
501 splitValue := strings.Split(fieldValue, ",")
502 splitLen := len(splitValue)
503 if splitLen < 1 {
504 errorOut = errors.New("invalid fieldValue")
505 return
506 }
507 for pos, kv := range splitValue {
508 percentile, value, err := extractPercentileVal(kv)
509 if err != nil {
510 errorOut = fmt.Errorf("invalid splitValue[%d]", pos)
511 return
512 }
513 percentileMap[percentile] = value
514 }
515 return
516 }
517
518 func parseMetricsErrorStats(fieldKey string, fieldValue string) (errorType string, count float64, errorOut error) {
519 /*
520 Format:
521 errorstat_ERR:count=4
522 errorstat_NOAUTH:count=3
523
524 broken up like this:
525 fieldKey = errorstat_ERR
526 fieldValue= count=3
527 */
528
529 const prefix = "errorstat_"
530
531 if !strings.HasPrefix(fieldKey, prefix) {
532 errorOut = errors.New("invalid fieldKey. errorstat_ prefix not present")
533 return
534 }
535 errorType = strings.TrimPrefix(fieldKey, prefix)
536 count, err := extractVal(fieldValue)
537 if err != nil {
538 errorOut = errors.New("invalid error type on splitValue[0]")
539 return
540 }
541 return
542 }
543
544 func (e *Exporter) handleMetricsCommandStats(ch chan<- prometheus.Metric, fieldKey string, fieldValue string) (cmd string, calls float64, usecTotal float64) {
545 cmd, calls, rejectedCalls, failedCalls, usecTotal, extendedStats, err := parseMetricsCommandStats(fieldKey, fieldValue)
546 if err != nil {
547 log.Debugf("parseMetricsCommandStats( %s , %s ) err: %s", fieldKey, fieldValue, err)
548 return
549 }
550 e.createMetricDescription("commands_total", []string{"cmd"})
551 e.createMetricDescription("commands_duration_seconds_total", []string{"cmd"})
552 e.registerConstMetric(ch, "commands_total", calls, prometheus.CounterValue, cmd)
553 e.registerConstMetric(ch, "commands_duration_seconds_total", usecTotal/1e6, prometheus.CounterValue, cmd)
554 if extendedStats {
555 e.createMetricDescription("commands_rejected_calls_total", []string{"cmd"})
556 e.createMetricDescription("commands_failed_calls_total", []string{"cmd"})
557 e.registerConstMetric(ch, "commands_rejected_calls_total", rejectedCalls, prometheus.CounterValue, cmd)
558 e.registerConstMetric(ch, "commands_failed_calls_total", failedCalls, prometheus.CounterValue, cmd)
559 }
560 return
561 }
562
563 func (e *Exporter) handleMetricsLatencyStats(fieldKey string, fieldValue string, cmdLatencyMap map[string]map[float64]float64) {
564 cmd, latencyMap, err := parseMetricsLatencyStats(fieldKey, fieldValue)
565 if err == nil {
566 cmdLatencyMap[cmd] = latencyMap
567 }
568 }
569
570 func (e *Exporter) handleMetricsErrorStats(ch chan<- prometheus.Metric, fieldKey string, fieldValue string) {
571 if errorPrefix, count, err := parseMetricsErrorStats(fieldKey, fieldValue); err == nil {
572 e.registerConstMetric(ch, "errors_total", count, prometheus.CounterValue, errorPrefix)
573 }
574 }