-
Notifications
You must be signed in to change notification settings - Fork 0
/
influxdb_collector.go
197 lines (159 loc) · 4.17 KB
/
influxdb_collector.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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"sync"
"text/template"
)
type httpClient interface {
Post(string, string, io.Reader) (*http.Response, error)
PostForm(string, url.Values) (*http.Response, error)
}
// InfluxdbCollector is a collector which pushes into the popular timeseries
// database "Influx"
type InfluxdbCollector struct {
Host string
Database string
client httpClient
funcs template.FuncMap
indices map[string]byte
queue []string
queueLen int
queueMutex *sync.Mutex
}
// NewInfluxdbCollector will bootstrap an InfluxdbCollector
// and configuree some `text/template' functions
func NewInfluxdbCollector(host, db string) (c *InfluxdbCollector, err error) {
c = &InfluxdbCollector{
Host: host,
Database: db,
client: new(http.Client),
funcs: make(template.FuncMap),
indices: make(map[string]byte),
queue: make([]string, 0),
queueLen: 2048,
queueMutex: new(sync.Mutex),
}
c.funcs["unix"] = unix
c.funcs["nanoseconds"] = nanoseconds
c.funcs["cleanURL"] = cleanURL
return
}
// CreateIndex takes a database name, templates it into an influx query,
// and posts this to influx. It then stores the index to ensure it's not
// created over and over. While this is idempotent in influx, it's still
// inefficient
func (c *InfluxdbCollector) CreateIndex(database string) (err error) {
t := "CREATE DATABASE {{.}}"
q, err := c.tmpl(t, database)
if err != nil {
return
}
err = c.postQuery("query", q)
if err != nil {
return
}
c.indices[database] = '1'
return
}
// Push takes output and pushes it into an influx database. If this database
// is not known to exist (so: this instance of the collector doesn't know it)
// then it will create it
func (c *InfluxdbCollector) Push(o OutputMapper) (err error) {
if o.output.Timestamp.UnixNano() == -6795364578871345152 {
// We've ingested some really invalid data that doesn't have even
// a timestamp
return fmt.Errorf("Missing timestamp")
}
t := "request,url={{cleanURL .URL}},method={{.Method}},status={{.Status}},error={{if .Error}}true{{else}}false{{end}} size={{.Size}},duration={{nanoseconds .Duration}} {{unix .Timestamp}}"
q, err := c.tmpl(t, o.output)
if err != nil {
return
}
c.queueMutex.Lock()
defer c.queueMutex.Unlock()
c.queue = append(c.queue, q)
if len(c.queue) >= c.queueLen {
if _, ok := c.indices[o.database]; !ok {
err = c.CreateIndex(o.database)
if err != nil {
return
}
}
p := fmt.Sprintf("write?db=%s", o.database)
err = c.post(p, strings.Join(c.queue, "\n"))
if err != nil {
return
}
c.queue = nil
}
return
}
func (c InfluxdbCollector) tmpl(s string, i interface{}) (out string, err error) {
tmpl, err := template.New("create").Funcs(c.funcs).Parse(s)
if err != nil {
return
}
outputBuffer := bytes.NewBuffer(make([]byte, 0))
err = tmpl.Execute(outputBuffer, i)
if err != nil {
return
}
out = outputBuffer.String()
return
}
func (c InfluxdbCollector) post(path, data string) (err error) {
r := strings.NewReader(data)
resp, err := c.client.Post(fmt.Sprintf("%s/%s", c.Host, path), "", r)
if err != nil {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 204 {
if resp.Request == nil {
err = fmt.Errorf("(INCOMPLETE LOG) %s - %s", resp.Status, string(body))
} else {
err = fmt.Errorf("%s on %s returned %s - %s",
resp.Request.Method,
resp.Request.URL.String(),
resp.Status,
string(body),
)
}
}
return
}
func (c InfluxdbCollector) postQuery(path, query string) (err error) {
fmt.Println(query)
resp, err := c.client.PostForm(fmt.Sprintf("%s/%s", c.Host, path), url.Values{"q": {query}})
if err != nil {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 && resp.StatusCode != 204 {
if resp.Request == nil {
err = fmt.Errorf("(INCOMPLETE LOG) %s - %s", resp.Status, string(body))
} else {
err = fmt.Errorf("%s on %s returned %s - %s",
resp.Request.Method,
resp.Request.URL.String(),
resp.Status,
string(body),
)
}
}
return
}