-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
112 lines (102 loc) · 2.17 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package datadog
import (
"bytes"
"encoding/json"
"fmt"
ddjson "github.com/laslowh/datadog/json"
"io"
"net/http"
"net/url"
"os"
"time"
)
const (
API_HOST = "https://app.datadoghq.com"
METRIC_UPDATE_URL = API_HOST + "/api/v1/series"
JSON_MIME_TYPE = "application/json"
)
type Client struct {
APIKey string
ApplicationKey string
authSuffix string
closeChan chan bool
counts []*Count
}
func (c *Client) Start() {
v := make(url.Values)
v.Add("api_key", c.APIKey)
if c.ApplicationKey != "" {
v.Add("application_key", c.ApplicationKey)
}
c.authSuffix = "?" + v.Encode()
c.closeChan = make(chan bool)
go c.doUpdates()
}
func (c *Client) UpdateMetrics(s []ddjson.Series) error {
rp, wp := io.Pipe()
enc := json.NewEncoder(wp)
go func() {
enc.Encode(&s)
wp.Close()
}()
return c.updateMetrics(rp)
}
func (c *Client) updateMetrics(rd io.Reader) error {
url := METRIC_UPDATE_URL + c.authSuffix
println(url)
r, err := http.Post(url, JSON_MIME_TYPE, rd)
if err != nil {
return err
}
r.Write(os.Stderr)
if r.StatusCode != http.StatusAccepted {
return fmt.Errorf("%s: unexpected response code", r.Status)
}
return nil
}
func (c *Client) doUpdates() {
tick := time.NewTicker(100 * time.Millisecond)
println("starting update loop")
for {
select {
case _, ok := <-c.closeChan:
println("done update loop")
if !ok {
return
}
case _ = <-tick.C:
println("tick", len(c.counts))
buf := bytes.NewBuffer(make([]byte, 0, 1024))
hasOne := false
first := true
io.WriteString(buf, `{"series": [`)
for _, count := range c.counts {
println("checking count")
if count.updated {
println("updated")
hasOne = true
count.lock.Lock()
count.updated = false
count.lock.Unlock()
if !first {
io.WriteString(buf, ",")
}
enc := json.NewEncoder(buf)
count.lock.RLock()
enc.Encode(&count.series)
count.lock.RUnlock()
first = false
}
}
if hasOne {
io.WriteString(buf, "]}")
println("updating", buf.String())
err := c.updateMetrics(buf)
if err != nil {
println(err.Error())
}
}
}
}
println("done update function")
}