-
Notifications
You must be signed in to change notification settings - Fork 9
/
librato_output.go
245 lines (212 loc) · 6.19 KB
/
librato_output.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package shh
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/heroku/slog"
)
type LibratoMetric struct {
Name string `json:"name"`
Value interface{} `json:"value"`
When int64 `json:"measure_time"`
Source string `json:"source,omitempty"`
Attributes LibratoMetricAttrs `json:"attributes,omitempty"`
}
type LibratoMetricAttrs struct {
UnitName string `json:"display_units_long,omitempty"`
UnitAbbr string `json:"display_units_short,omitempty"`
}
type LibratoPostBody struct {
Gauges []LibratoMetric `json:"gauges,omitempty"`
Counters []LibratoMetric `json:"counters,omitempty"`
}
const (
LibratoBacklog = 8 // No more than N pending batches in-flight
LibratoMaxAttempts = 4 // Max attempts before dropping batch
LibratoStartingBackoff = 500 * time.Millisecond
)
type Librato struct {
Timeout time.Duration
BatchSize int
User string
Token string
Url string
measurements <-chan Measurement
batches chan []Measurement
prefix string
source string
client *http.Client
userAgent string
interval time.Duration
round bool
meta bool
}
func NewLibratoOutputter(measurements <-chan Measurement, config Config) *Librato {
var user string
var token string
if config.LibratoUrl.User != nil {
user = config.LibratoUrl.User.Username()
token, _ = config.LibratoUrl.User.Password()
config.LibratoUrl.User = nil
}
// override settings in URL if they were present
if config.LibratoUser != "" {
user = config.LibratoUser
}
if config.LibratoToken != "" {
token = config.LibratoToken
}
return &Librato{
measurements: measurements,
prefix: config.Prefix,
source: config.Source,
batches: make(chan []Measurement, LibratoBacklog),
Timeout: config.LibratoBatchTimeout,
BatchSize: config.LibratoBatchSize,
User: user,
Token: token,
Url: config.LibratoUrl.String(),
interval: config.Interval,
round: config.LibratoRound,
userAgent: config.UserAgent,
client: &http.Client{Timeout: config.NetworkTimeout},
meta: config.Meta,
}
}
func (out *Librato) Start() {
go out.deliver()
go out.batch()
}
// Returns a batch that is ready to be submitted to Librato, either because it timed out
// after receiving it's first measurement or it is full.
func (out *Librato) readyBatch() []Measurement {
batch := make([]Measurement, 0, out.BatchSize)
timer := new(time.Timer) // "empty" timer so we don't timeout before we have any measurements
for {
select {
case measurement := <-out.measurements:
batch = append(batch, measurement)
if len(batch) == 1 { // We got a measurement, so we want to start the timer.
timer = time.NewTimer(out.Timeout)
defer timer.Stop()
}
if len(batch) == cap(batch) {
return batch
}
case <-timer.C:
return batch
}
}
}
// Continuously batch measurments into the batch channel
func (out *Librato) batch() {
ctx := slog.Context{"fn": "batch", "outputter": "librato"}
for {
batch := out.readyBatch()
select {
case out.batches <- batch:
default:
LogError(ctx, nil, "Batches backlogged, dropping")
}
}
}
func (out *Librato) appendLibratoMetric(counters, gauges []LibratoMetric, mm Measurement) ([]LibratoMetric, []LibratoMetric) {
var t int64
attrs := LibratoMetricAttrs{UnitName: mm.Unit().Name(), UnitAbbr: mm.Unit().Abbr()}
if out.round {
t = mm.Time().Round(out.interval).Unix()
} else {
t = mm.Time().Unix()
}
libratoMetric := LibratoMetric{mm.Name(out.prefix), mm.Value(), t, out.source, attrs}
switch mm.Type() {
case CounterType:
counters = append(counters, libratoMetric)
case GaugeType, FloatGaugeType:
gauges = append(gauges, libratoMetric)
}
return counters, gauges
}
func (out *Librato) deliver() {
ctx := slog.Context{"fn": "prepare", "outputter": "librato"}
for batch := range out.batches {
gauges := make([]LibratoMetric, 0)
counters := make([]LibratoMetric, 0)
for _, mm := range batch {
counters, gauges = out.appendLibratoMetric(counters, gauges, mm)
}
if out.meta {
counters, gauges = out.appendLibratoMetric(
counters,
gauges,
GaugeMeasurement{time.Now(), "librato-outlet", []string{"batch", "guage", "size"}, uint64(len(gauges) + 2), Metrics},
)
counters, gauges = out.appendLibratoMetric(
counters,
gauges,
GaugeMeasurement{time.Now(), "librato-outlet", []string{"batch", "counter", "size"}, uint64(len(counters)), Metrics},
)
}
payload := LibratoPostBody{gauges, counters}
j, err := json.Marshal(payload)
if err != nil {
FatalError(ctx, err, "marshaling json")
}
out.sendWithBackoff(j)
}
}
func (out *Librato) sendWithBackoff(payload []byte) bool {
ctx := slog.Context{"fn": "sendWithBackoff", "outputter": "librato", "backoff": LibratoStartingBackoff, "attempts": 0}
for ctx["attempts"].(int) < LibratoMaxAttempts {
retry, err := out.send(payload)
if retry {
LogError(ctx, err, "backing off")
ctx["backoff"] = backoff(ctx["backoff"].(time.Duration))
} else {
if err != nil {
LogError(ctx, err, "error sending, no retry")
return false
} else {
return true
}
}
ctx["attempts"] = ctx["attempts"].(int) + 1
}
return false
}
// Attempts to send the payload and signals retries on errors
func (out *Librato) send(payload []byte) (bool, error) {
body := bytes.NewReader(payload)
req, err := http.NewRequest("POST", out.Url, body)
if err != nil {
return false, err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", out.userAgent)
req.SetBasicAuth(out.User, out.Token)
resp, err := out.client.Do(req)
if err != nil {
return true, err
} else {
defer resp.Body.Close()
if resp.StatusCode >= 300 {
b, _ := ioutil.ReadAll(resp.Body)
if resp.StatusCode >= 500 {
err = fmt.Errorf("server error: %d, body: %+q", resp.StatusCode, string(b))
return true, err
} else {
err = fmt.Errorf("client error: %d, body: %+q", resp.StatusCode, string(b))
return false, err
}
}
}
return false, nil
}
// Sleeps `bo` and then returns double
func backoff(bo time.Duration) time.Duration {
time.Sleep(bo)
return bo * 2
}