|
| 1 | +package redis |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "net" |
| 8 | + "sync" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/kentik/ktranslate" |
| 12 | + "github.com/kentik/ktranslate/pkg/eggs/logger" |
| 13 | + "github.com/kentik/ktranslate/pkg/formats/util" |
| 14 | + "github.com/kentik/ktranslate/pkg/kt" |
| 15 | + "github.com/kentik/ktranslate/pkg/rollup" |
| 16 | + |
| 17 | + "github.com/redis/go-redis/v9" |
| 18 | +) |
| 19 | + |
| 20 | +type RedisFormat struct { |
| 21 | + logger.ContextL |
| 22 | + lastMetadata map[string]*kt.LastMetadata |
| 23 | + mux sync.RWMutex |
| 24 | + config *ktranslate.RedisFormatConfig |
| 25 | + ctx context.Context |
| 26 | + invalids map[string]bool |
| 27 | + rdb *redis.Client |
| 28 | + keyTTL time.Duration |
| 29 | +} |
| 30 | + |
| 31 | +var ( |
| 32 | + redisAddr string |
| 33 | + redisPassword string |
| 34 | + redisDB int |
| 35 | + keyPrefix string |
| 36 | + keyTTLSec int |
| 37 | +) |
| 38 | + |
| 39 | +const ( |
| 40 | + aPrefix = ":A" |
| 41 | + aaaaPrefix = ":AAAA" |
| 42 | +) |
| 43 | + |
| 44 | +func init() { |
| 45 | + flag.StringVar(&redisAddr, "redis.addr", "localhost:6379", "Where to connect to redis.") |
| 46 | + flag.StringVar(&redisPassword, "redis.password", "", "Password for redis") |
| 47 | + flag.IntVar(&redisDB, "redis.db", 0, "Use this redis DB.") |
| 48 | + flag.StringVar(&keyPrefix, "redis.key_prefix", "", "Use this key prefix.") |
| 49 | + flag.IntVar(&keyTTLSec, "redis.ttl.sec", 60, "Expire measurements if they are not refreshed within this number of sec.") |
| 50 | +} |
| 51 | + |
| 52 | +func NewFormat(ctx context.Context, log logger.Underlying, cfg *ktranslate.RedisFormatConfig) (*RedisFormat, error) { |
| 53 | + jf := &RedisFormat{ |
| 54 | + ContextL: logger.NewContextLFromUnderlying(logger.SContext{S: "redis"}, log), |
| 55 | + lastMetadata: map[string]*kt.LastMetadata{}, |
| 56 | + invalids: map[string]bool{}, |
| 57 | + keyTTL: time.Second * time.Duration(cfg.KeyTTLSeconds), |
| 58 | + ctx: ctx, |
| 59 | + config: cfg, |
| 60 | + } |
| 61 | + |
| 62 | + jf.rdb = redis.NewClient(&redis.Options{ |
| 63 | + Addr: cfg.RedisAddr, |
| 64 | + Password: cfg.RedisPassword, |
| 65 | + DB: cfg.RedisDB, |
| 66 | + }) |
| 67 | + |
| 68 | + if err := jf.rdb.Ping(ctx).Err(); err != nil { |
| 69 | + return nil, fmt.Errorf("cannot connect to Redis addr %s err %v", cfg.RedisAddr, err) |
| 70 | + } |
| 71 | + |
| 72 | + jf.Infof("connected to Redis: addr=%s, ttl: %v", cfg.RedisAddr, jf.keyTTL) |
| 73 | + |
| 74 | + return jf, nil |
| 75 | +} |
| 76 | + |
| 77 | +func (f *RedisFormat) To(msgs []*kt.JCHF, serBuf []byte) (*kt.Output, error) { |
| 78 | + res := map[string][]RedisData{} |
| 79 | + for _, m := range msgs { |
| 80 | + for fqdn, r := range f.toRedisMetric(m) { |
| 81 | + if _, ok := res[fqdn]; !ok { |
| 82 | + res[fqdn] = r |
| 83 | + } else { |
| 84 | + res[fqdn] = append(res[fqdn], r...) |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + if len(res) == 0 { |
| 90 | + return nil, nil |
| 91 | + } |
| 92 | + |
| 93 | + pipe := f.rdb.Pipeline() |
| 94 | + |
| 95 | + for fqdn, results := range res { |
| 96 | + key := f.config.KeyPrefix + fqdn |
| 97 | + aKey := key + aPrefix |
| 98 | + aaaaKey := key + aaaaPrefix |
| 99 | + |
| 100 | + aValues := make(map[string]interface{}) |
| 101 | + aaaaValues := make(map[string]interface{}) |
| 102 | + aFields := make([]string, 0, len(results)) |
| 103 | + aaaaFields := make([]string, 0, len(results)) |
| 104 | + aSeen := make(map[string]struct{}) |
| 105 | + aaaaSeen := make(map[string]struct{}) |
| 106 | + |
| 107 | + for _, r := range results { |
| 108 | + field := r.IP.String() |
| 109 | + if r.Is6 { |
| 110 | + aaaaValues[field] = r.Latency |
| 111 | + if _, ok := aaaaSeen[field]; !ok { |
| 112 | + aaaaSeen[field] = struct{}{} |
| 113 | + aaaaFields = append(aaaaFields, field) |
| 114 | + } |
| 115 | + } else { |
| 116 | + aValues[field] = r.Latency |
| 117 | + if _, ok := aSeen[field]; !ok { |
| 118 | + aSeen[field] = struct{}{} |
| 119 | + aFields = append(aFields, field) |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + if len(aValues) > 0 { |
| 125 | + pipe.HSet(f.ctx, aKey, aValues) |
| 126 | + pipe.HExpire(f.ctx, aKey, f.keyTTL, aFields...) |
| 127 | + } |
| 128 | + if len(aaaaValues) > 0 { |
| 129 | + pipe.HSet(f.ctx, aaaaKey, aaaaValues) |
| 130 | + pipe.HExpire(f.ctx, aaaaKey, f.keyTTL, aaaaFields...) |
| 131 | + } |
| 132 | + f.Debugf("queued HSet key %s members %d", key, len(results)) |
| 133 | + } |
| 134 | + |
| 135 | + _, err := pipe.Exec(f.ctx) |
| 136 | + return nil, err |
| 137 | +} |
| 138 | + |
| 139 | +func (f *RedisFormat) From(raw *kt.Output) ([]map[string]interface{}, error) { |
| 140 | + values := make([]map[string]interface{}, 0) |
| 141 | + return values, nil |
| 142 | +} |
| 143 | + |
| 144 | +func (f *RedisFormat) Rollup(rolls []rollup.Rollup) (*kt.Output, error) { |
| 145 | + return nil, nil |
| 146 | +} |
| 147 | + |
| 148 | +func (f *RedisFormat) toRedisMetric(in *kt.JCHF) map[string][]RedisData { |
| 149 | + switch in.EventType { |
| 150 | + case kt.KENTIK_EVENT_SYNTH: |
| 151 | + return f.fromKSynth(in) |
| 152 | + case kt.KENTIK_EVENT_SNMP_METADATA: |
| 153 | + return f.fromSnmpMetadata(in) |
| 154 | + default: |
| 155 | + f.mux.Lock() |
| 156 | + defer f.mux.Unlock() |
| 157 | + if !f.invalids[in.EventType] { |
| 158 | + f.Warnf("Invalid EventType: %s", in.EventType) |
| 159 | + f.invalids[in.EventType] = true |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + return nil |
| 164 | +} |
| 165 | + |
| 166 | +func (f *RedisFormat) fromKSynth(in *kt.JCHF) map[string][]RedisData { |
| 167 | + if in.CustomInt["result_type"] <= 1 { |
| 168 | + return nil // Don't worry about timeouts and errors for now. |
| 169 | + } |
| 170 | + |
| 171 | + metrics := util.GetSynMetricNameSet(in.CustomInt["result_type"]) |
| 172 | + attr := map[string]interface{}{} |
| 173 | + f.mux.RLock() |
| 174 | + util.SetAttr(attr, in, metrics, f.lastMetadata[in.DeviceName], false) |
| 175 | + f.mux.RUnlock() |
| 176 | + ms := make([]RedisData, 0, len(metrics)) |
| 177 | + var fqdn string |
| 178 | + var ip net.IP |
| 179 | + |
| 180 | + if tn, ok := attr["test_name"].(string); ok { |
| 181 | + fqdn = tn |
| 182 | + } else { |
| 183 | + return nil |
| 184 | + } |
| 185 | + if da, ok := attr["dst_addr"].(string); ok { |
| 186 | + ip = net.ParseIP(da) |
| 187 | + if ip == nil { |
| 188 | + return nil |
| 189 | + } |
| 190 | + } else { |
| 191 | + return nil |
| 192 | + } |
| 193 | + |
| 194 | + for m, name := range metrics { |
| 195 | + switch name.Name { |
| 196 | + case "avg_rtt": |
| 197 | + ms = append(ms, RedisData{ |
| 198 | + IP: ip, |
| 199 | + Latency: float64(in.CustomInt[m]), |
| 200 | + Is6: (ip.To4() == nil), |
| 201 | + }) |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + return map[string][]RedisData{fqdn: ms} |
| 206 | +} |
| 207 | + |
| 208 | +func (f *RedisFormat) fromSnmpMetadata(in *kt.JCHF) map[string][]RedisData { |
| 209 | + if in.DeviceName == "" { // Only run if this is set. |
| 210 | + return nil |
| 211 | + } |
| 212 | + |
| 213 | + lm := util.SetMetadata(in) |
| 214 | + |
| 215 | + f.mux.Lock() |
| 216 | + defer f.mux.Unlock() |
| 217 | + if f.lastMetadata[in.DeviceName] == nil || lm.Size() >= f.lastMetadata[in.DeviceName].Size() { |
| 218 | + f.Infof("New Metadata for %s", in.DeviceName) |
| 219 | + f.lastMetadata[in.DeviceName] = lm |
| 220 | + } else { |
| 221 | + f.Infof("The metadata for %s was not updated since the attribute size is smaller. New = %d < Old = %d, Size difference = %v.", |
| 222 | + in.DeviceName, lm.Size(), f.lastMetadata[in.DeviceName].Size(), f.lastMetadata[in.DeviceName].Missing(lm)) |
| 223 | + } |
| 224 | + |
| 225 | + return nil |
| 226 | +} |
| 227 | + |
| 228 | +type RedisData struct { |
| 229 | + IP net.IP |
| 230 | + Latency float64 |
| 231 | + Is6 bool |
| 232 | +} |
0 commit comments