|
| 1 | +package data |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/elgs/gojq" |
| 8 | + "gopkg.in/zorkian/go-datadog-api.v2" |
| 9 | +) |
| 10 | + |
| 11 | +type datadogSource struct { |
| 12 | + client *datadog.Client |
| 13 | + specs []Spec |
| 14 | + c chan res |
| 15 | + done chan struct{} |
| 16 | + |
| 17 | + // state |
| 18 | + lastQueryTime int64 |
| 19 | +} |
| 20 | + |
| 21 | +// FromDatadog fetches data from Datadog service (http://datadog.com). |
| 22 | +func FromDatadog(apiKey, appKey string, specs []Spec, interval time.Duration, size int) *Points { |
| 23 | + client := datadog.NewClient(apiKey, appKey) |
| 24 | + s := &datadogSource{ |
| 25 | + client: client, |
| 26 | + specs: specs, |
| 27 | + c: make(chan res), |
| 28 | + done: make(chan struct{}), |
| 29 | + lastQueryTime: time.Now().Unix(), |
| 30 | + } |
| 31 | + go s.run(interval) |
| 32 | + return &Points{ |
| 33 | + Size: size, |
| 34 | + Source: s, |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +func (s *datadogSource) run(interval time.Duration) { |
| 39 | + t := time.NewTicker(interval) |
| 40 | + defer t.Stop() |
| 41 | + for { |
| 42 | + select { |
| 43 | + case <-t.C: |
| 44 | + s.fetch() |
| 45 | + case <-s.done: |
| 46 | + close(s.c) |
| 47 | + return |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func (s *datadogSource) fetch() { |
| 53 | + maxUpdateTimestamp := int64(s.lastQueryTime) |
| 54 | + dataPoints := make(map[string]datadog.DataPoint, len(s.specs)) |
| 55 | + var err error |
| 56 | + for _, spec := range s.specs { |
| 57 | + for _, field := range spec.Fields { |
| 58 | + query := s.formatQuery(field) |
| 59 | + series, err := s.client.QueryMetrics(s.lastQueryTime, time.Now().Unix(), query) |
| 60 | + if err != nil { |
| 61 | + s.c <- res{err: err} |
| 62 | + return |
| 63 | + } |
| 64 | + if len(series) == 0 { |
| 65 | + s.c <- res{err: fmt.Errorf("no data for %s", field.Name)} |
| 66 | + return |
| 67 | + } |
| 68 | + endTs := int64(series[0].GetEnd() / 1000) |
| 69 | + if endTs > maxUpdateTimestamp { |
| 70 | + maxUpdateTimestamp = endTs |
| 71 | + } |
| 72 | + // assume the last data point is the latest |
| 73 | + dataPoints[field.ID] = series[0].Points[len(series[0].Points)-1] |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + jq := gojq.NewQuery(dataPoints) |
| 78 | + s.c <- res{jq: jq, err: err} |
| 79 | +} |
| 80 | + |
| 81 | +func (s *datadogSource) formatQuery(field Field) string { |
| 82 | + querySuffix := "" |
| 83 | + if field.IsCounter { |
| 84 | + querySuffix = ".as_count()" |
| 85 | + } |
| 86 | + return fmt.Sprintf("%s%s", field.Name, querySuffix) |
| 87 | +} |
| 88 | + |
| 89 | +func (s *datadogSource) Get() (*gojq.JQ, error) { |
| 90 | + res := <-s.c |
| 91 | + return res.jq, res.err |
| 92 | +} |
| 93 | + |
| 94 | +func (s *datadogSource) Close() error { |
| 95 | + close(s.done) |
| 96 | + return nil |
| 97 | +} |
0 commit comments