bosun.org@v0.0.0-20210513094433-e25bc3e69a1f/collect/eventListener.go (about) 1 package collect 2 3 import ( 4 "compress/gzip" 5 "encoding/json" 6 "fmt" 7 "net/http" 8 "time" 9 10 "bosun.org/opentsdb" 11 "bosun.org/slog" 12 "github.com/garyburd/redigo/redis" 13 ) 14 15 func HandleCounterPut(server string, database int) http.HandlerFunc { 16 17 pool := newRedisPool(server, database) 18 return func(w http.ResponseWriter, r *http.Request) { 19 gReader, err := gzip.NewReader(r.Body) 20 if err != nil { 21 http.Error(w, err.Error(), 500) 22 return 23 } 24 decoder := json.NewDecoder(gReader) 25 dps := []*opentsdb.DataPoint{} 26 err = decoder.Decode(&dps) 27 if err != nil { 28 http.Error(w, err.Error(), 500) 29 return 30 } 31 conn := pool.Get() 32 defer conn.Close() 33 for _, dp := range dps { 34 mts := fmt.Sprintf("%s%s", dp.Metric, dp.Tags) 35 var i int64 36 switch v := dp.Value.(type) { 37 case int: 38 i = int64(v) 39 case int64: 40 i = v 41 case float64: 42 i = int64(v) 43 default: 44 http.Error(w, "Values must be integers.", 400) 45 return 46 } 47 if _, err = conn.Do("HINCRBY", RedisCountersKey, mts, i); err != nil { 48 slog.Errorf("Error incrementing counter %s by %d. %s", mts, i, err) 49 http.Error(w, err.Error(), 500) 50 return 51 } 52 } 53 } 54 } 55 56 const RedisCountersKey = "scollectorCounters" 57 58 func newRedisPool(server string, database int) *redis.Pool { 59 return &redis.Pool{ 60 MaxIdle: 10, 61 MaxActive: 10, 62 Wait: true, 63 IdleTimeout: 240 * time.Second, 64 Dial: func() (redis.Conn, error) { 65 c, err := redis.Dial("tcp", server, redis.DialDatabase(database)) 66 if err != nil { 67 return nil, err 68 } 69 return c, err 70 }, 71 } 72 }