/
http.go
237 lines (196 loc) · 4.95 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
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
//go:generate ../../../tools/readme_config_includer/generator
package http
import (
"bytes"
"context"
_ "embed"
"fmt"
"io"
"net/http"
"os"
"strings"
"sync"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
httpconfig "github.com/influxdata/telegraf/plugins/common/http"
"github.com/influxdata/telegraf/plugins/inputs"
)
//go:embed sample.conf
var sampleConfig string
type HTTP struct {
URLs []string `toml:"urls"`
Method string `toml:"method"`
Body string `toml:"body"`
ContentEncoding string `toml:"content_encoding"`
Headers map[string]string `toml:"headers"`
// HTTP Basic Auth Credentials
Username config.Secret `toml:"username"`
Password config.Secret `toml:"password"`
// Absolute path to file with Bearer token
BearerToken string `toml:"bearer_token"`
SuccessStatusCodes []int `toml:"success_status_codes"`
Log telegraf.Logger `toml:"-"`
httpconfig.HTTPClientConfig
client *http.Client
parserFunc telegraf.ParserFunc
}
func (*HTTP) SampleConfig() string {
return sampleConfig
}
func (h *HTTP) Init() error {
ctx := context.Background()
client, err := h.HTTPClientConfig.CreateClient(ctx, h.Log)
if err != nil {
return err
}
h.client = client
// Set default as [200]
if len(h.SuccessStatusCodes) == 0 {
h.SuccessStatusCodes = []int{200}
}
return nil
}
// Gather takes in an accumulator and adds the metrics that the Input
// gathers. This is called every "interval"
func (h *HTTP) Gather(acc telegraf.Accumulator) error {
var wg sync.WaitGroup
for _, u := range h.URLs {
wg.Add(1)
go func(url string) {
defer wg.Done()
if err := h.gatherURL(acc, url); err != nil {
acc.AddError(fmt.Errorf("[url=%s]: %s", url, err))
}
}(u)
}
wg.Wait()
return nil
}
// SetParserFunc takes the data_format from the config and finds the right parser for that format
func (h *HTTP) SetParserFunc(fn telegraf.ParserFunc) {
h.parserFunc = fn
}
// Gathers data from a particular URL
// Parameters:
//
// acc : The telegraf Accumulator to use
// url : endpoint to send request to
//
// Returns:
//
// error: Any error that may have occurred
func (h *HTTP) gatherURL(
acc telegraf.Accumulator,
url string,
) error {
body, err := makeRequestBodyReader(h.ContentEncoding, h.Body)
if err != nil {
return err
}
request, err := http.NewRequest(h.Method, url, body)
if err != nil {
return err
}
if h.BearerToken != "" {
token, err := os.ReadFile(h.BearerToken)
if err != nil {
return err
}
bearer := "Bearer " + strings.Trim(string(token), "\n")
request.Header.Set("Authorization", bearer)
}
if h.ContentEncoding == "gzip" {
request.Header.Set("Content-Encoding", "gzip")
}
for k, v := range h.Headers {
if strings.ToLower(k) == "host" {
request.Host = v
} else {
request.Header.Add(k, v)
}
}
if err := h.setRequestAuth(request); err != nil {
return err
}
resp, err := h.client.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
responseHasSuccessCode := false
for _, statusCode := range h.SuccessStatusCodes {
if resp.StatusCode == statusCode {
responseHasSuccessCode = true
break
}
}
if !responseHasSuccessCode {
return fmt.Errorf("received status code %d (%s), expected any value out of %v",
resp.StatusCode,
http.StatusText(resp.StatusCode),
h.SuccessStatusCodes)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading body failed: %v", err)
}
// Instantiate a new parser for the new data to avoid trouble with stateful parsers
parser, err := h.parserFunc()
if err != nil {
return fmt.Errorf("instantiating parser failed: %v", err)
}
metrics, err := parser.Parse(b)
if err != nil {
return fmt.Errorf("parsing metrics failed: %v", err)
}
for _, metric := range metrics {
if !metric.HasTag("url") {
metric.AddTag("url", url)
}
acc.AddFields(metric.Name(), metric.Fields(), metric.Tags(), metric.Time())
}
return nil
}
func (h *HTTP) setRequestAuth(request *http.Request) error {
if h.Username.Empty() && h.Password.Empty() {
return nil
}
username, err := h.Username.Get()
if err != nil {
return fmt.Errorf("getting username failed: %v", err)
}
defer config.ReleaseSecret(username)
password, err := h.Password.Get()
if err != nil {
return fmt.Errorf("getting password failed: %v", err)
}
defer config.ReleaseSecret(password)
request.SetBasicAuth(string(username), string(password))
return nil
}
func makeRequestBodyReader(contentEncoding, body string) (io.Reader, error) {
if body == "" {
return nil, nil
}
var reader io.Reader = strings.NewReader(body)
if contentEncoding == "gzip" {
rc, err := internal.CompressWithGzip(reader)
if err != nil {
return nil, err
}
data, err := io.ReadAll(rc)
if err != nil {
return nil, err
}
return bytes.NewReader(data), nil
}
return reader, nil
}
func init() {
inputs.Add("http", func() telegraf.Input {
return &HTTP{
Method: "GET",
}
})
}