Add call to optional Init function for all plugins (#5899)

This commit is contained in:
Daniel Nelson
2019-06-14 15:12:27 -07:00
committed by GitHub
parent b35beb2fba
commit 0ff9c8ef88
12 changed files with 131 additions and 39 deletions

View File

@@ -1,7 +1,6 @@
package http
import (
"errors"
"fmt"
"io"
"io/ioutil"
@@ -89,27 +88,25 @@ func (*HTTP) Description() string {
return "Read formatted metrics from one or more HTTP endpoints"
}
func (h *HTTP) Init() error {
tlsCfg, err := h.ClientConfig.TLSConfig()
if err != nil {
return err
}
h.client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
Proxy: http.ProxyFromEnvironment,
},
Timeout: h.Timeout.Duration,
}
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 {
if h.parser == nil {
return errors.New("Parser is not set")
}
if h.client == nil {
tlsCfg, err := h.ClientConfig.TLSConfig()
if err != nil {
return err
}
h.client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
Proxy: http.ProxyFromEnvironment,
},
Timeout: h.Timeout.Duration,
}
}
var wg sync.WaitGroup
for _, u := range h.URLs {
wg.Add(1)

View File

@@ -37,6 +37,7 @@ func TestHTTPwithJSONFormat(t *testing.T) {
plugin.SetParser(p)
var acc testutil.Accumulator
plugin.Init()
require.NoError(t, acc.GatherError(plugin.Gather))
require.Len(t, acc.Metrics, 1)
@@ -78,6 +79,7 @@ func TestHTTPHeaders(t *testing.T) {
plugin.SetParser(p)
var acc testutil.Accumulator
plugin.Init()
require.NoError(t, acc.GatherError(plugin.Gather))
}
@@ -100,6 +102,7 @@ func TestInvalidStatusCode(t *testing.T) {
plugin.SetParser(p)
var acc testutil.Accumulator
plugin.Init()
require.Error(t, acc.GatherError(plugin.Gather))
}
@@ -125,28 +128,10 @@ func TestMethod(t *testing.T) {
plugin.SetParser(p)
var acc testutil.Accumulator
plugin.Init()
require.NoError(t, acc.GatherError(plugin.Gather))
}
func TestParserNotSet(t *testing.T) {
fakeServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/endpoint" {
_, _ = w.Write([]byte(simpleJSON))
} else {
w.WriteHeader(http.StatusNotFound)
}
}))
defer fakeServer.Close()
url := fakeServer.URL + "/endpoint"
plugin := &plugin.HTTP{
URLs: []string{url},
}
var acc testutil.Accumulator
require.Error(t, acc.GatherError(plugin.Gather))
}
const simpleJSON = `
{
"a": 1.2
@@ -237,6 +222,7 @@ func TestBodyAndContentEncoding(t *testing.T) {
tt.plugin.SetParser(parser)
var acc testutil.Accumulator
tt.plugin.Init()
err = tt.plugin.Gather(&acc)
require.NoError(t, err)
})