forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
196 lines (161 loc) · 4.59 KB
/
http.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
package http
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
httpconfig "github.com/influxdata/telegraf/plugins/common/http"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/outputs"
"github.com/influxdata/telegraf/plugins/serializers"
)
const (
defaultURL = "http://127.0.0.1:8080/telegraf"
)
var sampleConfig = `
## URL is the address to send metrics to
url = "http://127.0.0.1:8080/telegraf"
## Timeout for HTTP message
# timeout = "5s"
## HTTP method, one of: "POST" or "PUT"
# method = "POST"
## HTTP Basic Auth credentials
# username = "username"
# password = "pa$$word"
## OAuth2 Client Credentials Grant
# client_id = "clientid"
# client_secret = "secret"
# token_url = "https://indentityprovider/oauth2/v1/token"
# scopes = ["urn:opc:idm:__myscopes__"]
## Optional TLS Config
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
## Use TLS but skip chain & host verification
# insecure_skip_verify = false
## Data format to output.
## Each data format has it's own unique set of configuration options, read
## more about them here:
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_OUTPUT.md
# data_format = "influx"
## HTTP Content-Encoding for write request body, can be set to "gzip" to
## compress body or "identity" to apply no encoding.
# content_encoding = "identity"
## Additional HTTP headers
# [outputs.http.headers]
# # Should be set manually to "application/json" for json data_format
# Content-Type = "text/plain; charset=utf-8"
## Idle (keep-alive) connection timeout.
## Maximum amount of time before idle connection is closed.
## Zero means no limit.
# idle_conn_timeout = 0
`
const (
defaultClientTimeout = 5 * time.Second
defaultContentType = "text/plain; charset=utf-8"
defaultMethod = http.MethodPost
)
type HTTP struct {
URL string `toml:"url"`
Method string `toml:"method"`
Username string `toml:"username"`
Password string `toml:"password"`
Headers map[string]string `toml:"headers"`
ContentEncoding string `toml:"content_encoding"`
tls.ClientConfig
httpconfig.HTTPClientConfig
client *http.Client
serializer serializers.Serializer
}
func (h *HTTP) SetSerializer(serializer serializers.Serializer) {
h.serializer = serializer
}
func (h *HTTP) Connect() error {
if h.Method == "" {
h.Method = http.MethodPost
}
h.Method = strings.ToUpper(h.Method)
if h.Method != http.MethodPost && h.Method != http.MethodPut {
return fmt.Errorf("invalid method [%s] %s", h.URL, h.Method)
}
ctx := context.Background()
client, err := h.HTTPClientConfig.CreateClient(ctx)
if err != nil {
return err
}
h.client = client
return nil
}
func (h *HTTP) Close() error {
return nil
}
func (h *HTTP) Description() string {
return "A plugin that can transmit metrics over HTTP"
}
func (h *HTTP) SampleConfig() string {
return sampleConfig
}
func (h *HTTP) Write(metrics []telegraf.Metric) error {
reqBody, err := h.serializer.SerializeBatch(metrics)
if err != nil {
return err
}
return h.write(reqBody)
}
func (h *HTTP) write(reqBody []byte) error {
var reqBodyBuffer io.Reader = bytes.NewBuffer(reqBody)
var err error
if h.ContentEncoding == "gzip" {
rc, err := internal.CompressWithGzip(reqBodyBuffer)
if err != nil {
return err
}
defer rc.Close()
reqBodyBuffer = rc
}
req, err := http.NewRequest(h.Method, h.URL, reqBodyBuffer)
if err != nil {
return err
}
if h.Username != "" || h.Password != "" {
req.SetBasicAuth(h.Username, h.Password)
}
req.Header.Set("User-Agent", internal.ProductToken())
req.Header.Set("Content-Type", defaultContentType)
if h.ContentEncoding == "gzip" {
req.Header.Set("Content-Encoding", "gzip")
}
for k, v := range h.Headers {
if strings.ToLower(k) == "host" {
req.Host = v
}
req.Header.Set(k, v)
}
resp, err := h.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("when writing to [%s] received status code: %d", h.URL, resp.StatusCode)
}
if err != nil {
return fmt.Errorf("when writing to [%s] received error: %v", h.URL, err)
}
return nil
}
func init() {
outputs.Add("http", func() telegraf.Output {
return &HTTP{
Method: defaultMethod,
URL: defaultURL,
}
})
}