-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
librato.go
256 lines (226 loc) · 6.12 KB
/
librato.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
246
247
248
249
250
251
252
253
254
255
256
//go:generate ../../../tools/readme_config_includer/generator
package librato
import (
"bytes"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"regexp"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/outputs"
"github.com/influxdata/telegraf/plugins/serializers/graphite"
)
//go:embed sample.conf
var sampleConfig string
// Librato structure for configuration and client
type Librato struct {
APIUser config.Secret `toml:"api_user"`
APIToken config.Secret `toml:"api_token"`
Debug bool `toml:"debug"`
SourceTag string `toml:"source_tag" deprecated:"1.0.0;use 'template' instead"`
Timeout config.Duration `toml:"timeout"`
Template string `toml:"template"`
Log telegraf.Logger `toml:"-"`
APIUrl string
client *http.Client
}
// https://www.librato.com/docs/kb/faq/best_practices/naming_convention_metrics_sources.html#naming-limitations-for-sources-and-metrics
var reUnacceptedChar = regexp.MustCompile("[^.a-zA-Z0-9_-]")
// LMetrics is the default struct for Librato's API format
type LMetrics struct {
Gauges []*Gauge `json:"gauges"`
}
// Gauge is the gauge format for Librato's API format
type Gauge struct {
Name string `json:"name"`
Value float64 `json:"value"`
Source string `json:"source"`
MeasureTime int64 `json:"measure_time"`
}
const libratoAPI = "https://metrics-api.librato.com/v1/metrics"
// NewLibrato is the main constructor for librato output plugins
func NewLibrato(apiURL string) *Librato {
return &Librato{
APIUrl: apiURL,
Template: "host",
}
}
func (*Librato) SampleConfig() string {
return sampleConfig
}
// Connect is the default output plugin connection function who make sure it
// can connect to the endpoint
func (l *Librato) Connect() error {
if l.APIUser.Empty() || l.APIToken.Empty() {
return errors.New("api_user and api_token required")
}
l.client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
Timeout: time.Duration(l.Timeout),
}
return nil
}
func (l *Librato) Write(metrics []telegraf.Metric) error {
if len(metrics) == 0 {
return nil
}
if l.Template == "" {
l.Template = "host"
}
if l.SourceTag != "" {
l.Template = l.SourceTag
}
tempGauges := []*Gauge{}
for _, m := range metrics {
if gauges, err := l.buildGauges(m); err == nil {
for _, gauge := range gauges {
tempGauges = append(tempGauges, gauge)
l.Log.Debugf("Got a gauge: %v", gauge)
}
} else {
l.Log.Infof("Unable to build Gauge for %s, skipping", m.Name())
l.Log.Debugf("Couldn't build gauge: %v", err)
}
}
metricCounter := len(tempGauges)
// make sure we send a batch of maximum 300
sizeBatch := 300
for start := 0; start < metricCounter; start += sizeBatch {
err := l.writeBatch(start, sizeBatch, metricCounter, tempGauges)
if err != nil {
return err
}
}
return nil
}
func (l *Librato) writeBatch(start int, sizeBatch int, metricCounter int, tempGauges []*Gauge) error {
lmetrics := LMetrics{}
end := start + sizeBatch
if end > metricCounter {
end = metricCounter
sizeBatch = end - start
}
lmetrics.Gauges = make([]*Gauge, sizeBatch)
copy(lmetrics.Gauges, tempGauges[start:end])
metricsBytes, err := json.Marshal(lmetrics)
if err != nil {
return fmt.Errorf("unable to marshal Metrics: %w", err)
}
l.Log.Debugf("Librato request: %v", string(metricsBytes))
req, err := http.NewRequest(
"POST",
l.APIUrl,
bytes.NewBuffer(metricsBytes))
if err != nil {
return fmt.Errorf("unable to create http.Request: %w", err)
}
req.Header.Add("Content-Type", "application/json")
user, err := l.APIUser.Get()
if err != nil {
return fmt.Errorf("getting user failed: %w", err)
}
token, err := l.APIToken.Get()
if err != nil {
user.Destroy()
return fmt.Errorf("getting token failed: %w", err)
}
req.SetBasicAuth(user.String(), token.String())
user.Destroy()
token.Destroy()
resp, err := l.client.Do(req)
if err != nil {
l.Log.Debugf("Error POSTing metrics: %v", err.Error())
return fmt.Errorf("error POSTing metrics: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 || l.Debug {
htmlData, err := io.ReadAll(resp.Body)
if err != nil {
l.Log.Debugf("Couldn't get response! (%v)", err)
}
if resp.StatusCode != 200 {
return fmt.Errorf(
"received bad status code, %d\n %s",
resp.StatusCode,
string(htmlData))
}
l.Log.Debugf("Librato response: %v", string(htmlData))
}
return nil
}
func (l *Librato) buildGauges(m telegraf.Metric) ([]*Gauge, error) {
gauges := []*Gauge{}
if m.Time().Unix() == 0 {
return gauges, fmt.Errorf("time was zero %s", m.Name())
}
metricSource := graphite.InsertField(
graphite.SerializeBucketName("", m.Tags(), l.Template, ""),
"value")
if metricSource == "" {
return gauges,
fmt.Errorf("undeterminable Source type from Field, %s", l.Template)
}
for fieldName, value := range m.Fields() {
metricName := m.Name()
if fieldName != "value" {
metricName = fmt.Sprintf("%s.%s", m.Name(), fieldName)
}
gauge := &Gauge{
Source: reUnacceptedChar.ReplaceAllString(metricSource, "-"),
Name: reUnacceptedChar.ReplaceAllString(metricName, "-"),
MeasureTime: m.Time().Unix(),
}
if !verifyValue(value) {
continue
}
if err := gauge.setValue(value); err != nil {
return gauges, fmt.Errorf("unable to extract value from Fields: %w", err)
}
gauges = append(gauges, gauge)
}
l.Log.Debugf("Built gauges: %v", gauges)
return gauges, nil
}
func verifyValue(v interface{}) bool {
switch v.(type) {
case string:
return false
default:
return true
}
}
func (g *Gauge) setValue(v interface{}) error {
switch d := v.(type) {
case int64:
g.Value = float64(d)
case uint64:
g.Value = float64(d)
case float64:
g.Value = d
case bool:
if d {
g.Value = float64(1.0)
} else {
g.Value = float64(0.0)
}
default:
return fmt.Errorf("undeterminable type %+v", d)
}
return nil
}
// Close is used to close the connection to librato Output
func (l *Librato) Close() error {
return nil
}
func init() {
outputs.Add("librato", func() telegraf.Output {
return NewLibrato(libratoAPI)
})
}