| 1 | package exporter |
| 2 | |
| 3 | import ( |
| 4 | "encoding/csv" |
| 5 | "fmt" |
| 6 | "sort" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/gomodule/redigo/redis" |
| 11 | "github.com/prometheus/client_golang/prometheus" |
| 12 | log "github.com/sirupsen/logrus" |
| 13 | ) |
| 14 | |
| 15 | type keyGroupMetrics struct { |
| 16 | keyGroup string |
| 17 | count int64 |
| 18 | memoryUsage int64 |
| 19 | } |
| 20 | |
| 21 | type overflowedKeyGroupMetrics struct { |
| 22 | topMemoryUsageKeyGroups []*keyGroupMetrics |
| 23 | overflowKeyGroupAggregate keyGroupMetrics |
| 24 | keyGroupsCount int64 |
| 25 | } |
| 26 | |
| 27 | type keyGroupsScrapeResult struct { |
| 28 | duration time.Duration |
| 29 | metrics []map[string]*keyGroupMetrics |
| 30 | overflowedMetrics []*overflowedKeyGroupMetrics |
| 31 | } |
| 32 | |
| 33 | func (e *Exporter) extractKeyGroupMetrics(ch chan<- prometheus.Metric, c redis.Conn, dbCount int) { |
| 34 | allDbKeyGroupMetrics := e.gatherKeyGroupsMetricsForAllDatabases(c, dbCount) |
| 35 | if allDbKeyGroupMetrics == nil { |
| 36 | return |
| 37 | } |
| 38 | for db, dbKeyGroupMetrics := range allDbKeyGroupMetrics.metrics { |
| 39 | dbLabel := fmt.Sprintf("db%d", db) |
| 40 | registerKeyGroupMetrics := func(metrics *keyGroupMetrics) { |
| 41 | e.registerConstMetricGauge( |
| 42 | ch, |
| 43 | "key_group_count", |
| 44 | float64(metrics.count), |
| 45 | dbLabel, |
| 46 | metrics.keyGroup, |
| 47 | ) |
| 48 | e.registerConstMetricGauge( |
| 49 | ch, |
| 50 | "key_group_memory_usage_bytes", |
| 51 | float64(metrics.memoryUsage), |
| 52 | dbLabel, |
| 53 | metrics.keyGroup, |
| 54 | ) |
| 55 | } |
| 56 | if allDbKeyGroupMetrics.overflowedMetrics[db] != nil { |
| 57 | overflowedMetrics := allDbKeyGroupMetrics.overflowedMetrics[db] |
| 58 | for _, metrics := range overflowedMetrics.topMemoryUsageKeyGroups { |
| 59 | registerKeyGroupMetrics(metrics) |
| 60 | } |
| 61 | registerKeyGroupMetrics(&overflowedMetrics.overflowKeyGroupAggregate) |
| 62 | e.registerConstMetricGauge(ch, "number_of_distinct_key_groups", float64(overflowedMetrics.keyGroupsCount), dbLabel) |
| 63 | } else if dbKeyGroupMetrics != nil { |
| 64 | for _, metrics := range dbKeyGroupMetrics { |
| 65 | registerKeyGroupMetrics(metrics) |
| 66 | } |
| 67 | e.registerConstMetricGauge(ch, "number_of_distinct_key_groups", float64(len(dbKeyGroupMetrics)), dbLabel) |
| 68 | } |
| 69 | } |
| 70 | e.registerConstMetricGauge(ch, "last_key_groups_scrape_duration_milliseconds", float64(allDbKeyGroupMetrics.duration.Milliseconds())) |
| 71 | } |
| 72 | |
| 73 | func (e *Exporter) gatherKeyGroupsMetricsForAllDatabases(c redis.Conn, dbCount int) *keyGroupsScrapeResult { |
| 74 | start := time.Now() |
| 75 | allMetrics := &keyGroupsScrapeResult{ |
| 76 | metrics: make([]map[string]*keyGroupMetrics, dbCount), |
| 77 | overflowedMetrics: make([]*overflowedKeyGroupMetrics, dbCount), |
| 78 | } |
| 79 | defer func() { |
| 80 | allMetrics.duration = time.Since(start) |
| 81 | }() |
| 82 | if strings.TrimSpace(e.options.CheckKeyGroups) == "" { |
| 83 | return allMetrics |
| 84 | } |
| 85 | keyGroups, err := csv.NewReader( |
| 86 | strings.NewReader(e.options.CheckKeyGroups), |
| 87 | ).Read() |
| 88 | if err != nil { |
| 89 | log.Errorf("Failed to parse key groups as csv: %s", err) |
| 90 | return allMetrics |
| 91 | } |
| 92 | for i, v := range keyGroups { |
| 93 | keyGroups[i] = strings.TrimSpace(v) |
| 94 | } |
| 95 | |
| 96 | keyGroupsNoEmptyStrings := make([]string, 0) |
| 97 | for _, v := range keyGroups { |
| 98 | if len(v) > 0 { |
| 99 | keyGroupsNoEmptyStrings = append(keyGroupsNoEmptyStrings, v) |
| 100 | } |
| 101 | } |
| 102 | if len(keyGroupsNoEmptyStrings) == 0 { |
| 103 | return allMetrics |
| 104 | } |
| 105 | for db := range dbCount { |
| 106 | if _, err := doRedisCmd(c, "SELECT", db); err != nil { |
| 107 | log.Errorf("Couldn't select database %d when getting key info.", db) |
| 108 | continue |
| 109 | } |
| 110 | allGroups, err := gatherKeyGroupMetrics(c, e.options.CheckKeysBatchSize, keyGroupsNoEmptyStrings) |
| 111 | if err != nil { |
| 112 | log.Error(err) |
| 113 | continue |
| 114 | } |
| 115 | allMetrics.metrics[db] = allGroups |
| 116 | if int64(len(allGroups)) > e.options.MaxDistinctKeyGroups { |
| 117 | metricsSlice := make([]*keyGroupMetrics, 0, len(allGroups)) |
| 118 | for _, v := range allGroups { |
| 119 | metricsSlice = append(metricsSlice, v) |
| 120 | } |
| 121 | sort.Slice(metricsSlice, func(i, j int) bool { |
| 122 | if metricsSlice[i].memoryUsage == metricsSlice[j].memoryUsage { |
| 123 | if metricsSlice[i].count == metricsSlice[j].count { |
| 124 | return metricsSlice[i].keyGroup < metricsSlice[j].keyGroup |
| 125 | } |
| 126 | return metricsSlice[i].count < metricsSlice[j].count |
| 127 | } |
| 128 | return metricsSlice[i].memoryUsage > metricsSlice[j].memoryUsage |
| 129 | }) |
| 130 | var overflowedCount, overflowedMemoryUsage int64 |
| 131 | for _, v := range metricsSlice[e.options.MaxDistinctKeyGroups:] { |
| 132 | overflowedCount += v.count |
| 133 | overflowedMemoryUsage += v.memoryUsage |
| 134 | } |
| 135 | allMetrics.overflowedMetrics[db] = &overflowedKeyGroupMetrics{ |
| 136 | topMemoryUsageKeyGroups: metricsSlice[:e.options.MaxDistinctKeyGroups], |
| 137 | overflowKeyGroupAggregate: keyGroupMetrics{ |
| 138 | keyGroup: "overflow", |
| 139 | count: overflowedCount, |
| 140 | memoryUsage: overflowedMemoryUsage, |
| 141 | }, |
| 142 | keyGroupsCount: int64(len(allGroups)), |
| 143 | } |
| 144 | } |
| 145 | } |
| 146 | return allMetrics |
| 147 | } |
| 148 | |
| 149 | func gatherKeyGroupMetrics(c redis.Conn, batchSize int64, keyGroups []string) (map[string]*keyGroupMetrics, error) { |
| 150 | allGroups := make(map[string]*keyGroupMetrics) |
| 151 | keysAndArgs := []any{0, batchSize} |
| 152 | for _, keyGroup := range keyGroups { |
| 153 | keysAndArgs = append(keysAndArgs, keyGroup) |
| 154 | } |
| 155 | |
| 156 | script := redis.NewScript( |
| 157 | 0, |
| 158 | ` |
| 159 | local result = {} |
| 160 | local batch = redis.call("SCAN", ARGV[1], "COUNT", ARGV[2]) |
| 161 | local groups = {} |
| 162 | local usage = 0 |
| 163 | local group_index = 0 |
| 164 | local group = nil |
| 165 | local value = {} |
| 166 | local key_match_result = {} |
| 167 | local status = false |
| 168 | local err = nil |
| 169 | for i=3,#ARGV do |
| 170 | status, err = pcall(string.find, " ", ARGV[i]) |
| 171 | if not status then |
| 172 | error(err .. ARGV[i]) |
| 173 | end |
| 174 | end |
| 175 | for i,key in ipairs(batch[2]) do |
| 176 | local reply = redis.pcall("MEMORY", "USAGE", key) |
| 177 | if type(reply) == "number" then |
| 178 | usage = reply; |
| 179 | end |
| 180 | group = nil |
| 181 | for i=3,#ARGV do |
| 182 | key_match_result = {string.find(key, ARGV[i])} |
| 183 | if key_match_result[1] ~= nil then |
| 184 | group = table.concat({unpack(key_match_result, 3, #key_match_result)}, "") |
| 185 | break |
| 186 | end |
| 187 | end |
| 188 | if group == nil then |
| 189 | group = "unclassified" |
| 190 | end |
| 191 | value = groups[group] |
| 192 | if value == nil then |
| 193 | groups[group] = {1, usage} |
| 194 | else |
| 195 | groups[group] = {value[1] + 1, value[2] + usage} |
| 196 | end |
| 197 | end |
| 198 | for group,value in pairs(groups) do |
| 199 | result[#result+1] = {group, value[1], value[2]} |
| 200 | end |
| 201 | return {batch[1], result}`, |
| 202 | ) |
| 203 | |
| 204 | for { |
| 205 | arr, err := redis.Values(script.Do(c, keysAndArgs...)) |
| 206 | if err != nil { |
| 207 | return nil, err |
| 208 | } |
| 209 | |
| 210 | if len(arr) != 2 { |
| 211 | return nil, fmt.Errorf("invalid response from key group metrics lua script for groups: %s", strings.Join(keyGroups, ", ")) |
| 212 | } |
| 213 | |
| 214 | groups, _ := redis.Values(arr[1], nil) |
| 215 | |
| 216 | for _, group := range groups { |
| 217 | metricsArr, _ := redis.Values(group, nil) |
| 218 | name, _ := redis.String(metricsArr[0], nil) |
| 219 | count, _ := redis.Int64(metricsArr[1], nil) |
| 220 | memoryUsage, _ := redis.Int64(metricsArr[2], nil) |
| 221 | |
| 222 | if currentMetrics, ok := allGroups[name]; ok { |
| 223 | currentMetrics.count += count |
| 224 | currentMetrics.memoryUsage += memoryUsage |
| 225 | } else { |
| 226 | allGroups[name] = &keyGroupMetrics{ |
| 227 | keyGroup: name, |
| 228 | count: count, |
| 229 | memoryUsage: memoryUsage, |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | } |
| 234 | if keysAndArgs[0], _ = redis.Int(arr[0], nil); keysAndArgs[0].(int) == 0 { |
| 235 | break |
| 236 | } |
| 237 | } |
| 238 | return allGroups, nil |
| 239 | } |