Get rid of deprecated internal.{Duration,Size,Number} (#8969)

This commit is contained in:
Sven Rebhan 2021-04-09 19:15:04 +02:00 committed by GitHub
parent c66ccee46f
commit 9853bf6c54
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
194 changed files with 1558 additions and 1535 deletions

View File

@ -98,8 +98,8 @@ type outputUnit struct {
func (a *Agent) Run(ctx context.Context) error {
log.Printf("I! [agent] Config: Interval:%s, Quiet:%#v, Hostname:%#v, "+
"Flush Interval:%s",
a.Config.Agent.Interval.Duration, a.Config.Agent.Quiet,
a.Config.Agent.Hostname, a.Config.Agent.FlushInterval.Duration)
time.Duration(a.Config.Agent.Interval), a.Config.Agent.Quiet,
a.Config.Agent.Hostname, time.Duration(a.Config.Agent.FlushInterval))
log.Printf("D! [agent] Initializing plugins")
err := a.initPlugins()
@ -274,19 +274,19 @@ func (a *Agent) runInputs(
var wg sync.WaitGroup
for _, input := range unit.inputs {
// Overwrite agent interval if this plugin has its own.
interval := a.Config.Agent.Interval.Duration
interval := time.Duration(a.Config.Agent.Interval)
if input.Config.Interval != 0 {
interval = input.Config.Interval
}
// Overwrite agent precision if this plugin has its own.
precision := a.Config.Agent.Precision.Duration
precision := time.Duration(a.Config.Agent.Precision)
if input.Config.Precision != 0 {
precision = input.Config.Precision
}
// Overwrite agent collection_jitter if this plugin has its own.
jitter := a.Config.Agent.CollectionJitter.Duration
jitter := time.Duration(a.Config.Agent.CollectionJitter)
if input.Config.CollectionJitter != 0 {
jitter = input.Config.CollectionJitter
}
@ -373,13 +373,13 @@ func (a *Agent) testRunInputs(
defer wg.Done()
// Overwrite agent interval if this plugin has its own.
interval := a.Config.Agent.Interval.Duration
interval := time.Duration(a.Config.Agent.Interval)
if input.Config.Interval != 0 {
interval = input.Config.Interval
}
// Overwrite agent precision if this plugin has its own.
precision := a.Config.Agent.Precision.Duration
precision := time.Duration(a.Config.Agent.Precision)
if input.Config.Precision != 0 {
precision = input.Config.Precision
}
@ -611,8 +611,8 @@ func (a *Agent) runAggregators(
go func(agg *models.RunningAggregator) {
defer wg.Done()
interval := a.Config.Agent.Interval.Duration
precision := a.Config.Agent.Precision.Duration
interval := time.Duration(a.Config.Agent.Interval)
precision := time.Duration(a.Config.Agent.Precision)
acc := NewAccumulator(agg, unit.aggC)
acc.SetPrecision(getPrecision(precision, interval))
@ -723,8 +723,8 @@ func (a *Agent) runOutputs(
var wg sync.WaitGroup
// Start flush loop
interval := a.Config.Agent.FlushInterval.Duration
jitter := a.Config.Agent.FlushJitter.Duration
interval := time.Duration(a.Config.Agent.FlushInterval)
jitter := time.Duration(a.Config.Agent.FlushJitter)
ctx, cancel := context.WithCancel(context.Background())

View File

@ -151,14 +151,12 @@ func runAgent(ctx context.Context,
return errors.New("Error: no inputs found, did you provide a valid config file?")
}
if int64(c.Agent.Interval.Duration) <= 0 {
return fmt.Errorf("Agent interval must be positive, found %s",
c.Agent.Interval.Duration)
if int64(c.Agent.Interval) <= 0 {
return fmt.Errorf("Agent interval must be positive, found %v", c.Agent.Interval)
}
if int64(c.Agent.FlushInterval.Duration) <= 0 {
return fmt.Errorf("Agent flush_interval must be positive; found %s",
c.Agent.Interval.Duration)
if int64(c.Agent.FlushInterval) <= 0 {
return fmt.Errorf("Agent flush_interval must be positive; found %v", c.Agent.Interval)
}
ag, err := agent.NewAgent(c)

View File

@ -82,9 +82,9 @@ func NewConfig() *Config {
// Agent defaults:
Agent: &AgentConfig{
Interval: internal.Duration{Duration: 10 * time.Second},
Interval: Duration(10 * time.Second),
RoundInterval: true,
FlushInterval: internal.Duration{Duration: 10 * time.Second},
FlushInterval: Duration(10 * time.Second),
LogTarget: "file",
LogfileRotationMaxArchives: 5,
},
@ -111,7 +111,7 @@ func NewConfig() *Config {
// AgentConfig defines configuration that will be used by the Telegraf agent
type AgentConfig struct {
// Interval at which to gather information
Interval internal.Duration
Interval Duration
// RoundInterval rounds collection interval to 'interval'.
// ie, if Interval=10s then always collect on :00, :10, :20, etc.
@ -123,22 +123,22 @@ type AgentConfig struct {
// when interval = "250ms", precision will be "1ms"
// Precision will NOT be used for service inputs. It is up to each individual
// service input to set the timestamp at the appropriate precision.
Precision internal.Duration
Precision Duration
// CollectionJitter is used to jitter the collection by a random amount.
// Each plugin will sleep for a random time within jitter before collecting.
// This can be used to avoid many plugins querying things like sysfs at the
// same time, which can have a measurable effect on the system.
CollectionJitter internal.Duration
CollectionJitter Duration
// FlushInterval is the Interval at which to flush data
FlushInterval internal.Duration
FlushInterval Duration
// FlushJitter Jitters the flush interval by a random amount.
// This is primarily to avoid large write spikes for users running a large
// number of telegraf instances.
// ie, a jitter of 5s and interval 10s means flushes will happen every 10-15s
FlushJitter internal.Duration
FlushJitter Duration
// MetricBatchSize is the maximum number of metrics that is wrote to an
// output plugin in one call.
@ -178,11 +178,11 @@ type AgentConfig struct {
// The file will be rotated after the time interval specified. When set
// to 0 no time based rotation is performed.
LogfileRotationInterval internal.Duration `toml:"logfile_rotation_interval"`
LogfileRotationInterval Duration `toml:"logfile_rotation_interval"`
// The logfile will be rotated when it becomes larger than the specified
// size. When set to 0 no size based rotation is performed.
LogfileRotationMaxSize internal.Size `toml:"logfile_rotation_max_size"`
LogfileRotationMaxSize Size `toml:"logfile_rotation_max_size"`
// Maximum number of rotated archives to keep, any older logs are deleted.
// If set to -1, no archives are removed.

View File

@ -1,6 +1,7 @@
package config
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
@ -8,30 +9,23 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/models"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/exec"
"github.com/influxdata/telegraf/plugins/inputs/http_listener_v2"
"github.com/influxdata/telegraf/plugins/inputs/memcached"
"github.com/influxdata/telegraf/plugins/inputs/procstat"
"github.com/influxdata/telegraf/plugins/outputs/azure_monitor"
httpOut "github.com/influxdata/telegraf/plugins/outputs/http"
"github.com/influxdata/telegraf/plugins/outputs"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfig_LoadSingleInputWithEnvVars(t *testing.T) {
c := NewConfig()
err := os.Setenv("MY_TEST_SERVER", "192.168.1.1")
assert.NoError(t, err)
err = os.Setenv("TEST_INTERVAL", "10s")
assert.NoError(t, err)
require.NoError(t, os.Setenv("MY_TEST_SERVER", "192.168.1.1"))
require.NoError(t, os.Setenv("TEST_INTERVAL", "10s"))
c.LoadConfig("./testdata/single_plugin_env_vars.toml")
memcached := inputs.Inputs["memcached"]().(*memcached.Memcached)
memcached.Servers = []string{"192.168.1.1"}
input := inputs.Inputs["memcached"]().(*MockupInputPlugin)
input.Servers = []string{"192.168.1.1"}
filter := models.Filter{
NameDrop: []string{"metricname2"},
@ -51,26 +45,27 @@ func TestConfig_LoadSingleInputWithEnvVars(t *testing.T) {
},
},
}
assert.NoError(t, filter.Compile())
mConfig := &models.InputConfig{
require.NoError(t, filter.Compile())
inputConfig := &models.InputConfig{
Name: "memcached",
Filter: filter,
Interval: 10 * time.Second,
}
mConfig.Tags = make(map[string]string)
inputConfig.Tags = make(map[string]string)
assert.Equal(t, memcached, c.Inputs[0].Input,
"Testdata did not produce a correct memcached struct.")
assert.Equal(t, mConfig, c.Inputs[0].Config,
"Testdata did not produce correct memcached metadata.")
// Ignore Log and Parser
c.Inputs[0].Input.(*MockupInputPlugin).Log = nil
c.Inputs[0].Input.(*MockupInputPlugin).parser = nil
require.Equal(t, input, c.Inputs[0].Input, "Testdata did not produce a correct mockup struct.")
require.Equal(t, inputConfig, c.Inputs[0].Config, "Testdata did not produce correct input metadata.")
}
func TestConfig_LoadSingleInput(t *testing.T) {
c := NewConfig()
c.LoadConfig("./testdata/single_plugin.toml")
memcached := inputs.Inputs["memcached"]().(*memcached.Memcached)
memcached.Servers = []string{"localhost"}
input := inputs.Inputs["memcached"]().(*MockupInputPlugin)
input.Servers = []string{"localhost"}
filter := models.Filter{
NameDrop: []string{"metricname2"},
@ -90,35 +85,34 @@ func TestConfig_LoadSingleInput(t *testing.T) {
},
},
}
assert.NoError(t, filter.Compile())
mConfig := &models.InputConfig{
require.NoError(t, filter.Compile())
inputConfig := &models.InputConfig{
Name: "memcached",
Filter: filter,
Interval: 5 * time.Second,
}
mConfig.Tags = make(map[string]string)
inputConfig.Tags = make(map[string]string)
assert.Equal(t, memcached, c.Inputs[0].Input,
"Testdata did not produce a correct memcached struct.")
assert.Equal(t, mConfig, c.Inputs[0].Config,
"Testdata did not produce correct memcached metadata.")
// Ignore Log and Parser
c.Inputs[0].Input.(*MockupInputPlugin).Log = nil
c.Inputs[0].Input.(*MockupInputPlugin).parser = nil
require.Equal(t, input, c.Inputs[0].Input, "Testdata did not produce a correct memcached struct.")
require.Equal(t, inputConfig, c.Inputs[0].Config, "Testdata did not produce correct memcached metadata.")
}
func TestConfig_LoadDirectory(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("./testdata/single_plugin.toml")
if err != nil {
t.Error(err)
}
err = c.LoadDirectory("./testdata/subconfig")
if err != nil {
t.Error(err)
}
require.NoError(t, c.LoadConfig("./testdata/single_plugin.toml"))
require.NoError(t, c.LoadDirectory("./testdata/subconfig"))
memcached := inputs.Inputs["memcached"]().(*memcached.Memcached)
memcached.Servers = []string{"localhost"}
// Create the expected data
expectedPlugins := make([]*MockupInputPlugin, 4)
expectedConfigs := make([]*models.InputConfig, 4)
filter := models.Filter{
expectedPlugins[0] = inputs.Inputs["memcached"]().(*MockupInputPlugin)
expectedPlugins[0].Servers = []string{"localhost"}
filterMockup := models.Filter{
NameDrop: []string{"metricname2"},
NamePass: []string{"metricname1"},
FieldDrop: []string{"other", "stuff"},
@ -136,120 +130,138 @@ func TestConfig_LoadDirectory(t *testing.T) {
},
},
}
assert.NoError(t, filter.Compile())
mConfig := &models.InputConfig{
require.NoError(t, filterMockup.Compile())
expectedConfigs[0] = &models.InputConfig{
Name: "memcached",
Filter: filter,
Filter: filterMockup,
Interval: 5 * time.Second,
}
mConfig.Tags = make(map[string]string)
expectedConfigs[0].Tags = make(map[string]string)
assert.Equal(t, memcached, c.Inputs[0].Input,
"Testdata did not produce a correct memcached struct.")
assert.Equal(t, mConfig, c.Inputs[0].Config,
"Testdata did not produce correct memcached metadata.")
ex := inputs.Inputs["exec"]().(*exec.Exec)
expectedPlugins[1] = inputs.Inputs["exec"]().(*MockupInputPlugin)
p, err := parsers.NewParser(&parsers.Config{
MetricName: "exec",
DataFormat: "json",
JSONStrict: true,
})
assert.NoError(t, err)
ex.SetParser(p)
ex.Command = "/usr/bin/myothercollector --foo=bar"
eConfig := &models.InputConfig{
require.NoError(t, err)
expectedPlugins[1].SetParser(p)
expectedPlugins[1].Command = "/usr/bin/myothercollector --foo=bar"
expectedConfigs[1] = &models.InputConfig{
Name: "exec",
MeasurementSuffix: "_myothercollector",
}
eConfig.Tags = make(map[string]string)
expectedConfigs[1].Tags = make(map[string]string)
exec := c.Inputs[1].Input.(*exec.Exec)
require.NotNil(t, exec.Log)
exec.Log = nil
expectedPlugins[2] = inputs.Inputs["memcached"]().(*MockupInputPlugin)
expectedPlugins[2].Servers = []string{"192.168.1.1"}
assert.Equal(t, ex, c.Inputs[1].Input,
"Merged Testdata did not produce a correct exec struct.")
assert.Equal(t, eConfig, c.Inputs[1].Config,
"Merged Testdata did not produce correct exec metadata.")
filterMemcached := models.Filter{
NameDrop: []string{"metricname2"},
NamePass: []string{"metricname1"},
FieldDrop: []string{"other", "stuff"},
FieldPass: []string{"some", "strings"},
TagDrop: []models.TagFilter{
{
Name: "badtag",
Filter: []string{"othertag"},
},
},
TagPass: []models.TagFilter{
{
Name: "goodtag",
Filter: []string{"mytag"},
},
},
}
require.NoError(t, filterMemcached.Compile())
expectedConfigs[2] = &models.InputConfig{
Name: "memcached",
Filter: filterMemcached,
Interval: 5 * time.Second,
}
expectedConfigs[2].Tags = make(map[string]string)
memcached.Servers = []string{"192.168.1.1"}
assert.Equal(t, memcached, c.Inputs[2].Input,
"Testdata did not produce a correct memcached struct.")
assert.Equal(t, mConfig, c.Inputs[2].Config,
"Testdata did not produce correct memcached metadata.")
expectedPlugins[3] = inputs.Inputs["procstat"]().(*MockupInputPlugin)
expectedPlugins[3].PidFile = "/var/run/grafana-server.pid"
expectedConfigs[3] = &models.InputConfig{Name: "procstat"}
expectedConfigs[3].Tags = make(map[string]string)
pstat := inputs.Inputs["procstat"]().(*procstat.Procstat)
pstat.PidFile = "/var/run/grafana-server.pid"
// Check the generated plugins
require.Len(t, c.Inputs, len(expectedPlugins))
require.Len(t, c.Inputs, len(expectedConfigs))
for i, plugin := range c.Inputs {
input := plugin.Input.(*MockupInputPlugin)
// Check the logger and ignore it for comparison
require.NotNil(t, input.Log)
input.Log = nil
pConfig := &models.InputConfig{Name: "procstat"}
pConfig.Tags = make(map[string]string)
// Ignore the parser if not expected
if expectedPlugins[i].parser == nil {
input.parser = nil
}
assert.Equal(t, pstat, c.Inputs[3].Input,
"Merged Testdata did not produce a correct procstat struct.")
assert.Equal(t, pConfig, c.Inputs[3].Config,
"Merged Testdata did not produce correct procstat metadata.")
require.Equalf(t, expectedPlugins[i], plugin.Input, "Plugin %d: incorrect struct produced", i)
require.Equalf(t, expectedConfigs[i], plugin.Config, "Plugin %d: incorrect config produced", i)
}
}
func TestConfig_LoadSpecialTypes(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("./testdata/special_types.toml")
assert.NoError(t, err)
require.Equal(t, 1, len(c.Inputs))
require.NoError(t, c.LoadConfig("./testdata/special_types.toml"))
require.Len(t, c.Inputs, 1)
inputHTTPListener, ok := c.Inputs[0].Input.(*http_listener_v2.HTTPListenerV2)
assert.Equal(t, true, ok)
input, ok := c.Inputs[0].Input.(*MockupInputPlugin)
require.True(t, ok)
// Tests telegraf duration parsing.
assert.Equal(t, internal.Duration{Duration: time.Second}, inputHTTPListener.WriteTimeout)
require.Equal(t, Duration(time.Second), input.WriteTimeout)
// Tests telegraf size parsing.
assert.Equal(t, internal.Size{Size: 1024 * 1024}, inputHTTPListener.MaxBodySize)
require.Equal(t, Size(1024*1024), input.MaxBodySize)
// Tests toml multiline basic strings.
assert.Equal(t, "/path/to/my/cert", strings.TrimRight(inputHTTPListener.TLSCert, "\r\n"))
require.Equal(t, "/path/to/my/cert", strings.TrimRight(input.TLSCert, "\r\n"))
}
func TestConfig_FieldNotDefined(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("./testdata/invalid_field.toml")
require.Error(t, err, "invalid field name")
assert.Equal(t, "Error loading config file ./testdata/invalid_field.toml: plugin inputs.http_listener_v2: line 1: configuration specified the fields [\"not_a_field\"], but they weren't used", err.Error())
require.Equal(t, "Error loading config file ./testdata/invalid_field.toml: plugin inputs.http_listener_v2: line 1: configuration specified the fields [\"not_a_field\"], but they weren't used", err.Error())
}
func TestConfig_WrongFieldType(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("./testdata/wrong_field_type.toml")
require.Error(t, err, "invalid field type")
assert.Equal(t, "Error loading config file ./testdata/wrong_field_type.toml: error parsing http_listener_v2, line 2: (http_listener_v2.HTTPListenerV2.Port) cannot unmarshal TOML string into int", err.Error())
require.Equal(t, "Error loading config file ./testdata/wrong_field_type.toml: error parsing http_listener_v2, line 2: (config.MockupInputPlugin.Port) cannot unmarshal TOML string into int", err.Error())
c = NewConfig()
err = c.LoadConfig("./testdata/wrong_field_type2.toml")
require.Error(t, err, "invalid field type2")
assert.Equal(t, "Error loading config file ./testdata/wrong_field_type2.toml: error parsing http_listener_v2, line 2: (http_listener_v2.HTTPListenerV2.Methods) cannot unmarshal TOML string into []string", err.Error())
require.Equal(t, "Error loading config file ./testdata/wrong_field_type2.toml: error parsing http_listener_v2, line 2: (config.MockupInputPlugin.Methods) cannot unmarshal TOML string into []string", err.Error())
}
func TestConfig_InlineTables(t *testing.T) {
// #4098
c := NewConfig()
err := c.LoadConfig("./testdata/inline_table.toml")
assert.NoError(t, err)
require.Equal(t, 2, len(c.Outputs))
require.NoError(t, c.LoadConfig("./testdata/inline_table.toml"))
require.Len(t, c.Outputs, 2)
outputHTTP, ok := c.Outputs[1].Output.(*httpOut.HTTP)
assert.Equal(t, true, ok)
assert.Equal(t, map[string]string{"Authorization": "Token $TOKEN", "Content-Type": "application/json"}, outputHTTP.Headers)
assert.Equal(t, []string{"org_id"}, c.Outputs[0].Config.Filter.TagInclude)
output, ok := c.Outputs[1].Output.(*MockupOuputPlugin)
require.True(t, ok)
require.Equal(t, map[string]string{"Authorization": "Token $TOKEN", "Content-Type": "application/json"}, output.Headers)
require.Equal(t, []string{"org_id"}, c.Outputs[0].Config.Filter.TagInclude)
}
func TestConfig_SliceComment(t *testing.T) {
t.Skipf("Skipping until #3642 is resolved")
c := NewConfig()
err := c.LoadConfig("./testdata/slice_comment.toml")
assert.NoError(t, err)
require.Equal(t, 1, len(c.Outputs))
require.NoError(t, c.LoadConfig("./testdata/slice_comment.toml"))
require.Len(t, c.Outputs, 1)
outputHTTP, ok := c.Outputs[0].Output.(*httpOut.HTTP)
assert.Equal(t, []string{"test"}, outputHTTP.Scopes)
assert.Equal(t, true, ok)
output, ok := c.Outputs[0].Output.(*MockupOuputPlugin)
require.True(t, ok)
require.Equal(t, []string{"test"}, output.Scopes)
}
func TestConfig_BadOrdering(t *testing.T) {
@ -258,27 +270,21 @@ func TestConfig_BadOrdering(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("./testdata/non_slice_slice.toml")
require.Error(t, err, "bad ordering")
assert.Equal(t, "Error loading config file ./testdata/non_slice_slice.toml: error parsing http array, line 4: cannot unmarshal TOML array into string (need slice)", err.Error())
require.Equal(t, "Error loading config file ./testdata/non_slice_slice.toml: error parsing http array, line 4: cannot unmarshal TOML array into string (need slice)", err.Error())
}
func TestConfig_AzureMonitorNamespacePrefix(t *testing.T) {
// #8256 Cannot use empty string as the namespace prefix
c := NewConfig()
defaultPrefixConfig := `[[outputs.azure_monitor]]`
err := c.LoadConfigData([]byte(defaultPrefixConfig))
assert.NoError(t, err)
azureMonitor, ok := c.Outputs[0].Output.(*azure_monitor.AzureMonitor)
assert.Equal(t, "Telegraf/", azureMonitor.NamespacePrefix)
assert.Equal(t, true, ok)
require.NoError(t, c.LoadConfig("./testdata/azure_monitor.toml"))
require.Len(t, c.Outputs, 2)
c = NewConfig()
customPrefixConfig := `[[outputs.azure_monitor]]
namespace_prefix = ""`
err = c.LoadConfigData([]byte(customPrefixConfig))
assert.NoError(t, err)
azureMonitor, ok = c.Outputs[0].Output.(*azure_monitor.AzureMonitor)
assert.Equal(t, "", azureMonitor.NamespacePrefix)
assert.Equal(t, true, ok)
expectedPrefix := []string{"Telegraf/", ""}
for i, plugin := range c.Outputs {
output, ok := plugin.Output.(*MockupOuputPlugin)
require.True(t, ok)
require.Equal(t, expectedPrefix[i], output.NamespacePrefix)
}
}
func TestConfig_URLRetries3Fails(t *testing.T) {
@ -290,9 +296,12 @@ func TestConfig_URLRetries3Fails(t *testing.T) {
}))
defer ts.Close()
expected := fmt.Sprintf("Error loading config file %s: Retry 3 of 3 failed to retrieve remote config: 404 Not Found", ts.URL)
c := NewConfig()
err := c.LoadConfig(ts.URL)
require.Error(t, err)
require.Equal(t, expected, err.Error())
require.Equal(t, 4, responseCounter)
}
@ -310,7 +319,57 @@ func TestConfig_URLRetries3FailsThenPasses(t *testing.T) {
defer ts.Close()
c := NewConfig()
err := c.LoadConfig(ts.URL)
require.NoError(t, err)
require.NoError(t, c.LoadConfig(ts.URL))
require.Equal(t, 4, responseCounter)
}
/*** Mockup INPUT plugin for testing to avoid cyclic dependencies ***/
type MockupInputPlugin struct {
Servers []string `toml:"servers"`
Methods []string `toml:"methods"`
Timeout Duration `toml:"timeout"`
ReadTimeout Duration `toml:"read_timeout"`
WriteTimeout Duration `toml:"write_timeout"`
MaxBodySize Size `toml:"max_body_size"`
Port int `toml:"port"`
Command string
PidFile string
Log telegraf.Logger `toml:"-"`
tls.ServerConfig
parser parsers.Parser
}
func (m *MockupInputPlugin) SampleConfig() string { return "Mockup test intput plugin" }
func (m *MockupInputPlugin) Description() string { return "Mockup test intput plugin" }
func (m *MockupInputPlugin) Gather(acc telegraf.Accumulator) error { return nil }
func (m *MockupInputPlugin) SetParser(parser parsers.Parser) { m.parser = parser }
/*** Mockup OUTPUT plugin for testing to avoid cyclic dependencies ***/
type MockupOuputPlugin struct {
URL string `toml:"url"`
Headers map[string]string `toml:"headers"`
Scopes []string `toml:"scopes"`
NamespacePrefix string `toml:"namespace_prefix"`
Log telegraf.Logger `toml:"-"`
tls.ClientConfig
}
func (m *MockupOuputPlugin) Connect() error { return nil }
func (m *MockupOuputPlugin) Close() error { return nil }
func (m *MockupOuputPlugin) Description() string { return "Mockup test output plugin" }
func (m *MockupOuputPlugin) SampleConfig() string { return "Mockup test output plugin" }
func (m *MockupOuputPlugin) Write(metrics []telegraf.Metric) error { return nil }
// Register the mockup plugin on loading
func init() {
// Register the mockup input plugin for the required names
inputs.Add("exec", func() telegraf.Input { return &MockupInputPlugin{Timeout: Duration(time.Second * 5)} })
inputs.Add("http_listener_v2", func() telegraf.Input { return &MockupInputPlugin{} })
inputs.Add("memcached", func() telegraf.Input { return &MockupInputPlugin{} })
inputs.Add("procstat", func() telegraf.Input { return &MockupInputPlugin{} })
// Register the mockup output plugin for the required names
outputs.Add("azure_monitor", func() telegraf.Output { return &MockupOuputPlugin{NamespacePrefix: "Telegraf/"} })
outputs.Add("http", func() telegraf.Output { return &MockupOuputPlugin{} })
}

4
config/testdata/azure_monitor.toml vendored Normal file
View File

@ -0,0 +1,4 @@
[[outputs.azure_monitor]]
[[outputs.azure_monitor]]
namespace_prefix = ""

View File

@ -29,3 +29,49 @@ func TestConfigDuration(t *testing.T) {
require.Equal(t, p.MaxParallelLookups, 13)
require.Equal(t, p.Ordered, true)
}
func TestDuration(t *testing.T) {
var d config.Duration
require.NoError(t, d.UnmarshalTOML([]byte(`"1s"`)))
require.Equal(t, time.Second, time.Duration(d))
d = config.Duration(0)
require.NoError(t, d.UnmarshalTOML([]byte(`1s`)))
require.Equal(t, time.Second, time.Duration(d))
d = config.Duration(0)
require.NoError(t, d.UnmarshalTOML([]byte(`'1s'`)))
require.Equal(t, time.Second, time.Duration(d))
d = config.Duration(0)
require.NoError(t, d.UnmarshalTOML([]byte(`10`)))
require.Equal(t, 10*time.Second, time.Duration(d))
d = config.Duration(0)
require.NoError(t, d.UnmarshalTOML([]byte(`1.5`)))
require.Equal(t, time.Second, time.Duration(d))
}
func TestSize(t *testing.T) {
var s config.Size
require.NoError(t, s.UnmarshalTOML([]byte(`"1B"`)))
require.Equal(t, int64(1), int64(s))
s = config.Size(0)
require.NoError(t, s.UnmarshalTOML([]byte(`1`)))
require.Equal(t, int64(1), int64(s))
s = config.Size(0)
require.NoError(t, s.UnmarshalTOML([]byte(`'1'`)))
require.Equal(t, int64(1), int64(s))
s = config.Size(0)
require.NoError(t, s.UnmarshalTOML([]byte(`"1GB"`)))
require.Equal(t, int64(1000*1000*1000), int64(s))
s = config.Size(0)
require.NoError(t, s.UnmarshalTOML([]byte(`"12GiB"`)))
require.Equal(t, int64(12*1024*1024*1024), int64(s))
}

14
go.sum
View File

@ -109,8 +109,12 @@ github.com/Microsoft/ApplicationInsights-Go v0.4.2/go.mod h1:CukZ/G66zxXtI+h/VcV
github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=
github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/NYTimes/gziphandler v0.0.0-20170623195520-56545f4a5d46/go.mod h1:3wb06e3pkSAbeQ52E9H9iFoQsEEwGN64994WTCIhntQ=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.0.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.1.0/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
@ -372,6 +376,8 @@ github.com/go-openapi/errors v0.19.2/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA
github.com/go-openapi/errors v0.19.3/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94=
github.com/go-openapi/errors v0.19.4/go.mod h1:qX0BLWsyaKfvhluLejVpVNwNRdXZhEbTA4kxxpKBC94=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonpointer v0.0.0-20160704185906-46af16f9f7b1/go.mod h1:+35s3my2LFTysnkMfxsJBAMHj/DoqoB9knIWoYG/Vk0=
github.com/go-openapi/jsonpointer v0.17.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M=
github.com/go-openapi/jsonpointer v0.18.0/go.mod h1:cOnomiV+CVVwFLk0A/MExoFMjwdsUdVpsRhURCKh+3M=
github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDBPKZGEoHC/NkiQRg=
@ -379,6 +385,8 @@ github.com/go-openapi/jsonpointer v0.19.2/go.mod h1:3akKfEdA7DF1sugOqz1dVQHBcuDB
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/jsonreference v0.0.0-20160704190145-13c6e3589ad9/go.mod h1:W3Z9FmVs9qj+KR4zFKmDPGiLdk1D9Rlm7cyMvf57TTg=
github.com/go-openapi/jsonreference v0.17.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=
github.com/go-openapi/jsonreference v0.18.0/go.mod h1:g4xxGn04lDIRh0GJb5QlpE3HfopLOL6uZrK/VgnsK9I=
github.com/go-openapi/jsonreference v0.19.2/go.mod h1:jMjeRr2HHw6nAVajTXJ4eiUwohSTlpa0o73RUL1owJc=
@ -397,6 +405,8 @@ github.com/go-openapi/runtime v0.19.0/go.mod h1:OwNfisksmmaZse4+gpV3Ne9AyMOlP1lt
github.com/go-openapi/runtime v0.19.4/go.mod h1:X277bwSUBxVlCYR3r7xgZZGKVvBd/29gLDlFGtJ8NL4=
github.com/go-openapi/runtime v0.19.15/go.mod h1:dhGWCTKRXlAfGnQG0ONViOZpjfg0m2gUt9nTQPQZuoo=
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/spec v0.0.0-20160808142527-6aced65f8501/go.mod h1:J8+jY1nAiCcj+friV/PDoE1/3eeccG9LYBs0tYvLOWc=
github.com/go-openapi/spec v0.17.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI=
github.com/go-openapi/spec v0.18.0/go.mod h1:XkF/MOi14NmjsfZ8VtAKf8pIlbZzyoTvZsdfssdxcBI=
github.com/go-openapi/spec v0.19.2/go.mod h1:sCxk3jxKgioEJikev4fgkNmwS+3kuYdJtcsZsD5zxMY=
@ -972,6 +982,8 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
github.com/rogpeppe/go-internal v1.1.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.2.2/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
@ -1079,6 +1091,8 @@ github.com/tinylib/msgp v1.1.5 h1:2gXmtWueD2HefZHQe1QOy9HVzmFrLOVvsXwXBQ0ayy0=
github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q=
github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/uber/jaeger-client-go v2.25.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk=

View File

@ -2,7 +2,6 @@ package internal
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"errors"
@ -19,8 +18,6 @@ import (
"syscall"
"time"
"unicode"
"github.com/alecthomas/units"
)
const alphanum string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
@ -34,20 +31,6 @@ var (
// Set via the main module
var version string
// Duration just wraps time.Duration
type Duration struct {
Duration time.Duration
}
// Size just wraps an int64
type Size struct {
Size int64
}
type Number struct {
Value float64
}
type ReadWaitCloser struct {
pipeReader *io.PipeReader
wg sync.WaitGroup
@ -73,72 +56,6 @@ func ProductToken() string {
Version(), strings.TrimPrefix(runtime.Version(), "go"))
}
// UnmarshalTOML parses the duration from the TOML config file
func (d *Duration) UnmarshalTOML(b []byte) error {
var err error
b = bytes.Trim(b, `'`)
// see if we can directly convert it
d.Duration, err = time.ParseDuration(string(b))
if err == nil {
return nil
}
// Parse string duration, ie, "1s"
if uq, err := strconv.Unquote(string(b)); err == nil && len(uq) > 0 {
d.Duration, err = time.ParseDuration(uq)
if err == nil {
return nil
}
}
// First try parsing as integer seconds
sI, err := strconv.ParseInt(string(b), 10, 64)
if err == nil {
d.Duration = time.Second * time.Duration(sI)
return nil
}
// Second try parsing as float seconds
sF, err := strconv.ParseFloat(string(b), 64)
if err == nil {
d.Duration = time.Second * time.Duration(sF)
return nil
}
return nil
}
func (s *Size) UnmarshalTOML(b []byte) error {
var err error
b = bytes.Trim(b, `'`)
val, err := strconv.ParseInt(string(b), 10, 64)
if err == nil {
s.Size = val
return nil
}
uq, err := strconv.Unquote(string(b))
if err != nil {
return err
}
val, err = units.ParseStrictBytes(uq)
if err != nil {
return err
}
s.Size = val
return nil
}
func (n *Number) UnmarshalTOML(b []byte) error {
value, err := strconv.ParseFloat(string(b), 64)
if err != nil {
return err
}
n.Value = value
return nil
}
// ReadLines reads contents from a file and splits them by new lines.
// A convenience wrapper to ReadLinesOffsetN(filename, 0, -1).
func ReadLines(filename string) ([]string, error) {

View File

@ -171,52 +171,6 @@ func TestRandomSleep(t *testing.T) {
assert.True(t, elapsed < time.Millisecond*150)
}
func TestDuration(t *testing.T) {
var d Duration
d.UnmarshalTOML([]byte(`"1s"`))
assert.Equal(t, time.Second, d.Duration)
d = Duration{}
d.UnmarshalTOML([]byte(`1s`))
assert.Equal(t, time.Second, d.Duration)
d = Duration{}
d.UnmarshalTOML([]byte(`'1s'`))
assert.Equal(t, time.Second, d.Duration)
d = Duration{}
d.UnmarshalTOML([]byte(`10`))
assert.Equal(t, 10*time.Second, d.Duration)
d = Duration{}
d.UnmarshalTOML([]byte(`1.5`))
assert.Equal(t, time.Second, d.Duration)
}
func TestSize(t *testing.T) {
var s Size
s.UnmarshalTOML([]byte(`"1B"`))
assert.Equal(t, int64(1), s.Size)
s = Size{}
s.UnmarshalTOML([]byte(`1`))
assert.Equal(t, int64(1), s.Size)
s = Size{}
s.UnmarshalTOML([]byte(`'1'`))
assert.Equal(t, int64(1), s.Size)
s = Size{}
s.UnmarshalTOML([]byte(`"1GB"`))
assert.Equal(t, int64(1000*1000*1000), s.Size)
s = Size{}
s.UnmarshalTOML([]byte(`"12GiB"`))
assert.Equal(t, int64(12*1024*1024*1024), s.Size)
}
func TestCompressWithGzip(t *testing.T) {
testData := "the quick brown fox jumps over the lazy dog"
inputBuffer := bytes.NewBuffer([]byte(testData))

View File

@ -1,13 +1,13 @@
package snmp
import (
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
)
type ClientConfig struct {
// Timeout to wait for a response.
Timeout internal.Duration `toml:"timeout"`
Retries int `toml:"retries"`
Timeout config.Duration `toml:"timeout"`
Retries int `toml:"retries"`
// Values: 1, 2, 3
Version uint8 `toml:"version"`

View File

@ -5,6 +5,7 @@ import (
"net/url"
"strconv"
"strings"
"time"
"github.com/gosnmp/gosnmp"
)
@ -62,7 +63,7 @@ func (gs GosnmpWrapper) Get(oids []string) (*gosnmp.SnmpPacket, error) {
func NewWrapper(s ClientConfig) (GosnmpWrapper, error) {
gs := GosnmpWrapper{&gosnmp.GoSNMP{}}
gs.Timeout = s.Timeout.Duration
gs.Timeout = time.Duration(s.Timeout)
gs.Retries = s.Retries

View File

@ -8,7 +8,7 @@ import (
"regexp"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/rotate"
"github.com/influxdata/wlog"
)
@ -33,9 +33,9 @@ type LogConfig struct {
// logger will fallback to stderr
Logfile string
// will rotate when current file at the specified time interval
RotationInterval internal.Duration
RotationInterval config.Duration
// will rotate when current file size exceeds this parameter.
RotationMaxSize internal.Size
RotationMaxSize config.Size
// maximum rotated files to keep (older ones will be deleted)
RotationMaxArchives int
}
@ -105,7 +105,7 @@ func (t *telegrafLogCreator) CreateLogger(config LogConfig) (io.Writer, error) {
case LogTargetFile:
if config.Logfile != "" {
var err error
if writer, err = rotate.NewFileWriter(config.Logfile, config.RotationInterval.Duration, config.RotationMaxSize.Size, config.RotationMaxArchives); err != nil {
if writer, err = rotate.NewFileWriter(config.Logfile, time.Duration(config.RotationInterval), int64(config.RotationMaxSize), config.RotationMaxArchives); err != nil {
log.Printf("E! Unable to open %s (%s), using stderr", config.Logfile, err)
writer = defaultWriter
}

View File

@ -9,7 +9,7 @@ import (
"path/filepath"
"testing"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -99,10 +99,10 @@ func TestWriteToTruncatedFile(t *testing.T) {
func TestWriteToFileInRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "LogRotation")
require.NoError(t, err)
config := createBasicLogConfig(filepath.Join(tempDir, "test.log"))
config.LogTarget = LogTargetFile
config.RotationMaxSize = internal.Size{Size: int64(30)}
writer := newLogWriter(config)
cfg := createBasicLogConfig(filepath.Join(tempDir, "test.log"))
cfg.LogTarget = LogTargetFile
cfg.RotationMaxSize = config.Size(30)
writer := newLogWriter(cfg)
// Close the writer here, otherwise the temp folder cannot be deleted because the current log file is in use.
closer, isCloser := writer.(io.Closer)
assert.True(t, isCloser)

View File

@ -4,7 +4,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/aggregators"
)
@ -20,7 +20,7 @@ var sampleConfig = `
`
type Final struct {
SeriesTimeout internal.Duration `toml:"series_timeout"`
SeriesTimeout config.Duration `toml:"series_timeout"`
// The last metric for all series which are active
metricCache map[uint64]telegraf.Metric
@ -28,7 +28,7 @@ type Final struct {
func NewFinal() *Final {
return &Final{
SeriesTimeout: internal.Duration{Duration: 5 * time.Minute},
SeriesTimeout: config.Duration(5 * time.Minute),
metricCache: make(map[uint64]telegraf.Metric),
}
}
@ -51,7 +51,7 @@ func (m *Final) Push(acc telegraf.Accumulator) {
acc.SetPrecision(time.Nanosecond)
for id, metric := range m.metricCache {
if time.Since(metric.Time()) > m.SeriesTimeout.Duration {
if time.Since(metric.Time()) > time.Duration(m.SeriesTimeout) {
fields := map[string]interface{}{}
for _, field := range metric.FieldList() {
fields[field.Key+"_final"] = field.Value

View File

@ -5,7 +5,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
)
@ -93,7 +93,7 @@ func TestTwoTags(t *testing.T) {
func TestLongDifference(t *testing.T) {
acc := testutil.Accumulator{}
final := NewFinal()
final.SeriesTimeout = internal.Duration{Duration: 30 * time.Second}
final.SeriesTimeout = config.Duration(30 * time.Second)
tags := map[string]string{"foo": "bar"}
now := time.Now()

View File

@ -12,19 +12,19 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type ActiveMQ struct {
Server string `toml:"server"`
Port int `toml:"port"`
URL string `toml:"url"`
Username string `toml:"username"`
Password string `toml:"password"`
Webadmin string `toml:"webadmin"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Server string `toml:"server"`
Port int `toml:"port"`
URL string `toml:"url"`
Username string `toml:"username"`
Password string `toml:"password"`
Webadmin string `toml:"webadmin"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
client *http.Client
@ -127,15 +127,15 @@ func (a *ActiveMQ) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: a.ResponseTimeout.Duration,
Timeout: time.Duration(a.ResponseTimeout),
}
return client, nil
}
func (a *ActiveMQ) Init() error {
if a.ResponseTimeout.Duration < time.Second {
a.ResponseTimeout.Duration = time.Second * 5
if a.ResponseTimeout < config.Duration(time.Second) {
a.ResponseTimeout = config.Duration(time.Second * 5)
}
var err error

View File

@ -12,6 +12,7 @@ import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/providers"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/internal/limiter"
"github.com/influxdata/telegraf/plugins/inputs"
@ -31,7 +32,7 @@ const (
## 5) RSA keypair credential
## 6) Environment variables credential
## 7) Instance metadata credential
# access_key_id = ""
# access_key_secret = ""
# access_key_sts_token = ""
@ -40,7 +41,7 @@ const (
# private_key = ""
# public_key_id = ""
# role_name = ""
# The minimum period for AliyunCMS metrics is 1 minute (60s). However not all
# metrics are made available to the 1 minute period. Some are collected at
# 3 minute, 5 minute, or larger intervals.
@ -51,22 +52,22 @@ const (
#
## Requested AliyunCMS aggregation Period (required - must be a multiple of 60s)
period = "5m"
## Collection Delay (required - must account for metrics availability via AliyunCMS API)
delay = "1m"
## Recommended: use metric 'interval' that is a multiple of 'period' to avoid
## gaps or overlap in pulled data
interval = "5m"
## Metric Statistic Project (required)
project = "acs_slb_dashboard"
## Maximum requests per second, default value is 200
ratelimit = 200
## Discovery regions set the scope for object discovery, the discovered info can be used to enrich
## the metrics with objects attributes/tags. Discovery is supported not for all projects (if not supported, then
## the metrics with objects attributes/tags. Discovery is supported not for all projects (if not supported, then
## it will be reported on the start - foo example for 'acs_cdn' project:
## 'E! [inputs.aliyuncms] Discovery tool is not activated: no discovery support for project "acs_cdn"' )
## Currently, discovery supported for the following projects:
@ -78,28 +79,28 @@ const (
## If not set, all regions would be covered, it can provide a significant load on API, so the recommendation here
## is to limit the list as much as possible. Allowed values: https://www.alibabacloud.com/help/zh/doc-detail/40654.htm
discovery_regions = ["cn-hongkong"]
## how often the discovery API call executed (default 1m)
#discovery_interval = "1m"
## Metrics to Pull (Required)
[[inputs.aliyuncms.metrics]]
## Metrics names to be requested,
## Metrics names to be requested,
## described here (per project): https://help.aliyun.com/document_detail/28619.html?spm=a2c4g.11186623.6.690.1938ad41wg8QSq
names = ["InstanceActiveConnection", "InstanceNewConnection"]
## Dimension filters for Metric (these are optional).
## This allows to get additional metric dimension. If dimension is not specified it can be returned or
## the data can be aggregated - it depends on particular metric, you can find details here: https://help.aliyun.com/document_detail/28619.html?spm=a2c4g.11186623.6.690.1938ad41wg8QSq
##
## Note, that by default dimension filter includes the list of discovered objects in scope (if discovery is enabled)
## Values specified here would be added into the list of discovered objects.
## You can specify either single dimension:
## You can specify either single dimension:
#dimensions = '{"instanceId": "p-example"}'
## Or you can specify several dimensions at once:
#dimensions = '[{"instanceId": "p-example"},{"instanceId": "q-example"}]'
## Enrichment tags, can be added from discovery (if supported)
## Notation is <measurement_tag_name>:<JMES query path (https://jmespath.org/tutorial.html)>
## To figure out which fields are available, consult the Describe<ObjectType> API per project.
@ -110,10 +111,10 @@ const (
# "cluster_owner:Tags.Tag[?TagKey=='cs.cluster.name'].TagValue | [0]"
# ]
## The following tags added by default: regionId (if discovery enabled), userId, instanceId.
## Allow metrics without discovery data, if discovery is enabled. If set to true, then metric without discovery
## data would be emitted, otherwise dropped. This cane be of help, in case debugging dimension filters, or partial coverage
## of discovery scope vs monitoring scope
## data would be emitted, otherwise dropped. This cane be of help, in case debugging dimension filters, or partial coverage
## of discovery scope vs monitoring scope
#allow_dps_without_discovery = false
`
)
@ -130,13 +131,13 @@ type (
PublicKeyID string `toml:"public_key_id"`
RoleName string `toml:"role_name"`
DiscoveryRegions []string `toml:"discovery_regions"`
DiscoveryInterval internal.Duration `toml:"discovery_interval"`
Period internal.Duration `toml:"period"`
Delay internal.Duration `toml:"delay"`
Project string `toml:"project"`
Metrics []*Metric `toml:"metrics"`
RateLimit int `toml:"ratelimit"`
DiscoveryRegions []string `toml:"discovery_regions"`
DiscoveryInterval config.Duration `toml:"discovery_interval"`
Period config.Duration `toml:"period"`
Delay config.Duration `toml:"delay"`
Project string `toml:"project"`
Metrics []*Metric `toml:"metrics"`
RateLimit int `toml:"ratelimit"`
Log telegraf.Logger `toml:"-"`
@ -238,7 +239,7 @@ func (s *AliyunCMS) Init() error {
//Init discovery...
if s.dt == nil { //Support for tests
s.dt, err = NewDiscoveryTool(s.DiscoveryRegions, s.Project, s.Log, credential, int(float32(s.RateLimit)*0.2), s.DiscoveryInterval.Duration)
s.dt, err = NewDiscoveryTool(s.DiscoveryRegions, s.Project, s.Log, credential, int(float32(s.RateLimit)*0.2), time.Duration(s.DiscoveryInterval))
if err != nil {
s.Log.Errorf("Discovery tool is not activated: %v", err)
s.dt = nil
@ -310,11 +311,11 @@ func (s *AliyunCMS) updateWindow(relativeTo time.Time) {
//opening left and closing right, and startTime cannot be equal
//to or greater than endTime.
windowEnd := relativeTo.Add(-s.Delay.Duration)
windowEnd := relativeTo.Add(-time.Duration(s.Delay))
if s.windowEnd.IsZero() {
// this is the first run, no window info, so just get a single period
s.windowStart = windowEnd.Add(-s.Period.Duration)
s.windowStart = windowEnd.Add(-time.Duration(s.Period))
} else {
// subsequent window, start where last window left off
s.windowStart = s.windowEnd
@ -326,7 +327,7 @@ func (s *AliyunCMS) updateWindow(relativeTo time.Time) {
// Gather given metric and emit error
func (s *AliyunCMS) gatherMetric(acc telegraf.Accumulator, metricName string, metric *Metric) error {
req := cms.CreateDescribeMetricListRequest()
req.Period = strconv.FormatInt(int64(s.Period.Duration.Seconds()), 10)
req.Period = strconv.FormatInt(int64(time.Duration(s.Period).Seconds()), 10)
req.MetricName = metricName
req.Length = "10000"
req.Namespace = s.Project
@ -547,7 +548,7 @@ func init() {
inputs.Add("aliyuncms", func() telegraf.Input {
return &AliyunCMS{
RateLimit: 200,
DiscoveryInterval: internal.Duration{Duration: time.Minute},
DiscoveryInterval: config.Duration(time.Minute),
dimensionKey: "instanceId",
}
})

View File

@ -13,7 +13,7 @@ import (
"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
"github.com/aliyun/alibaba-cloud-sdk-go/services/cms"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/testutil"
"github.com/pkg/errors"
@ -34,11 +34,11 @@ func (m *mockGatherAliyunCMSClient) DescribeMetricList(request *cms.DescribeMetr
resp.Period = "60"
resp.Datapoints = `
[{
"timestamp": 1490152860000,
"Maximum": 200,
"userId": "1234567898765432",
"Minimum": 100,
"instanceId": "i-abcdefgh123456",
"timestamp": 1490152860000,
"Maximum": 200,
"userId": "1234567898765432",
"Minimum": 100,
"instanceId": "i-abcdefgh123456",
"Average": 150,
"Value": 300
}]`
@ -50,11 +50,11 @@ func (m *mockGatherAliyunCMSClient) DescribeMetricList(request *cms.DescribeMetr
resp.Period = "60"
resp.Datapoints = `
[{
"timestamp": 1490152860000,
"Maximum": 200,
"userId": "1234567898765432",
"Minimum": 100,
"instanceId": "i-abcdefgh123456",
"timestamp": 1490152860000,
"Maximum": 200,
"userId": "1234567898765432",
"Minimum": 100,
"instanceId": "i-abcdefgh123456",
"Average": 150,
}]`
case "EmptyDatapoint":
@ -113,7 +113,7 @@ func getMockSdkCli(httpResp *http.Response) (mockAliyunSDKCli, error) {
func TestPluginDefaults(t *testing.T) {
require.Equal(t, &AliyunCMS{RateLimit: 200,
DiscoveryInterval: internal.Duration{Duration: time.Minute},
DiscoveryInterval: config.Duration(time.Minute),
dimensionKey: "instanceId",
}, inputs.Inputs["aliyuncms"]())
}
@ -136,7 +136,7 @@ func TestPluginInitialize(t *testing.T) {
`{
"LoadBalancers":
{
"LoadBalancer": [
"LoadBalancer": [
{"LoadBalancerId":"bla"}
]
},
@ -187,9 +187,7 @@ func TestPluginInitialize(t *testing.T) {
func TestUpdateWindow(t *testing.T) {
duration, _ := time.ParseDuration("1m")
internalDuration := internal.Duration{
Duration: duration,
}
internalDuration := config.Duration(duration)
plugin := &AliyunCMS{
Project: "acs_slb_dashboard",
@ -208,14 +206,14 @@ func TestUpdateWindow(t *testing.T) {
newStartTime := plugin.windowEnd
// initial window just has a single period
require.EqualValues(t, plugin.windowEnd, now.Add(-plugin.Delay.Duration))
require.EqualValues(t, plugin.windowStart, now.Add(-plugin.Delay.Duration).Add(-plugin.Period.Duration))
require.EqualValues(t, plugin.windowEnd, now.Add(-time.Duration(plugin.Delay)))
require.EqualValues(t, plugin.windowStart, now.Add(-time.Duration(plugin.Delay)).Add(-time.Duration(plugin.Period)))
now = time.Now()
plugin.updateWindow(now)
// subsequent window uses previous end time as start time
require.EqualValues(t, plugin.windowEnd, now.Add(-plugin.Delay.Duration))
require.EqualValues(t, plugin.windowEnd, now.Add(-time.Duration(plugin.Delay)))
require.EqualValues(t, plugin.windowStart, newStartTime)
}
@ -363,7 +361,7 @@ func TestGetDiscoveryDataAllRegions(t *testing.T) {
`{
"LoadBalancers":
{
"LoadBalancer": [
"LoadBalancer": [
{"LoadBalancerId":"bla"}
]
},

View File

@ -12,7 +12,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -21,7 +21,7 @@ type Apache struct {
Urls []string
Username string
Password string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
client *http.Client
@ -62,8 +62,8 @@ func (n *Apache) Gather(acc telegraf.Accumulator) error {
if len(n.Urls) == 0 {
n.Urls = []string{"http://localhost/server-status?auto"}
}
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
if n.client == nil {
@ -102,7 +102,7 @@ func (n *Apache) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -8,18 +8,18 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/mdlayher/apcupsd"
)
const defaultAddress = "tcp://127.0.0.1:3551"
var defaultTimeout = internal.Duration{Duration: time.Second * 5}
var defaultTimeout = config.Duration(5 * time.Second)
type ApcUpsd struct {
Servers []string
Timeout internal.Duration
Timeout config.Duration
}
func (*ApcUpsd) Description() string {
@ -51,7 +51,7 @@ func (h *ApcUpsd) Gather(acc telegraf.Accumulator) error {
addrBits.Scheme = "tcp"
}
ctx, cancel := context.WithTimeout(ctx, h.Timeout.Duration)
ctx, cancel := context.WithTimeout(ctx, time.Duration(h.Timeout))
defer cancel()
status, err := fetchStatus(ctx, addrBits)

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -43,11 +43,11 @@ var (
type Vars map[string]interface{}
type Aurora struct {
Schedulers []string `toml:"schedulers"`
Roles []string `toml:"roles"`
Timeout internal.Duration `toml:"timeout"`
Username string `toml:"username"`
Password string `toml:"password"`
Schedulers []string `toml:"schedulers"`
Roles []string `toml:"roles"`
Timeout config.Duration `toml:"timeout"`
Username string `toml:"username"`
Password string `toml:"password"`
tls.ClientConfig
client *http.Client
@ -95,7 +95,7 @@ func (a *Aurora) Gather(acc telegraf.Accumulator) error {
}
}
ctx, cancel := context.WithTimeout(context.Background(), a.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.Timeout))
defer cancel()
var wg sync.WaitGroup
@ -147,8 +147,8 @@ func (a *Aurora) initialize() error {
urls = append(urls, loc)
}
if a.Timeout.Duration < time.Second {
a.Timeout.Duration = defaultTimeout
if a.Timeout < config.Duration(time.Second) {
a.Timeout = config.Duration(defaultTimeout)
}
if len(a.Roles) == 0 {

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/choice"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -80,7 +80,7 @@ type Beat struct {
Method string `toml:"method"`
Headers map[string]string `toml:"headers"`
HostHeader string `toml:"host_header"`
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
tls.ClientConfig
client *http.Client
@ -92,7 +92,7 @@ func NewBeat() *Beat {
Includes: []string{"beat", "libbeat", "filebeat"},
Method: "GET",
Headers: make(map[string]string),
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
}
@ -133,7 +133,7 @@ func (beat *Beat) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: beat.Timeout.Duration,
Timeout: time.Duration(beat.Timeout),
}
return client, nil

View File

@ -11,8 +11,8 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -73,7 +73,7 @@ type (
Servers []string
Username string
Password string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
ConcurrentConnections int
APIPrefix string `toml:"api_prefix"`
@ -188,10 +188,8 @@ func (b *burrow) setDefaults() {
if b.ConcurrentConnections < 1 {
b.ConcurrentConnections = defaultConcurrentConnections
}
if b.ResponseTimeout.Duration < time.Second {
b.ResponseTimeout = internal.Duration{
Duration: defaultResponseTimeout,
}
if time.Duration(b.ResponseTimeout) < time.Second {
b.ResponseTimeout = config.Duration(defaultResponseTimeout)
}
}
@ -224,7 +222,7 @@ func (b *burrow) createClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: b.ResponseTimeout.Duration,
Timeout: time.Duration(b.ResponseTimeout),
}
return client, nil

View File

@ -14,6 +14,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -101,20 +102,20 @@ func init() {
ClientConfig: tls.ClientConfig{
InsecureSkipVerify: false,
},
Timeout: internal.Duration{Duration: defaultTimeout},
Timeout: config.Duration(defaultTimeout),
}
})
}
// ClickHouse Telegraf Input Plugin
type ClickHouse struct {
Username string `toml:"username"`
Password string `toml:"password"`
Servers []string `toml:"servers"`
AutoDiscovery bool `toml:"auto_discovery"`
ClusterInclude []string `toml:"cluster_include"`
ClusterExclude []string `toml:"cluster_exclude"`
Timeout internal.Duration `toml:"timeout"`
Username string `toml:"username"`
Password string `toml:"password"`
Servers []string `toml:"servers"`
AutoDiscovery bool `toml:"auto_discovery"`
ClusterInclude []string `toml:"cluster_include"`
ClusterExclude []string `toml:"cluster_exclude"`
Timeout config.Duration `toml:"timeout"`
HTTPClient http.Client
tls.ClientConfig
}
@ -132,8 +133,8 @@ func (*ClickHouse) Description() string {
// Start ClickHouse input service
func (ch *ClickHouse) Start(telegraf.Accumulator) error {
timeout := defaultTimeout
if ch.Timeout.Duration != 0 {
timeout = ch.Timeout.Duration
if time.Duration(ch.Timeout) != 0 {
timeout = time.Duration(ch.Timeout)
}
tlsCfg, err := ch.ClientConfig.TLSConfig()
if err != nil {

View File

@ -10,6 +10,7 @@ import (
"cloud.google.com/go/pubsub"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
@ -31,10 +32,10 @@ type PubSub struct {
Subscription string `toml:"subscription"`
// Subscription ReceiveSettings
MaxExtension internal.Duration `toml:"max_extension"`
MaxOutstandingMessages int `toml:"max_outstanding_messages"`
MaxOutstandingBytes int `toml:"max_outstanding_bytes"`
MaxReceiverGoRoutines int `toml:"max_receiver_go_routines"`
MaxExtension config.Duration `toml:"max_extension"`
MaxOutstandingMessages int `toml:"max_outstanding_messages"`
MaxOutstandingBytes int `toml:"max_outstanding_bytes"`
MaxReceiverGoRoutines int `toml:"max_receiver_go_routines"`
// Agent settings
MaxMessageLen int `toml:"max_message_len"`
@ -277,7 +278,7 @@ func (ps *PubSub) getGCPSubscription(subID string) (subscription, error) {
s := client.Subscription(subID)
s.ReceiveSettings = pubsub.ReceiveSettings{
NumGoroutines: ps.MaxReceiverGoRoutines,
MaxExtension: ps.MaxExtension.Duration,
MaxExtension: time.Duration(ps.MaxExtension),
MaxOutstandingMessages: ps.MaxOutstandingMessages,
MaxOutstandingBytes: ps.MaxOutstandingBytes,
}
@ -312,8 +313,8 @@ const sampleConfig = `
## Application Default Credentials, which is preferred.
# credentials_file = "path/to/my/creds.json"
## Optional. Number of seconds to wait before attempting to restart the
## PubSub subscription receiver after an unexpected error.
## Optional. Number of seconds to wait before attempting to restart the
## PubSub subscription receiver after an unexpected error.
## If the streaming pull for a PubSub Subscription fails (receiver),
## the agent attempts to restart receiving messages after this many seconds.
# retry_delay_seconds = 5
@ -362,7 +363,7 @@ const sampleConfig = `
## processed concurrently (use "max_outstanding_messages" instead).
# max_receiver_go_routines = 0
## Optional. If true, Telegraf will attempt to base64 decode the
## Optional. If true, Telegraf will attempt to base64 decode the
## PubSub message data before parsing
# base64_data = false
`

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
@ -27,9 +27,9 @@ type PubSubPush struct {
ServiceAddress string
Token string
Path string
ReadTimeout internal.Duration
WriteTimeout internal.Duration
MaxBodySize internal.Size
ReadTimeout config.Duration
WriteTimeout config.Duration
MaxBodySize config.Size
AddMeta bool
Log telegraf.Logger
@ -129,15 +129,15 @@ func (p *PubSubPush) SetParser(parser parsers.Parser) {
// Start starts the http listener service.
func (p *PubSubPush) Start(acc telegraf.Accumulator) error {
if p.MaxBodySize.Size == 0 {
p.MaxBodySize.Size = defaultMaxBodySize
if p.MaxBodySize == 0 {
p.MaxBodySize = config.Size(defaultMaxBodySize)
}
if p.ReadTimeout.Duration < time.Second {
p.ReadTimeout.Duration = time.Second * 10
if p.ReadTimeout < config.Duration(time.Second) {
p.ReadTimeout = config.Duration(time.Second * 10)
}
if p.WriteTimeout.Duration < time.Second {
p.WriteTimeout.Duration = time.Second * 10
if p.WriteTimeout < config.Duration(time.Second) {
p.WriteTimeout = config.Duration(time.Second * 10)
}
tlsConf, err := p.ServerConfig.TLSConfig()
@ -147,8 +147,8 @@ func (p *PubSubPush) Start(acc telegraf.Accumulator) error {
p.server = &http.Server{
Addr: p.ServiceAddress,
Handler: http.TimeoutHandler(p, p.WriteTimeout.Duration, "timed out processing metric"),
ReadTimeout: p.ReadTimeout.Duration,
Handler: http.TimeoutHandler(p, time.Duration(p.WriteTimeout), "timed out processing metric"),
ReadTimeout: time.Duration(p.ReadTimeout),
TLSConfig: tlsConf,
}
@ -206,7 +206,7 @@ func (p *PubSubPush) serveWrite(res http.ResponseWriter, req *http.Request) {
}
// Check that the content length is not too large for us to handle.
if req.ContentLength > p.MaxBodySize.Size {
if req.ContentLength > int64(p.MaxBodySize) {
res.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
@ -216,7 +216,7 @@ func (p *PubSubPush) serveWrite(res http.ResponseWriter, req *http.Request) {
return
}
body := http.MaxBytesReader(res, req.Body, p.MaxBodySize.Size)
body := http.MaxBytesReader(res, req.Body, int64(p.MaxBodySize))
bytes, err := ioutil.ReadAll(body)
if err != nil {
res.WriteHeader(http.StatusRequestEntityTooLarge)

View File

@ -15,7 +15,7 @@ import (
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/agent"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/models"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil"
@ -119,15 +119,13 @@ func TestServeHTTP(t *testing.T) {
rr := httptest.NewRecorder()
pubPush := &PubSubPush{
Log: testutil.Logger{},
Path: "/",
MaxBodySize: internal.Size{
Size: test.maxsize,
},
Log: testutil.Logger{},
Path: "/",
MaxBodySize: config.Size(test.maxsize),
sem: make(chan struct{}, 1),
undelivered: make(map[telegraf.TrackingID]chan bool),
mu: &sync.Mutex{},
WriteTimeout: internal.Duration{Duration: time.Second * 1},
WriteTimeout: config.Duration(time.Second * 1),
}
pubPush.ctx, pubPush.cancel = context.WithCancel(context.Background())
@ -162,7 +160,7 @@ func TestServeHTTP(t *testing.T) {
}
}(dst)
ctx, cancel := context.WithTimeout(req.Context(), pubPush.WriteTimeout.Duration)
ctx, cancel := context.WithTimeout(req.Context(), time.Duration(pubPush.WriteTimeout))
req = req.WithContext(ctx)
pubPush.ServeHTTP(rr, req)

View File

@ -11,8 +11,8 @@ import (
jwt "github.com/dgrijalva/jwt-go/v4"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -56,7 +56,7 @@ type DCOS struct {
AppExclude []string
MaxConnections int
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
client Client
@ -359,7 +359,7 @@ func (d *DCOS) createClient() (Client, error) {
client := NewClusterClient(
url,
d.ResponseTimeout.Duration,
time.Duration(d.ResponseTimeout),
d.MaxConnections,
tlsCfg,
)
@ -421,10 +421,8 @@ func (d *DCOS) createFilters() error {
func init() {
inputs.Add("dcos", func() telegraf.Input {
return &DCOS{
MaxConnections: defaultMaxConnections,
ResponseTimeout: internal.Duration{
Duration: defaultResponseTimeout,
},
MaxConnections: defaultMaxConnections,
ResponseTimeout: config.Duration(defaultResponseTimeout),
}
})
}

View File

@ -16,8 +16,8 @@ import (
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/swarm"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/internal/choice"
"github.com/influxdata/telegraf/internal/docker"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
@ -31,7 +31,7 @@ type Docker struct {
GatherServices bool `toml:"gather_services"`
Timeout internal.Duration
Timeout config.Duration
PerDevice bool `toml:"perdevice"`
PerDeviceInclude []string `toml:"perdevice_include"`
Total bool `toml:"total"`
@ -259,7 +259,7 @@ func (d *Docker) Gather(acc telegraf.Accumulator) error {
opts := types.ContainerListOptions{
Filters: filterArgs,
}
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Timeout))
defer cancel()
containers, err := d.client.ContainerList(ctx, opts)
@ -287,7 +287,7 @@ func (d *Docker) Gather(acc telegraf.Accumulator) error {
}
func (d *Docker) gatherSwarmInfo(acc telegraf.Accumulator) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Timeout))
defer cancel()
services, err := d.client.ServiceList(ctx, types.ServiceListOptions{})
@ -364,7 +364,7 @@ func (d *Docker) gatherInfo(acc telegraf.Accumulator) error {
now := time.Now()
// Get info from docker daemon
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Timeout))
defer cancel()
info, err := d.client.Info(ctx)
@ -524,7 +524,7 @@ func (d *Docker) gatherContainer(
tags["source"] = hostnameFromID(container.ID)
}
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Timeout))
defer cancel()
r, err := d.client.ContainerStats(ctx, container.ID, false)
@ -562,7 +562,7 @@ func (d *Docker) gatherContainerInspect(
daemonOSType string,
v *types.StatsJSON,
) error {
ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Timeout))
defer cancel()
info, err := d.client.ContainerInspect(ctx, container.ID)
@ -1010,7 +1010,7 @@ func init() {
PerDevice: true,
PerDeviceInclude: []string{"cpu"},
TotalInclude: []string{"cpu", "blkio", "network"},
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
Endpoint: defaultEndpoint,
newEnvClient: NewEnvClient,
newClient: NewClient,

View File

@ -16,8 +16,8 @@ import (
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/pkg/stdcopy"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/internal/docker"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -73,16 +73,16 @@ var (
)
type DockerLogs struct {
Endpoint string `toml:"endpoint"`
FromBeginning bool `toml:"from_beginning"`
Timeout internal.Duration `toml:"timeout"`
LabelInclude []string `toml:"docker_label_include"`
LabelExclude []string `toml:"docker_label_exclude"`
ContainerInclude []string `toml:"container_name_include"`
ContainerExclude []string `toml:"container_name_exclude"`
ContainerStateInclude []string `toml:"container_state_include"`
ContainerStateExclude []string `toml:"container_state_exclude"`
IncludeSourceTag bool `toml:"source_tag"`
Endpoint string `toml:"endpoint"`
FromBeginning bool `toml:"from_beginning"`
Timeout config.Duration `toml:"timeout"`
LabelInclude []string `toml:"docker_label_include"`
LabelExclude []string `toml:"docker_label_exclude"`
ContainerInclude []string `toml:"container_name_include"`
ContainerExclude []string `toml:"container_name_exclude"`
ContainerStateInclude []string `toml:"container_state_include"`
ContainerStateExclude []string `toml:"container_state_exclude"`
IncludeSourceTag bool `toml:"source_tag"`
tlsint.ClientConfig
@ -199,7 +199,7 @@ func (d *DockerLogs) Gather(acc telegraf.Accumulator) error {
ctx := context.Background()
acc.SetPrecision(time.Nanosecond)
ctx, cancel := context.WithTimeout(ctx, d.Timeout.Duration)
ctx, cancel := context.WithTimeout(ctx, time.Duration(d.Timeout))
defer cancel()
containers, err := d.client.ContainerList(ctx, d.opts)
if err != nil {
@ -235,7 +235,7 @@ func (d *DockerLogs) Gather(acc telegraf.Accumulator) error {
}
func (d *DockerLogs) hasTTY(ctx context.Context, container types.Container) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, d.Timeout.Duration)
ctx, cancel := context.WithTimeout(ctx, time.Duration(d.Timeout))
defer cancel()
c, err := d.client.ContainerInspect(ctx, container.ID)
if err != nil {
@ -450,7 +450,7 @@ func (d *DockerLogs) createContainerStateFilters() error {
func init() {
inputs.Add("docker_log", func() telegraf.Input {
return &DockerLogs{
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
Endpoint: defaultEndpoint,
newEnvClient: NewEnvClient,
newClient: NewClient,

View File

@ -12,7 +12,7 @@ import (
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/pkg/stdcopy"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
@ -165,7 +165,7 @@ func Test(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
var acc testutil.Accumulator
plugin := &DockerLogs{
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
newClient: func(string, *tls.Config) (Client, error) { return tt.client, nil },
containerList: make(map[string]context.CancelFunc),
IncludeSourceTag: true,

View File

@ -6,15 +6,15 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Ecs config object
type Ecs struct {
EndpointURL string `toml:"endpoint_url"`
Timeout internal.Duration
Timeout config.Duration
ContainerNameInclude []string `toml:"container_name_include"`
ContainerNameExclude []string `toml:"container_name_exclude"`
@ -114,7 +114,7 @@ func initSetup(ecs *Ecs) error {
if ecs.client == nil {
resolveEndpoint(ecs)
c, err := ecs.newClient(ecs.Timeout.Duration, ecs.EndpointURL, ecs.metadataVersion)
c, err := ecs.newClient(time.Duration(ecs.Timeout), ecs.EndpointURL, ecs.metadataVersion)
if err != nil {
return err
}
@ -262,7 +262,7 @@ func init() {
inputs.Add("ecs", func() telegraf.Input {
return &Ecs{
EndpointURL: "",
Timeout: internal.Duration{Duration: 5 * time.Second},
Timeout: config.Duration(5 * time.Second),
newClient: NewClient,
filtersCreated: false,
}

View File

@ -12,8 +12,8 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
jsonparser "github.com/influxdata/telegraf/plugins/parsers/json"
@ -147,19 +147,19 @@ const sampleConfig = `
// Elasticsearch is a plugin to read stats from one or many Elasticsearch
// servers.
type Elasticsearch struct {
Local bool `toml:"local"`
Servers []string `toml:"servers"`
HTTPTimeout internal.Duration `toml:"http_timeout"`
ClusterHealth bool `toml:"cluster_health"`
ClusterHealthLevel string `toml:"cluster_health_level"`
ClusterStats bool `toml:"cluster_stats"`
ClusterStatsOnlyFromMaster bool `toml:"cluster_stats_only_from_master"`
IndicesInclude []string `toml:"indices_include"`
IndicesLevel string `toml:"indices_level"`
NodeStats []string `toml:"node_stats"`
Username string `toml:"username"`
Password string `toml:"password"`
NumMostRecentIndices int `toml:"num_most_recent_indices"`
Local bool `toml:"local"`
Servers []string `toml:"servers"`
HTTPTimeout config.Duration `toml:"http_timeout"`
ClusterHealth bool `toml:"cluster_health"`
ClusterHealthLevel string `toml:"cluster_health_level"`
ClusterStats bool `toml:"cluster_stats"`
ClusterStatsOnlyFromMaster bool `toml:"cluster_stats_only_from_master"`
IndicesInclude []string `toml:"indices_include"`
IndicesLevel string `toml:"indices_level"`
NodeStats []string `toml:"node_stats"`
Username string `toml:"username"`
Password string `toml:"password"`
NumMostRecentIndices int `toml:"num_most_recent_indices"`
tls.ClientConfig
@ -180,7 +180,7 @@ func (i serverInfo) isMaster() bool {
// NewElasticsearch return a new instance of Elasticsearch
func NewElasticsearch() *Elasticsearch {
return &Elasticsearch{
HTTPTimeout: internal.Duration{Duration: time.Second * 5},
HTTPTimeout: config.Duration(time.Second * 5),
ClusterStatsOnlyFromMaster: true,
ClusterHealthLevel: "indices",
}
@ -340,12 +340,12 @@ func (e *Elasticsearch) createHTTPClient() (*http.Client, error) {
return nil, err
}
tr := &http.Transport{
ResponseHeaderTimeout: e.HTTPTimeout.Duration,
ResponseHeaderTimeout: time.Duration(e.HTTPTimeout),
TLSClientConfig: tlsCfg,
}
client := &http.Client{
Transport: tr,
Timeout: e.HTTPTimeout.Duration,
Timeout: time.Duration(e.HTTPTimeout),
}
return client, nil

View File

@ -12,6 +12,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
@ -43,9 +44,9 @@ const sampleConfig = `
const MaxStderrBytes int = 512
type Exec struct {
Commands []string `toml:"commands"`
Command string `toml:"command"`
Timeout internal.Duration `toml:"timeout"`
Commands []string `toml:"commands"`
Command string `toml:"command"`
Timeout config.Duration `toml:"timeout"`
parser parsers.Parser
@ -56,7 +57,7 @@ type Exec struct {
func NewExec() *Exec {
return &Exec{
runner: CommandRunner{},
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
}
@ -138,7 +139,7 @@ func (e *Exec) ProcessCommand(command string, acc telegraf.Accumulator, wg *sync
defer wg.Done()
_, isNagios := e.parser.(*nagios.NagiosParser)
out, errbuf, runErr := e.runner.Run(command, e.Timeout.Duration)
out, errbuf, runErr := e.runner.Run(command, time.Duration(e.Timeout))
if !isNagios && runErr != nil {
err := fmt.Errorf("exec: %s for command '%s': %s", runErr, command, string(errbuf))
acc.AddError(err)

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -37,7 +37,7 @@ type Fibaro struct {
Username string `toml:"username"`
Password string `toml:"password"`
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
client *http.Client
}
@ -126,7 +126,7 @@ func (f *Fibaro) Gather(acc telegraf.Accumulator) error {
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
Timeout: f.Timeout.Duration,
Timeout: time.Duration(f.Timeout),
}
}
@ -221,7 +221,7 @@ func (f *Fibaro) Gather(acc telegraf.Accumulator) error {
func init() {
inputs.Add("fibaro", func() telegraf.Input {
return &Fibaro{
Timeout: internal.Duration{Duration: defaultTimeout},
Timeout: config.Duration(defaultTimeout),
}
})
}

View File

@ -6,7 +6,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/globpath"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/karrick/godirwalk"
@ -57,8 +57,8 @@ type FileCount struct {
Recursive bool
RegularOnly bool
FollowSymlinks bool
Size internal.Size
MTime internal.Duration `toml:"mtime"`
Size config.Size
MTime config.Duration `toml:"mtime"`
fileFilters []fileFilterFunc
globPaths []globpath.GlobPath
Fs fileSystem
@ -108,7 +108,7 @@ func (fc *FileCount) regularOnlyFilter() fileFilterFunc {
}
func (fc *FileCount) sizeFilter() fileFilterFunc {
if fc.Size.Size == 0 {
if fc.Size == 0 {
return nil
}
@ -116,22 +116,22 @@ func (fc *FileCount) sizeFilter() fileFilterFunc {
if !f.Mode().IsRegular() {
return false, nil
}
if fc.Size.Size < 0 {
return f.Size() < -fc.Size.Size, nil
if fc.Size < 0 {
return f.Size() < -int64(fc.Size), nil
}
return f.Size() >= fc.Size.Size, nil
return f.Size() >= int64(fc.Size), nil
}
}
func (fc *FileCount) mtimeFilter() fileFilterFunc {
if fc.MTime.Duration == 0 {
if time.Duration(fc.MTime) == 0 {
return nil
}
return func(f os.FileInfo) (bool, error) {
age := absDuration(fc.MTime.Duration)
age := absDuration(time.Duration(fc.MTime))
mtime := time.Now().Add(-age)
if fc.MTime.Duration < 0 {
if time.Duration(fc.MTime) < 0 {
return f.ModTime().After(mtime), nil
}
return f.ModTime().Before(mtime), nil
@ -302,8 +302,8 @@ func NewFileCount() *FileCount {
Recursive: true,
RegularOnly: true,
FollowSymlinks: false,
Size: internal.Size{Size: 0},
MTime: internal.Duration{Duration: 0},
Size: config.Size(0),
MTime: config.Duration(0),
fileFilters: nil,
Fs: osFS{},
}

View File

@ -14,7 +14,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
@ -95,12 +95,12 @@ func TestRegularOnlyFilter(t *testing.T) {
func TestSizeFilter(t *testing.T) {
fc := getNoFilterFileCount()
fc.Size = internal.Size{Size: -100}
fc.Size = config.Size(-100)
matches := []string{"foo", "bar", "baz",
"subdir/quux", "subdir/quuz"}
fileCountEquals(t, fc, len(matches), 0)
fc.Size = internal.Size{Size: 100}
fc.Size = config.Size(100)
matches = []string{"qux", "subdir/nested2//qux"}
fileCountEquals(t, fc, len(matches), 800)
@ -111,14 +111,14 @@ func TestMTimeFilter(t *testing.T) {
fileAge := time.Since(mtime) - (60 * time.Second)
fc := getNoFilterFileCount()
fc.MTime = internal.Duration{Duration: -fileAge}
fc.MTime = config.Duration(-fileAge)
matches := []string{"foo", "bar", "qux",
"subdir/", "subdir/quux", "subdir/quuz",
"subdir/nested2", "subdir/nested2/qux"}
fileCountEquals(t, fc, len(matches), 5096)
fc.MTime = internal.Duration{Duration: fileAge}
fc.MTime = config.Duration(fileAge)
matches = []string{"baz"}
fileCountEquals(t, fc, len(matches), 0)
}
@ -175,8 +175,8 @@ func getNoFilterFileCount() FileCount {
Name: "*",
Recursive: true,
RegularOnly: false,
Size: internal.Size{Size: 0},
MTime: internal.Duration{Duration: 0},
Size: config.Size(0),
MTime: config.Duration(0),
fileFilters: nil,
Fs: getFakeFileSystem(getTestdataDir()),
}

View File

@ -8,15 +8,15 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Fireboard gathers statistics from the fireboard.io servers
type Fireboard struct {
AuthToken string `toml:"auth_token"`
URL string `toml:"url"`
HTTPTimeout internal.Duration `toml:"http_timeout"`
AuthToken string `toml:"auth_token"`
URL string `toml:"url"`
HTTPTimeout config.Duration `toml:"http_timeout"`
client *http.Client
}
@ -76,11 +76,11 @@ func (r *Fireboard) Init() error {
r.URL = "https://fireboard.io/api/v1/devices.json"
}
// Have a default timeout of 4s
if r.HTTPTimeout.Duration == 0 {
r.HTTPTimeout.Duration = time.Second * 4
if r.HTTPTimeout == 0 {
r.HTTPTimeout = config.Duration(time.Second * 4)
}
r.client.Timeout = r.HTTPTimeout.Duration
r.client.Timeout = time.Duration(r.HTTPTimeout)
return nil
}

View File

@ -10,7 +10,7 @@ import (
"github.com/google/go-github/v32/github"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/selfstat"
"golang.org/x/oauth2"
@ -18,11 +18,11 @@ import (
// GitHub - plugin main structure
type GitHub struct {
Repositories []string `toml:"repositories"`
AccessToken string `toml:"access_token"`
AdditionalFields []string `toml:"additional_fields"`
EnterpriseBaseURL string `toml:"enterprise_base_url"`
HTTPTimeout internal.Duration `toml:"http_timeout"`
Repositories []string `toml:"repositories"`
AccessToken string `toml:"access_token"`
AdditionalFields []string `toml:"additional_fields"`
EnterpriseBaseURL string `toml:"enterprise_base_url"`
HTTPTimeout config.Duration `toml:"http_timeout"`
githubClient *github.Client
obfuscatedToken string
@ -73,7 +73,7 @@ func (g *GitHub) createGitHubClient(ctx context.Context) (*github.Client, error)
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
Timeout: g.HTTPTimeout.Duration,
Timeout: time.Duration(g.HTTPTimeout),
}
g.obfuscatedToken = "Unauthenticated"
@ -249,7 +249,7 @@ func (g *GitHub) getPullRequestFields(ctx context.Context, owner, repo string) (
func init() {
inputs.Add("github", func() telegraf.Input {
return &GitHub{
HTTPTimeout: internal.Duration{Duration: time.Second * 5},
HTTPTimeout: config.Duration(time.Second * 5),
}
})
}

View File

@ -15,7 +15,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric"
internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -44,7 +44,7 @@ type GNMI struct {
Password string
// Redial
Redial internal.Duration
Redial config.Duration
// GRPC TLS settings
EnableTLS bool `toml:"enable_tls"`
@ -66,12 +66,12 @@ type Subscription struct {
Path string
// Subscription mode and interval
SubscriptionMode string `toml:"subscription_mode"`
SampleInterval internal.Duration `toml:"sample_interval"`
SubscriptionMode string `toml:"subscription_mode"`
SampleInterval config.Duration `toml:"sample_interval"`
// Duplicate suppression
SuppressRedundant bool `toml:"suppress_redundant"`
HeartbeatInterval internal.Duration `toml:"heartbeat_interval"`
SuppressRedundant bool `toml:"suppress_redundant"`
HeartbeatInterval config.Duration `toml:"heartbeat_interval"`
}
// Start the http listener service
@ -86,7 +86,7 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
// Validate configuration
if request, err = c.newSubscribeRequest(); err != nil {
return err
} else if c.Redial.Duration.Nanoseconds() <= 0 {
} else if time.Duration(c.Redial).Nanoseconds() <= 0 {
return fmt.Errorf("redial duration must be positive")
}
@ -143,7 +143,7 @@ func (c *GNMI) Start(acc telegraf.Accumulator) error {
select {
case <-ctx.Done():
case <-time.After(c.Redial.Duration):
case <-time.After(time.Duration(c.Redial)):
}
}
}(addr)
@ -167,9 +167,9 @@ func (c *GNMI) newSubscribeRequest() (*gnmi.SubscribeRequest, error) {
subscriptions[i] = &gnmi.Subscription{
Path: gnmiPath,
Mode: gnmi.SubscriptionMode(mode),
SampleInterval: uint64(subscription.SampleInterval.Duration.Nanoseconds()),
SampleInterval: uint64(time.Duration(subscription.SampleInterval).Nanoseconds()),
SuppressRedundant: subscription.SuppressRedundant,
HeartbeatInterval: uint64(subscription.HeartbeatInterval.Duration.Nanoseconds()),
HeartbeatInterval: uint64(time.Duration(subscription.HeartbeatInterval).Nanoseconds()),
}
}
@ -555,7 +555,7 @@ func (c *GNMI) Gather(_ telegraf.Accumulator) error {
func New() telegraf.Input {
return &GNMI{
Encoding: "proto",
Redial: internal.Duration{Duration: 10 * time.Second},
Redial: config.Duration(10 * time.Second),
}
}

View File

@ -10,7 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/openconfig/gnmi/proto/gnmi"
"github.com/stretchr/testify/assert"
@ -77,7 +77,7 @@ func TestWaitError(t *testing.T) {
Log: testutil.Logger{},
Addresses: []string{listener.Addr().String()},
Encoding: "proto",
Redial: internal.Duration{Duration: 1 * time.Second},
Redial: config.Duration(1 * time.Second),
}
var acc testutil.Accumulator
@ -135,7 +135,7 @@ func TestUsernamePassword(t *testing.T) {
Username: "theusername",
Password: "thepassword",
Encoding: "proto",
Redial: internal.Duration{Duration: 1 * time.Second},
Redial: config.Duration(1 * time.Second),
}
var acc testutil.Accumulator
@ -218,7 +218,7 @@ func TestNotification(t *testing.T) {
plugin: &GNMI{
Log: testutil.Logger{},
Encoding: "proto",
Redial: internal.Duration{Duration: 1 * time.Second},
Redial: config.Duration(1 * time.Second),
Subscriptions: []Subscription{
{
Name: "alias",
@ -302,7 +302,7 @@ func TestNotification(t *testing.T) {
plugin: &GNMI{
Log: testutil.Logger{},
Encoding: "proto",
Redial: internal.Duration{Duration: 1 * time.Second},
Redial: config.Duration(1 * time.Second),
Subscriptions: []Subscription{
{
Name: "PHY_COUNTERS",
@ -435,7 +435,7 @@ func TestRedial(t *testing.T) {
Log: testutil.Logger{},
Addresses: []string{listener.Addr().String()},
Encoding: "proto",
Redial: internal.Duration{Duration: 10 * time.Millisecond},
Redial: config.Duration(10 * time.Millisecond),
}
grpcServer := grpc.NewServer()

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/proxy"
"github.com/influxdata/telegraf/plugins/common/tls"
@ -37,7 +38,7 @@ type HTTP struct {
SuccessStatusCodes []int `toml:"success_status_codes"`
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
client *http.Client
@ -124,7 +125,7 @@ func (h *HTTP) Init() error {
h.client = &http.Client{
Transport: transport,
Timeout: h.Timeout.Duration,
Timeout: time.Duration(h.Timeout),
}
// Set default as [200]
@ -261,7 +262,7 @@ func makeRequestBodyReader(contentEncoding, body string) (io.ReadCloser, error)
func init() {
inputs.Add("http", func() telegraf.Input {
return &HTTP{
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
Method: "GET",
}
})

View File

@ -14,7 +14,7 @@ import (
"github.com/golang/snappy"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
@ -39,9 +39,9 @@ type HTTPListenerV2 struct {
Path string `toml:"path"`
Methods []string `toml:"methods"`
DataSource string `toml:"data_source"`
ReadTimeout internal.Duration `toml:"read_timeout"`
WriteTimeout internal.Duration `toml:"write_timeout"`
MaxBodySize internal.Size `toml:"max_body_size"`
ReadTimeout config.Duration `toml:"read_timeout"`
WriteTimeout config.Duration `toml:"write_timeout"`
MaxBodySize config.Size `toml:"max_body_size"`
Port int `toml:"port"`
BasicUsername string `toml:"basic_username"`
BasicPassword string `toml:"basic_password"`
@ -125,15 +125,15 @@ func (h *HTTPListenerV2) SetParser(parser parsers.Parser) {
// Start starts the http listener service.
func (h *HTTPListenerV2) Start(acc telegraf.Accumulator) error {
if h.MaxBodySize.Size == 0 {
h.MaxBodySize.Size = defaultMaxBodySize
if h.MaxBodySize == 0 {
h.MaxBodySize = config.Size(defaultMaxBodySize)
}
if h.ReadTimeout.Duration < time.Second {
h.ReadTimeout.Duration = time.Second * 10
if h.ReadTimeout < config.Duration(time.Second) {
h.ReadTimeout = config.Duration(time.Second * 10)
}
if h.WriteTimeout.Duration < time.Second {
h.WriteTimeout.Duration = time.Second * 10
if h.WriteTimeout < config.Duration(time.Second) {
h.WriteTimeout = config.Duration(time.Second * 10)
}
h.acc = acc
@ -146,8 +146,8 @@ func (h *HTTPListenerV2) Start(acc telegraf.Accumulator) error {
server := &http.Server{
Addr: h.ServiceAddress,
Handler: h,
ReadTimeout: h.ReadTimeout.Duration,
WriteTimeout: h.WriteTimeout.Duration,
ReadTimeout: time.Duration(h.ReadTimeout),
WriteTimeout: time.Duration(h.WriteTimeout),
TLSConfig: tlsConf,
}
@ -198,7 +198,7 @@ func (h *HTTPListenerV2) ServeHTTP(res http.ResponseWriter, req *http.Request) {
func (h *HTTPListenerV2) serveWrite(res http.ResponseWriter, req *http.Request) {
// Check that the content length is not too large for us to handle.
if req.ContentLength > h.MaxBodySize.Size {
if req.ContentLength > int64(h.MaxBodySize) {
if err := tooLarge(res); err != nil {
h.Log.Debugf("error in too-large: %v", err)
}
@ -271,7 +271,7 @@ func (h *HTTPListenerV2) collectBody(res http.ResponseWriter, req *http.Request)
return nil, false
}
defer r.Close()
maxReader := http.MaxBytesReader(res, r, h.MaxBodySize.Size)
maxReader := http.MaxBytesReader(res, r, int64(h.MaxBodySize))
bytes, err := ioutil.ReadAll(maxReader)
if err != nil {
if err := tooLarge(res); err != nil {

View File

@ -14,7 +14,7 @@ import (
"time"
"github.com/golang/snappy"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/parsers"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
@ -53,7 +53,7 @@ func newTestHTTPListenerV2() *HTTPListenerV2 {
Methods: []string{"POST"},
Parser: parser,
TimeFunc: time.Now,
MaxBodySize: internal.Size{Size: 70000},
MaxBodySize: config.Size(70000),
DataSource: "body",
}
return listener
@ -114,7 +114,7 @@ func TestInvalidListenerConfig(t *testing.T) {
Methods: []string{"POST"},
Parser: parser,
TimeFunc: time.Now,
MaxBodySize: internal.Size{Size: 70000},
MaxBodySize: config.Size(70000),
DataSource: "body",
}
@ -260,7 +260,7 @@ func TestWriteHTTPExactMaxBodySize(t *testing.T) {
Path: "/write",
Methods: []string{"POST"},
Parser: parser,
MaxBodySize: internal.Size{Size: int64(len(hugeMetric))},
MaxBodySize: config.Size(len(hugeMetric)),
TimeFunc: time.Now,
}
@ -283,7 +283,7 @@ func TestWriteHTTPVerySmallMaxBody(t *testing.T) {
Path: "/write",
Methods: []string{"POST"},
Parser: parser,
MaxBodySize: internal.Size{Size: 4096},
MaxBodySize: config.Size(4096),
TimeFunc: time.Now,
}

View File

@ -15,7 +15,7 @@ import (
"unicode/utf8"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -33,14 +33,14 @@ type HTTPResponse struct {
HTTPProxy string `toml:"http_proxy"`
Body string
Method string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
HTTPHeaderTags map[string]string `toml:"http_header_tags"`
Headers map[string]string
FollowRedirects bool
// Absolute path to file with Bearer token
BearerToken string `toml:"bearer_token"`
ResponseBodyField string `toml:"response_body_field"`
ResponseBodyMaxSize internal.Size `toml:"response_body_max_size"`
BearerToken string `toml:"bearer_token"`
ResponseBodyField string `toml:"response_body_field"`
ResponseBodyMaxSize config.Size `toml:"response_body_max_size"`
ResponseStringMatch string
ResponseStatusCode int
Interface string
@ -185,7 +185,7 @@ func (h *HTTPResponse) createHTTPClient() (*http.Client, error) {
DisableKeepAlives: true,
TLSClientConfig: tlsCfg,
},
Timeout: h.ResponseTimeout.Duration,
Timeout: time.Duration(h.ResponseTimeout),
}
if !h.FollowRedirects {
@ -336,12 +336,12 @@ func (h *HTTPResponse) httpGather(u string) (map[string]interface{}, map[string]
tags["status_code"] = strconv.Itoa(resp.StatusCode)
fields["http_response_code"] = resp.StatusCode
if h.ResponseBodyMaxSize.Size == 0 {
h.ResponseBodyMaxSize.Size = defaultResponseBodyMaxSize
if h.ResponseBodyMaxSize == 0 {
h.ResponseBodyMaxSize = config.Size(defaultResponseBodyMaxSize)
}
bodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, h.ResponseBodyMaxSize.Size+1))
bodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, int64(h.ResponseBodyMaxSize)+1))
// Check first if the response body size exceeds the limit.
if err == nil && int64(len(bodyBytes)) > h.ResponseBodyMaxSize.Size {
if err == nil && int64(len(bodyBytes)) > int64(h.ResponseBodyMaxSize) {
h.setBodyReadError("The body of the HTTP Response is too large", bodyBytes, fields, tags)
return fields, tags, nil
} else if err != nil {
@ -413,8 +413,8 @@ func (h *HTTPResponse) Gather(acc telegraf.Accumulator) error {
}
// Set default values
if h.ResponseTimeout.Duration < time.Second {
h.ResponseTimeout.Duration = time.Second * 5
if h.ResponseTimeout < config.Duration(time.Second) {
h.ResponseTimeout = config.Duration(time.Second * 5)
}
// Check send and expected string
if h.Method == "" {

View File

@ -16,7 +16,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
@ -177,7 +177,7 @@ func TestHeaders(t *testing.T) {
Log: testutil.Logger{},
URLs: []string{ts.URL},
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 2},
ResponseTimeout: config.Duration(time.Second * 2),
Headers: map[string]string{
"Content-Type": "application/json",
"Host": "Hello",
@ -214,7 +214,7 @@ func TestFields(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -252,7 +252,7 @@ func TestResponseBodyField(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -287,7 +287,7 @@ func TestResponseBodyField(t *testing.T) {
URLs: []string{ts.URL + "/invalidUTF8"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -321,11 +321,11 @@ func TestResponseBodyMaxSize(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
ResponseBodyMaxSize: internal.Size{Size: 5},
ResponseBodyMaxSize: config.Size(5),
FollowRedirects: true,
}
@ -355,7 +355,7 @@ func TestHTTPHeaderTags(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
HTTPHeaderTags: map[string]string{"Server": "my_server", "Content-Type": "content_type"},
Headers: map[string]string{
"Content-Type": "application/json",
@ -390,7 +390,7 @@ func TestHTTPHeaderTags(t *testing.T) {
URLs: []string{ts.URL + "/noheader"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
HTTPHeaderTags: map[string]string{"Server": "my_server", "Content-Type": "content_type"},
Headers: map[string]string{
"Content-Type": "application/json",
@ -416,7 +416,7 @@ func TestHTTPHeaderTags(t *testing.T) {
URLs: []string{"https:/nonexistent.nonexistent"}, // Any non-routable IP works here
Body: "",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 5},
ResponseTimeout: config.Duration(time.Second * 5),
HTTPHeaderTags: map[string]string{"Server": "my_server", "Content-Type": "content_type"},
FollowRedirects: false,
}
@ -472,7 +472,7 @@ func TestInterface(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -511,7 +511,7 @@ func TestRedirects(t *testing.T) {
URLs: []string{ts.URL + "/redirect"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -542,7 +542,7 @@ func TestRedirects(t *testing.T) {
URLs: []string{ts.URL + "/badredirect"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -579,7 +579,7 @@ func TestMethod(t *testing.T) {
URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}",
Method: "POST",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -610,7 +610,7 @@ func TestMethod(t *testing.T) {
URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -642,7 +642,7 @@ func TestMethod(t *testing.T) {
URLs: []string{ts.URL + "/mustbepostmethod"},
Body: "{ 'test': 'data'}",
Method: "head",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -679,7 +679,7 @@ func TestBody(t *testing.T) {
URLs: []string{ts.URL + "/musthaveabody"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -709,7 +709,7 @@ func TestBody(t *testing.T) {
Log: testutil.Logger{},
URLs: []string{ts.URL + "/musthaveabody"},
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -745,7 +745,7 @@ func TestStringMatch(t *testing.T) {
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseStringMatch: "hit the good page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -783,7 +783,7 @@ func TestStringMatchJson(t *testing.T) {
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseStringMatch: "\"service_status\": \"up\"",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -821,7 +821,7 @@ func TestStringMatchFail(t *testing.T) {
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseStringMatch: "hit the bad page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -863,7 +863,7 @@ func TestTimeout(t *testing.T) {
URLs: []string{ts.URL + "/twosecondnap"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second},
ResponseTimeout: config.Duration(time.Second),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -898,7 +898,7 @@ func TestBadRegex(t *testing.T) {
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseStringMatch: "bad regex:[[",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -930,7 +930,7 @@ func TestNetworkErrors(t *testing.T) {
URLs: []string{"https://nonexistent.nonexistent"}, // Any non-resolvable URL works here
Body: "",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
FollowRedirects: false,
client: &fakeClient{err: &url.Error{Err: &net.OpError{Err: &net.DNSError{Err: "DNS error"}}}},
}
@ -958,7 +958,7 @@ func TestNetworkErrors(t *testing.T) {
URLs: []string{"https:/nonexistent.nonexistent"}, // Any non-routable IP works here
Body: "",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 5},
ResponseTimeout: config.Duration(time.Second * 5),
FollowRedirects: false,
}
@ -990,7 +990,7 @@ func TestContentLength(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -1021,7 +1021,7 @@ func TestContentLength(t *testing.T) {
URLs: []string{ts.URL + "/musthaveabody"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Headers: map[string]string{
"Content-Type": "application/json",
},
@ -1109,7 +1109,7 @@ func TestBasicAuth(t *testing.T) {
URLs: []string{ts.URL + "/good"},
Body: "{ 'test': 'data'}",
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
Username: "me",
Password: "mypassword",
Headers: map[string]string{
@ -1147,7 +1147,7 @@ func TestStatusCodeMatchFail(t *testing.T) {
Log: testutil.Logger{},
URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusOK,
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
}
var acc testutil.Accumulator
@ -1180,7 +1180,7 @@ func TestStatusCodeMatch(t *testing.T) {
Log: testutil.Logger{},
URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusNoContent,
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
}
var acc testutil.Accumulator
@ -1214,7 +1214,7 @@ func TestStatusCodeAndStringMatch(t *testing.T) {
URLs: []string{ts.URL + "/good"},
ResponseStatusCode: http.StatusOK,
ResponseStringMatch: "hit the good page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
}
var acc testutil.Accumulator
@ -1249,7 +1249,7 @@ func TestStatusCodeAndStringMatchFail(t *testing.T) {
URLs: []string{ts.URL + "/nocontent"},
ResponseStatusCode: http.StatusOK,
ResponseStringMatch: "hit the good page",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
}
var acc testutil.Accumulator
@ -1285,7 +1285,7 @@ func TestSNI(t *testing.T) {
Log: testutil.Logger{},
URLs: []string{ts.URL + "/good"},
Method: "GET",
ResponseTimeout: internal.Duration{Duration: time.Second * 20},
ResponseTimeout: config.Duration(time.Second * 20),
ClientConfig: tls.ClientConfig{
InsecureSkipVerify: true,
ServerName: "super-special-hostname.example.com",

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/parsers"
@ -27,7 +27,7 @@ type HTTPJSON struct {
Servers []string
Method string
TagKeys []string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
Parameters map[string]string
Headers map[string]string
tls.ClientConfig
@ -131,12 +131,12 @@ func (h *HTTPJSON) Gather(acc telegraf.Accumulator) error {
return err
}
tr := &http.Transport{
ResponseHeaderTimeout: h.ResponseTimeout.Duration,
ResponseHeaderTimeout: time.Duration(h.ResponseTimeout),
TLSClientConfig: tlsCfg,
}
client := &http.Client{
Transport: tr,
Timeout: h.ResponseTimeout.Duration,
Timeout: time.Duration(h.ResponseTimeout),
}
h.client.SetHTTPClient(client)
}
@ -286,10 +286,8 @@ func (h *HTTPJSON) sendRequest(serverURL string) (string, float64, error) {
func init() {
inputs.Add("httpjson", func() telegraf.Input {
return &HTTPJSON{
client: &RealHTTPClient{},
ResponseTimeout: internal.Duration{
Duration: 5 * time.Second,
},
client: &RealHTTPClient{},
ResponseTimeout: config.Duration(5 * time.Second),
}
})
}

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -18,7 +18,7 @@ type Icinga2 struct {
ObjectType string
Username string
Password string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
Log telegraf.Logger
@ -125,15 +125,15 @@ func (i *Icinga2) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: i.ResponseTimeout.Duration,
Timeout: time.Duration(i.ResponseTimeout),
}
return client, nil
}
func (i *Icinga2) Gather(acc telegraf.Accumulator) error {
if i.ResponseTimeout.Duration < time.Second {
i.ResponseTimeout.Duration = time.Second * 5
if i.ResponseTimeout < config.Duration(time.Second) {
i.ResponseTimeout = config.Duration(time.Second * 5)
}
if i.client == nil {
@ -186,7 +186,7 @@ func init() {
return &Icinga2{
Server: "https://localhost:5665",
ObjectType: "services",
ResponseTimeout: internal.Duration{Duration: time.Second * 5},
ResponseTimeout: config.Duration(time.Second * 5),
}
})
}

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -33,10 +34,10 @@ func (e *APIError) Error() string {
}
type InfluxDB struct {
URLs []string `toml:"urls"`
Username string `toml:"username"`
Password string `toml:"password"`
Timeout internal.Duration `toml:"timeout"`
URLs []string `toml:"urls"`
Username string `toml:"username"`
Password string `toml:"password"`
Timeout config.Duration `toml:"timeout"`
tls.ClientConfig
client *http.Client
@ -86,10 +87,10 @@ func (i *InfluxDB) Gather(acc telegraf.Accumulator) error {
}
i.client = &http.Client{
Transport: &http.Transport{
ResponseHeaderTimeout: i.Timeout.Duration,
ResponseHeaderTimeout: time.Duration(i.Timeout),
TLSClientConfig: tlsCfg,
},
Timeout: i.Timeout.Duration,
Timeout: time.Duration(i.Timeout),
}
}
@ -318,7 +319,7 @@ func readResponseError(resp *http.Response) error {
func init() {
inputs.Add("influxdb", func() telegraf.Input {
return &InfluxDB{
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
})
}

View File

@ -11,6 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -29,14 +30,14 @@ type InfluxDBListener struct {
port int
tlsint.ServerConfig
ReadTimeout internal.Duration `toml:"read_timeout"`
WriteTimeout internal.Duration `toml:"write_timeout"`
MaxBodySize internal.Size `toml:"max_body_size"`
MaxLineSize internal.Size `toml:"max_line_size"` // deprecated in 1.14; ignored
BasicUsername string `toml:"basic_username"`
BasicPassword string `toml:"basic_password"`
DatabaseTag string `toml:"database_tag"`
RetentionPolicyTag string `toml:"retention_policy_tag"`
ReadTimeout config.Duration `toml:"read_timeout"`
WriteTimeout config.Duration `toml:"write_timeout"`
MaxBodySize config.Size `toml:"max_body_size"`
MaxLineSize config.Size `toml:"max_line_size"` // deprecated in 1.14; ignored
BasicUsername string `toml:"basic_username"`
BasicPassword string `toml:"basic_password"`
DatabaseTag string `toml:"database_tag"`
RetentionPolicyTag string `toml:"retention_policy_tag"`
timeFunc influx.TimeFunc
@ -137,19 +138,19 @@ func (h *InfluxDBListener) Init() error {
h.authFailures = selfstat.Register("influxdb_listener", "auth_failures", tags)
h.routes()
if h.MaxBodySize.Size == 0 {
h.MaxBodySize.Size = defaultMaxBodySize
if h.MaxBodySize == 0 {
h.MaxBodySize = config.Size(defaultMaxBodySize)
}
if h.MaxLineSize.Size != 0 {
if h.MaxLineSize != 0 {
h.Log.Warnf("Use of deprecated configuration: 'max_line_size'; parser now handles lines of unlimited length and option is ignored")
}
if h.ReadTimeout.Duration < time.Second {
h.ReadTimeout.Duration = time.Second * 10
if h.ReadTimeout < config.Duration(time.Second) {
h.ReadTimeout = config.Duration(time.Second * 10)
}
if h.WriteTimeout.Duration < time.Second {
h.WriteTimeout.Duration = time.Second * 10
if h.WriteTimeout < config.Duration(time.Second) {
h.WriteTimeout = config.Duration(time.Second * 10)
}
return nil
@ -167,8 +168,8 @@ func (h *InfluxDBListener) Start(acc telegraf.Accumulator) error {
h.server = http.Server{
Addr: h.ServiceAddress,
Handler: h,
ReadTimeout: h.ReadTimeout.Duration,
WriteTimeout: h.WriteTimeout.Duration,
ReadTimeout: time.Duration(h.ReadTimeout),
WriteTimeout: time.Duration(h.WriteTimeout),
TLSConfig: tlsConf,
}
@ -259,7 +260,7 @@ func (h *InfluxDBListener) handleWrite() http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
defer h.writesServed.Incr(1)
// Check that the content length is not too large for us to handle.
if req.ContentLength > h.MaxBodySize.Size {
if req.ContentLength > int64(h.MaxBodySize) {
if err := tooLarge(res); err != nil {
h.Log.Debugf("error in too-large: %v", err)
}
@ -270,7 +271,7 @@ func (h *InfluxDBListener) handleWrite() http.HandlerFunc {
rp := req.URL.Query().Get("rp")
body := req.Body
body = http.MaxBytesReader(res, body, h.MaxBodySize.Size)
body = http.MaxBytesReader(res, body, int64(h.MaxBodySize))
// Handle gzip request bodies
if req.Header.Get("Content-Encoding") == "gzip" {
var err error

View File

@ -8,7 +8,7 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/selfstat"
"github.com/influxdata/telegraf/testutil"
)
@ -20,9 +20,7 @@ func newListener() *InfluxDBListener {
acc: &testutil.NopAccumulator{},
bytesRecv: selfstat.Register("influxdb_listener", "bytes_received", map[string]string{}),
writesServed: selfstat.Register("influxdb_listener", "writes_served", map[string]string{}),
MaxBodySize: internal.Size{
Size: defaultMaxBodySize,
},
MaxBodySize: config.Size(defaultMaxBodySize),
}
return listener
}

View File

@ -14,7 +14,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
@ -308,7 +308,7 @@ func TestWriteVerySmallMaxBody(t *testing.T) {
listener := &InfluxDBListener{
Log: testutil.Logger{},
ServiceAddress: "localhost:0",
MaxBodySize: internal.Size{Size: 4096},
MaxBodySize: config.Size(4096),
timeFunc: time.Now,
}

View File

@ -12,6 +12,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -39,9 +40,9 @@ type InfluxDBV2Listener struct {
port int
tlsint.ServerConfig
MaxBodySize internal.Size `toml:"max_body_size"`
Token string `toml:"token"`
BucketTag string `toml:"bucket_tag"`
MaxBodySize config.Size `toml:"max_body_size"`
Token string `toml:"token"`
BucketTag string `toml:"bucket_tag"`
timeFunc influx.TimeFunc
@ -134,8 +135,8 @@ func (h *InfluxDBV2Listener) Init() error {
h.authFailures = selfstat.Register("influxdb_v2_listener", "auth_failures", tags)
h.routes()
if h.MaxBodySize.Size == 0 {
h.MaxBodySize.Size = defaultMaxBodySize
if h.MaxBodySize == 0 {
h.MaxBodySize = config.Size(defaultMaxBodySize)
}
return nil
@ -227,8 +228,8 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
defer h.writesServed.Incr(1)
// Check that the content length is not too large for us to handle.
if req.ContentLength > h.MaxBodySize.Size {
if err := tooLarge(res, h.MaxBodySize.Size); err != nil {
if req.ContentLength > int64(h.MaxBodySize) {
if err := tooLarge(res, int64(h.MaxBodySize)); err != nil {
h.Log.Debugf("error in too-large: %v", err)
}
return
@ -237,7 +238,7 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc {
bucket := req.URL.Query().Get("bucket")
body := req.Body
body = http.MaxBytesReader(res, body, h.MaxBodySize.Size)
body = http.MaxBytesReader(res, body, int64(h.MaxBodySize))
// Handle gzip request bodies
if req.Header.Get("Content-Encoding") == "gzip" {
var err error

View File

@ -8,7 +8,7 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/selfstat"
"github.com/influxdata/telegraf/testutil"
)
@ -20,9 +20,7 @@ func newListener() *InfluxDBV2Listener {
acc: &testutil.NopAccumulator{},
bytesRecv: selfstat.Register("influxdb_v2_listener", "bytes_received", map[string]string{}),
writesServed: selfstat.Register("influxdb_v2_listener", "writes_served", map[string]string{}),
MaxBodySize: internal.Size{
Size: defaultMaxBodySize,
},
MaxBodySize: config.Size(defaultMaxBodySize),
}
return listener
}

View File

@ -14,7 +14,7 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
@ -265,7 +265,7 @@ func TestWriteVerySmallMaxBody(t *testing.T) {
listener := &InfluxDBV2Listener{
Log: testutil.Logger{},
ServiceAddress: "localhost:0",
MaxBodySize: internal.Size{Size: 4096},
MaxBodySize: config.Size(4096),
timeFunc: time.Now,
}

View File

@ -15,6 +15,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -33,7 +34,7 @@ type Ipmi struct {
Privilege string
HexKey string `toml:"hex_key"`
Servers []string
Timeout internal.Duration
Timeout config.Duration
MetricVersion int
UseSudo bool
UseCache bool
@ -147,7 +148,7 @@ func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
name = "sudo"
}
cmd := execCommand(name, dumpOpts...)
out, err := internal.CombinedOutputTimeout(cmd, m.Timeout.Duration)
out, err := internal.CombinedOutputTimeout(cmd, time.Duration(m.Timeout))
if err != nil {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
}
@ -165,7 +166,7 @@ func (m *Ipmi) parse(acc telegraf.Accumulator, server string) error {
name = "sudo"
}
cmd := execCommand(name, opts...)
out, err := internal.CombinedOutputTimeout(cmd, m.Timeout.Duration)
out, err := internal.CombinedOutputTimeout(cmd, time.Duration(m.Timeout))
timestamp := time.Now()
if err != nil {
return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out))
@ -329,7 +330,7 @@ func init() {
if len(path) > 0 {
m.Path = path
}
m.Timeout = internal.Duration{Duration: time.Second * 20}
m.Timeout = config.Duration(time.Second * 20)
m.UseCache = false
m.CachePath = os.TempDir()
inputs.Add("ipmi_sensor", func() telegraf.Input {

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
@ -18,7 +18,7 @@ func TestGather(t *testing.T) {
Servers: []string{"USERID:PASSW0RD@lan(192.168.1.1)"},
Path: "ipmitool",
Privilege: "USER",
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
HexKey: "1234567F",
}
@ -126,7 +126,7 @@ func TestGather(t *testing.T) {
i = &Ipmi{
Path: "ipmitool",
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
err = acc.GatherError(i.Gather)
@ -390,7 +390,7 @@ func TestGatherV2(t *testing.T) {
Servers: []string{"USERID:PASSW0RD@lan(192.168.1.1)"},
Path: "ipmitool",
Privilege: "USER",
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
MetricVersion: 2,
HexKey: "0000000F",
}
@ -432,7 +432,7 @@ func TestGatherV2(t *testing.T) {
i = &Ipmi{
Path: "ipmitool",
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
MetricVersion: 2,
}

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -18,15 +19,15 @@ import (
type Ipset struct {
IncludeUnmatchedSets bool
UseSudo bool
Timeout internal.Duration
Timeout config.Duration
lister setLister
}
type setLister func(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error)
type setLister func(Timeout config.Duration, UseSudo bool) (*bytes.Buffer, error)
const measurement = "ipset"
var defaultTimeout = internal.Duration{Duration: time.Second}
var defaultTimeout = config.Duration(time.Second)
// Description returns a short description of the plugin
func (i *Ipset) Description() string {
@ -90,7 +91,7 @@ func (i *Ipset) Gather(acc telegraf.Accumulator) error {
return nil
}
func setList(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
func setList(timeout config.Duration, useSudo bool) (*bytes.Buffer, error) {
// Is ipset installed ?
ipsetPath, err := exec.LookPath("ipset")
if err != nil {
@ -98,7 +99,7 @@ func setList(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
}
var args []string
cmdName := ipsetPath
if UseSudo {
if useSudo {
cmdName = "sudo"
args = append(args, ipsetPath)
}
@ -108,7 +109,7 @@ func setList(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
var out bytes.Buffer
cmd.Stdout = &out
err = internal.RunTimeout(cmd, Timeout.Duration)
err = internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running ipset save: %s", err)
}

View File

@ -7,7 +7,7 @@ import (
"reflect"
"testing"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
@ -80,7 +80,7 @@ func TestIpset(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
i++
ips := &Ipset{
lister: func(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
lister: func(timeout config.Duration, useSudo bool) (*bytes.Buffer, error) {
return bytes.NewBufferString(tt.value), nil
},
}
@ -123,7 +123,7 @@ func TestIpset(t *testing.T) {
func TestIpset_Gather_listerError(t *testing.T) {
errFoo := errors.New("error foobar")
ips := &Ipset{
lister: func(Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
lister: func(timeout config.Duration, useSudo bool) (*bytes.Buffer, error) {
return new(bytes.Buffer), errFoo
},
}

View File

@ -11,8 +11,8 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -25,19 +25,19 @@ type Jenkins struct {
Source string
Port string
// HTTP Timeout specified as a string - 3s, 1m, 1h
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
client *client
Log telegraf.Logger
MaxConnections int `toml:"max_connections"`
MaxBuildAge internal.Duration `toml:"max_build_age"`
MaxSubJobDepth int `toml:"max_subjob_depth"`
MaxSubJobPerLayer int `toml:"max_subjob_per_layer"`
JobExclude []string `toml:"job_exclude"`
JobInclude []string `toml:"job_include"`
MaxConnections int `toml:"max_connections"`
MaxBuildAge config.Duration `toml:"max_build_age"`
MaxSubJobDepth int `toml:"max_subjob_depth"`
MaxSubJobPerLayer int `toml:"max_subjob_per_layer"`
JobExclude []string `toml:"job_exclude"`
JobInclude []string `toml:"job_include"`
jobFilterExclude filter.Filter
jobFilterInclude filter.Filter
@ -138,7 +138,7 @@ func (j *Jenkins) newHTTPClient() (*http.Client, error) {
TLSClientConfig: tlsCfg,
MaxIdleConns: j.MaxConnections,
},
Timeout: j.ResponseTimeout.Duration,
Timeout: time.Duration(j.ResponseTimeout),
}, nil
}
@ -353,7 +353,7 @@ func (j *Jenkins) getJobDetail(jr jobRequest, acc telegraf.Accumulator) error {
// stop if build is too old
// Higher up in gatherJobs
cutoff := time.Now().Add(-1 * j.MaxBuildAge.Duration)
cutoff := time.Now().Add(-1 * time.Duration(j.MaxBuildAge))
// Here we just test
if build.GetTimestamp().Before(cutoff) {
@ -501,7 +501,7 @@ func mapResultCode(s string) int {
func init() {
inputs.Add("jenkins", func() telegraf.Input {
return &Jenkins{
MaxBuildAge: internal.Duration{Duration: time.Hour},
MaxBuildAge: config.Duration(time.Hour),
MaxConnections: 5,
MaxSubJobPerLayer: 10,
}

View File

@ -10,7 +10,7 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
@ -304,7 +304,7 @@ func TestGatherNodeData(t *testing.T) {
j := &Jenkins{
Log: testutil.Logger{},
URL: ts.URL,
ResponseTimeout: internal.Duration{Duration: time.Microsecond},
ResponseTimeout: config.Duration(time.Microsecond),
NodeExclude: []string{"ignore-1", "ignore-2"},
}
te := j.initialize(&http.Client{Transport: &http.Transport{}})
@ -360,7 +360,7 @@ func TestInitialize(t *testing.T) {
input: &Jenkins{
Log: testutil.Logger{},
URL: "http://a bad url",
ResponseTimeout: internal.Duration{Duration: time.Microsecond},
ResponseTimeout: config.Duration(time.Microsecond),
},
wantErr: true,
},
@ -369,7 +369,7 @@ func TestInitialize(t *testing.T) {
input: &Jenkins{
Log: testutil.Logger{},
URL: ts.URL,
ResponseTimeout: internal.Duration{Duration: time.Microsecond},
ResponseTimeout: config.Duration(time.Microsecond),
JobInclude: []string{"jobA", "jobB"},
JobExclude: []string{"job1", "job2"},
NodeExclude: []string{"node1", "node2"},
@ -380,7 +380,7 @@ func TestInitialize(t *testing.T) {
input: &Jenkins{
Log: testutil.Logger{},
URL: ts.URL,
ResponseTimeout: internal.Duration{Duration: time.Microsecond},
ResponseTimeout: config.Duration(time.Microsecond),
},
output: &Jenkins{
Log: testutil.Logger{},
@ -807,8 +807,8 @@ func TestGatherJobs(t *testing.T) {
j := &Jenkins{
Log: testutil.Logger{},
URL: ts.URL,
MaxBuildAge: internal.Duration{Duration: time.Hour},
ResponseTimeout: internal.Duration{Duration: time.Microsecond},
MaxBuildAge: config.Duration(time.Hour),
ResponseTimeout: config.Duration(time.Microsecond),
JobInclude: []string{
"*",
},

View File

@ -10,13 +10,13 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Default http timeouts
var DefaultResponseHeaderTimeout = internal.Duration{Duration: 3 * time.Second}
var DefaultClientTimeout = internal.Duration{Duration: 4 * time.Second}
var DefaultResponseHeaderTimeout = config.Duration(3 * time.Second)
var DefaultClientTimeout = config.Duration(4 * time.Second)
type Server struct {
Name string
@ -54,9 +54,9 @@ type Jolokia struct {
Proxy Server
Delimiter string
ResponseHeaderTimeout internal.Duration `toml:"response_header_timeout"`
ClientTimeout internal.Duration `toml:"client_timeout"`
Log telegraf.Logger `toml:"-"`
ResponseHeaderTimeout config.Duration `toml:"response_header_timeout"`
ClientTimeout config.Duration `toml:"client_timeout"`
Log telegraf.Logger `toml:"-"`
}
const sampleConfig = `
@ -263,10 +263,10 @@ func (j *Jolokia) Gather(acc telegraf.Accumulator) error {
"in favor of the jolokia2 plugin " +
"(https://github.com/influxdata/telegraf/tree/master/plugins/inputs/jolokia2)")
tr := &http.Transport{ResponseHeaderTimeout: j.ResponseHeaderTimeout.Duration}
tr := &http.Transport{ResponseHeaderTimeout: time.Duration(j.ResponseHeaderTimeout)}
j.jClient = &JolokiaClientImpl{&http.Client{
Transport: tr,
Timeout: j.ClientTimeout.Duration,
Timeout: time.Duration(j.ClientTimeout),
}}
}

View File

@ -3,9 +3,10 @@ package jolokia2
import (
"fmt"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
)
@ -17,7 +18,7 @@ type JolokiaAgent struct {
URLs []string `toml:"urls"`
Username string
Password string
ResponseTimeout internal.Duration `toml:"response_timeout"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
@ -108,7 +109,7 @@ func (ja *JolokiaAgent) createClient(url string) (*Client, error) {
return NewClient(url, &ClientConfig{
Username: ja.Username,
Password: ja.Password,
ResponseTimeout: ja.ResponseTimeout.Duration,
ResponseTimeout: time.Duration(ja.ResponseTimeout),
ClientConfig: ja.ClientConfig,
})
}

View File

@ -1,8 +1,10 @@
package jolokia2
import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
)
@ -18,7 +20,7 @@ type JolokiaProxy struct {
Username string
Password string
ResponseTimeout internal.Duration `toml:"response_timeout"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
Metrics []MetricConfig `toml:"metric"`
@ -116,7 +118,7 @@ func (jp *JolokiaProxy) createClient() (*Client, error) {
return NewClient(jp.URL, &ClientConfig{
Username: jp.Username,
Password: jp.Password,
ResponseTimeout: jp.ResponseTimeout.Duration,
ResponseTimeout: time.Duration(jp.ResponseTimeout),
ClientConfig: jp.ClientConfig,
ProxyConfig: proxyConfig,
})

View File

@ -9,7 +9,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
internaltls "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/auth"
@ -22,15 +22,15 @@ import (
)
type OpenConfigTelemetry struct {
Servers []string `toml:"servers"`
Sensors []string `toml:"sensors"`
Username string `toml:"username"`
Password string `toml:"password"`
ClientID string `toml:"client_id"`
SampleFrequency internal.Duration `toml:"sample_frequency"`
StrAsTags bool `toml:"str_as_tags"`
RetryDelay internal.Duration `toml:"retry_delay"`
EnableTLS bool `toml:"enable_tls"`
Servers []string `toml:"servers"`
Sensors []string `toml:"sensors"`
Username string `toml:"username"`
Password string `toml:"password"`
ClientID string `toml:"client_id"`
SampleFrequency config.Duration `toml:"sample_frequency"`
StrAsTags bool `toml:"str_as_tags"`
RetryDelay config.Duration `toml:"retry_delay"`
EnableTLS bool `toml:"enable_tls"`
internaltls.ClientConfig
Log telegraf.Logger
@ -219,7 +219,7 @@ func (m *OpenConfigTelemetry) splitSensorConfig() int {
m.sensorsConfig = make([]sensorConfig, 0)
for _, sensor := range m.Sensors {
spathSplit := strings.Fields(sensor)
reportingRate = uint32(m.SampleFrequency.Duration / time.Millisecond)
reportingRate = uint32(time.Duration(m.SampleFrequency) / time.Millisecond)
// Extract measurement name and custom reporting rate if specified. Custom
// reporting rate will be specified at the beginning of sensor list,
@ -296,9 +296,9 @@ func (m *OpenConfigTelemetry) collectData(
}
// Retry with delay. If delay is not provided, use default
if m.RetryDelay.Duration > 0 {
m.Log.Debugf("Retrying %s with timeout %v", grpcServer, m.RetryDelay.Duration)
time.Sleep(m.RetryDelay.Duration)
if time.Duration(m.RetryDelay) > 0 {
m.Log.Debugf("Retrying %s with timeout %v", grpcServer, time.Duration(m.RetryDelay))
time.Sleep(time.Duration(m.RetryDelay))
continue
}
return
@ -408,7 +408,7 @@ func (m *OpenConfigTelemetry) Start(acc telegraf.Accumulator) error {
func init() {
inputs.Add("jti_openconfig_telemetry", func() telegraf.Input {
return &OpenConfigTelemetry{
RetryDelay: internal.Duration{Duration: time.Second},
RetryDelay: config.Duration(time.Second),
StrAsTags: false,
}
})

View File

@ -10,7 +10,7 @@ import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs/jti_openconfig_telemetry/oc"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
@ -19,7 +19,7 @@ import (
var cfg = &OpenConfigTelemetry{
Log: testutil.Logger{},
Servers: []string{"127.0.0.1:50051"},
SampleFrequency: internal.Duration{Duration: time.Second * 2},
SampleFrequency: config.Duration(time.Second * 2),
}
var data = &telemetry.OpenConfigData{

View File

@ -8,7 +8,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -19,7 +19,7 @@ const (
type Kapacitor struct {
URLs []string `toml:"urls"`
Timeout internal.Duration
Timeout config.Duration
tls.ClientConfig
client *http.Client
@ -83,7 +83,7 @@ func (k *Kapacitor) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: k.Timeout.Duration,
Timeout: time.Duration(k.Timeout),
}
return client, nil
@ -247,7 +247,7 @@ func init() {
inputs.Add("kapacitor", func() telegraf.Input {
return &Kapacitor{
URLs: []string{defaultURL},
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
})
}

View File

@ -12,7 +12,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -104,7 +104,7 @@ type Kibana struct {
Servers []string
Username string
Password string
Timeout internal.Duration
Timeout config.Duration
tls.ClientConfig
client *http.Client
@ -112,7 +112,7 @@ type Kibana struct {
func NewKibana() *Kibana {
return &Kibana{
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
}
@ -176,7 +176,7 @@ func (k *Kibana) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: k.Timeout.Duration,
Timeout: time.Duration(k.Timeout),
}
return client, nil

View File

@ -13,8 +13,8 @@ import (
"k8s.io/apimachinery/pkg/api/resource"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -25,14 +25,14 @@ const (
// KubernetesInventory represents the config object for the plugin.
type KubernetesInventory struct {
URL string `toml:"url"`
BearerToken string `toml:"bearer_token"`
BearerTokenString string `toml:"bearer_token_string"`
Namespace string `toml:"namespace"`
ResponseTimeout internal.Duration `toml:"response_timeout"` // Timeout specified as a string - 3s, 1m, 1h
ResourceExclude []string `toml:"resource_exclude"`
ResourceInclude []string `toml:"resource_include"`
MaxConfigMapAge internal.Duration `toml:"max_config_map_age"`
URL string `toml:"url"`
BearerToken string `toml:"bearer_token"`
BearerTokenString string `toml:"bearer_token_string"`
Namespace string `toml:"namespace"`
ResponseTimeout config.Duration `toml:"response_timeout"` // Timeout specified as a string - 3s, 1m, 1h
ResourceExclude []string `toml:"resource_exclude"`
ResourceInclude []string `toml:"resource_include"`
MaxConfigMapAge config.Duration `toml:"max_config_map_age"`
SelectorInclude []string `toml:"selector_include"`
SelectorExclude []string `toml:"selector_exclude"`
@ -109,7 +109,7 @@ func (ki *KubernetesInventory) Init() error {
}
var err error
ki.client, err = newClient(ki.URL, ki.Namespace, ki.BearerTokenString, ki.ResponseTimeout.Duration, ki.ClientConfig)
ki.client, err = newClient(ki.URL, ki.Namespace, ki.BearerTokenString, time.Duration(ki.ResponseTimeout), ki.ClientConfig)
if err != nil {
return err
@ -211,7 +211,7 @@ var (
func init() {
inputs.Add("kube_inventory", func() telegraf.Input {
return &KubernetesInventory{
ResponseTimeout: internal.Duration{Duration: time.Second * 5},
ResponseTimeout: config.Duration(time.Second * 5),
Namespace: "default",
SelectorInclude: []string{},
SelectorExclude: []string{"*"},

View File

@ -9,8 +9,8 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -29,7 +29,7 @@ type Kubernetes struct {
labelFilter filter.Filter
// HTTP Timeout specified as a string - 3s, 1m, 1h
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
@ -204,13 +204,13 @@ func (k *Kubernetes) LoadJSON(url string, v interface{}) error {
return err
}
if k.RoundTripper == nil {
if k.ResponseTimeout.Duration < time.Second {
k.ResponseTimeout.Duration = time.Second * 5
if k.ResponseTimeout < config.Duration(time.Second) {
k.ResponseTimeout = config.Duration(time.Second * 5)
}
k.RoundTripper = &http.Transport{
TLSHandshakeTimeout: 5 * time.Second,
TLSClientConfig: tlsCfg,
ResponseHeaderTimeout: k.ResponseTimeout.Duration,
ResponseHeaderTimeout: time.Duration(k.ResponseTimeout),
}
}
req.Header.Set("Authorization", "Bearer "+k.BearerTokenString)

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/choice"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -59,7 +59,7 @@ type Logstash struct {
Username string `toml:"username"`
Password string `toml:"password"`
Headers map[string]string `toml:"headers"`
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
tls.ClientConfig
client *http.Client
@ -72,7 +72,7 @@ func NewLogstash() *Logstash {
SinglePipeline: false,
Collect: []string{"pipelines", "process", "jvm"},
Headers: make(map[string]string),
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
}
@ -171,7 +171,7 @@ func (logstash *Logstash) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: logstash.Timeout.Duration,
Timeout: time.Duration(logstash.Timeout),
}
return client, nil

View File

@ -11,14 +11,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Mcrouter is a mcrouter plugin
type Mcrouter struct {
Servers []string
Timeout internal.Duration
Timeout config.Duration
}
// enum for statType
@ -127,11 +127,11 @@ func (m *Mcrouter) Description() string {
func (m *Mcrouter) Gather(acc telegraf.Accumulator) error {
ctx := context.Background()
if m.Timeout.Duration < 1*time.Second {
m.Timeout.Duration = defaultTimeout
if m.Timeout < config.Duration(1*time.Second) {
m.Timeout = config.Duration(defaultTimeout)
}
ctx, cancel := context.WithTimeout(ctx, m.Timeout.Duration)
ctx, cancel := context.WithTimeout(ctx, time.Duration(m.Timeout))
defer cancel()
if len(m.Servers) == 0 {

View File

@ -11,29 +11,29 @@ import (
mb "github.com/goburrow/modbus"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Modbus holds all data relevant to the plugin
type Modbus struct {
Name string `toml:"name"`
Controller string `toml:"controller"`
TransmissionMode string `toml:"transmission_mode"`
BaudRate int `toml:"baud_rate"`
DataBits int `toml:"data_bits"`
Parity string `toml:"parity"`
StopBits int `toml:"stop_bits"`
SlaveID int `toml:"slave_id"`
Timeout internal.Duration `toml:"timeout"`
Retries int `toml:"busy_retries"`
RetriesWaitTime internal.Duration `toml:"busy_retries_wait"`
DiscreteInputs []fieldContainer `toml:"discrete_inputs"`
Coils []fieldContainer `toml:"coils"`
HoldingRegisters []fieldContainer `toml:"holding_registers"`
InputRegisters []fieldContainer `toml:"input_registers"`
Log telegraf.Logger `toml:"-"`
Name string `toml:"name"`
Controller string `toml:"controller"`
TransmissionMode string `toml:"transmission_mode"`
BaudRate int `toml:"baud_rate"`
DataBits int `toml:"data_bits"`
Parity string `toml:"parity"`
StopBits int `toml:"stop_bits"`
SlaveID int `toml:"slave_id"`
Timeout config.Duration `toml:"timeout"`
Retries int `toml:"busy_retries"`
RetriesWaitTime config.Duration `toml:"busy_retries_wait"`
DiscreteInputs []fieldContainer `toml:"discrete_inputs"`
Coils []fieldContainer `toml:"coils"`
HoldingRegisters []fieldContainer `toml:"holding_registers"`
InputRegisters []fieldContainer `toml:"input_registers"`
Log telegraf.Logger `toml:"-"`
registers []register
isConnected bool
tcpHandler *mb.TCPClientHandler
@ -264,7 +264,7 @@ func connect(m *Modbus) error {
return err
}
m.tcpHandler = mb.NewTCPClientHandler(host + ":" + port)
m.tcpHandler.Timeout = m.Timeout.Duration
m.tcpHandler.Timeout = time.Duration(m.Timeout)
m.tcpHandler.SlaveId = byte(m.SlaveID)
m.client = mb.NewClient(m.tcpHandler)
err := m.tcpHandler.Connect()
@ -276,7 +276,7 @@ func connect(m *Modbus) error {
case "file":
if m.TransmissionMode == "RTU" {
m.rtuHandler = mb.NewRTUClientHandler(u.Path)
m.rtuHandler.Timeout = m.Timeout.Duration
m.rtuHandler.Timeout = time.Duration(m.Timeout)
m.rtuHandler.SlaveId = byte(m.SlaveID)
m.rtuHandler.BaudRate = m.BaudRate
m.rtuHandler.DataBits = m.DataBits
@ -291,7 +291,7 @@ func connect(m *Modbus) error {
return nil
} else if m.TransmissionMode == "ASCII" {
m.asciiHandler = mb.NewASCIIClientHandler(u.Path)
m.asciiHandler.Timeout = m.Timeout.Duration
m.asciiHandler.Timeout = time.Duration(m.Timeout)
m.asciiHandler.SlaveId = byte(m.SlaveID)
m.asciiHandler.BaudRate = m.BaudRate
m.asciiHandler.DataBits = m.DataBits
@ -679,7 +679,7 @@ func (m *Modbus) Gather(acc telegraf.Accumulator) error {
mberr, ok := err.(*mb.ModbusError)
if ok && mberr.ExceptionCode == mb.ExceptionCodeServerDeviceBusy && retry < m.Retries {
m.Log.Infof("Device busy! Retrying %d more time(s)...", m.Retries-retry)
time.Sleep(m.RetriesWaitTime.Duration)
time.Sleep(time.Duration(m.RetriesWaitTime))
continue
}
// Ignore return error to not shadow the initial error

View File

@ -4,9 +4,10 @@ import (
"encoding/xml"
"fmt"
"net/http"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
"golang.org/x/net/html/charset"
@ -178,7 +179,7 @@ type Monit struct {
Password string `toml:"password"`
client http.Client
tls.ClientConfig
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
}
type Messagebody struct {
@ -223,7 +224,7 @@ func (m *Monit) Init() error {
TLSClientConfig: tlsCfg,
Proxy: http.ProxyFromEnvironment,
},
Timeout: m.Timeout.Duration,
Timeout: time.Duration(m.Timeout),
}
return nil
}

View File

@ -10,6 +10,7 @@ import (
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -18,7 +19,7 @@ import (
var (
// 30 Seconds is the default used by paho.mqtt.golang
defaultConnectionTimeout = internal.Duration{Duration: 30 * time.Second}
defaultConnectionTimeout = config.Duration(30 * time.Second)
defaultMaxUndeliveredMessages = 1000
)
@ -43,14 +44,14 @@ type Client interface {
type ClientFactory func(o *mqtt.ClientOptions) Client
type MQTTConsumer struct {
Servers []string `toml:"servers"`
Topics []string `toml:"topics"`
TopicTag *string `toml:"topic_tag"`
Username string `toml:"username"`
Password string `toml:"password"`
QoS int `toml:"qos"`
ConnectionTimeout internal.Duration `toml:"connection_timeout"`
MaxUndeliveredMessages int `toml:"max_undelivered_messages"`
Servers []string `toml:"servers"`
Topics []string `toml:"topics"`
TopicTag *string `toml:"topic_tag"`
Username string `toml:"username"`
Password string `toml:"password"`
QoS int `toml:"qos"`
ConnectionTimeout config.Duration `toml:"connection_timeout"`
MaxUndeliveredMessages int `toml:"max_undelivered_messages"`
parser parsers.Parser
@ -169,8 +170,8 @@ func (m *MQTTConsumer) Init() error {
return fmt.Errorf("qos value must be 0, 1, or 2: %d", m.QoS)
}
if m.ConnectionTimeout.Duration < 1*time.Second {
return fmt.Errorf("connection_timeout must be greater than 1s: %s", m.ConnectionTimeout.Duration)
if time.Duration(m.ConnectionTimeout) < 1*time.Second {
return fmt.Errorf("connection_timeout must be greater than 1s: %s", time.Duration(m.ConnectionTimeout))
}
m.topicTag = "topic"
@ -320,7 +321,7 @@ func (m *MQTTConsumer) Gather(_ telegraf.Accumulator) error {
func (m *MQTTConsumer) createOpts() (*mqtt.ClientOptions, error) {
opts := mqtt.NewClientOptions()
opts.ConnectTimeout = m.ConnectionTimeout.Duration
opts.ConnectTimeout = time.Duration(m.ConnectionTimeout)
if m.ClientID == "" {
opts.SetClientID("Telegraf-Consumer-" + internal.RandomString(5))

View File

@ -11,14 +11,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
gnatsd "github.com/nats-io/nats-server/v2/server"
)
type Nats struct {
Server string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
client *http.Client
}
@ -93,7 +93,7 @@ func (n *Nats) createHTTPClient() *http.Client {
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
}
timeout := n.ResponseTimeout.Duration
timeout := time.Duration(n.ResponseTimeout)
if timeout == time.Duration(0) {
timeout = 5 * time.Second
}

View File

@ -14,7 +14,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -51,7 +51,7 @@ type outlet struct {
// NeptuneApex implements telegraf.Input.
type NeptuneApex struct {
Servers []string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
httpClient *http.Client
}

View File

@ -9,7 +9,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -26,8 +26,8 @@ const (
// NetResponse struct
type NetResponse struct {
Address string
Timeout internal.Duration
ReadTimeout internal.Duration
Timeout config.Duration
ReadTimeout config.Duration
Send string
Expect string
Protocol string
@ -80,7 +80,7 @@ func (n *NetResponse) TCPGather() (map[string]string, map[string]interface{}, er
// Start Timer
start := time.Now()
// Connecting
conn, err := net.DialTimeout("tcp", n.Address, n.Timeout.Duration)
conn, err := net.DialTimeout("tcp", n.Address, time.Duration(n.Timeout))
// Stop timer
responseTime := time.Since(start).Seconds()
// Handle error
@ -105,7 +105,7 @@ func (n *NetResponse) TCPGather() (map[string]string, map[string]interface{}, er
// Read string if needed
if n.Expect != "" {
// Set read timeout
if gerr := conn.SetReadDeadline(time.Now().Add(n.ReadTimeout.Duration)); gerr != nil {
if gerr := conn.SetReadDeadline(time.Now().Add(time.Duration(n.ReadTimeout))); gerr != nil {
return nil, nil, gerr
}
// Prepare reader
@ -169,7 +169,7 @@ func (n *NetResponse) UDPGather() (map[string]string, map[string]interface{}, er
}
// Read string
// Set read timeout
if gerr := conn.SetReadDeadline(time.Now().Add(n.ReadTimeout.Duration)); gerr != nil {
if gerr := conn.SetReadDeadline(time.Now().Add(time.Duration(n.ReadTimeout))); gerr != nil {
return nil, nil, gerr
}
// Read
@ -204,11 +204,11 @@ func (n *NetResponse) UDPGather() (map[string]string, map[string]interface{}, er
// also fill an Accumulator that is supplied.
func (n *NetResponse) Gather(acc telegraf.Accumulator) error {
// Set default values
if n.Timeout.Duration == 0 {
n.Timeout.Duration = time.Second
if n.Timeout == 0 {
n.Timeout = config.Duration(time.Second)
}
if n.ReadTimeout.Duration == 0 {
n.ReadTimeout.Duration = time.Second
if n.ReadTimeout == 0 {
n.ReadTimeout = config.Duration(time.Second)
}
// Check send and expected string
if n.Protocol == "udp" && n.Send == "" {

View File

@ -6,7 +6,7 @@ import (
"testing"
"time"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
@ -86,7 +86,7 @@ func TestTCPError(t *testing.T) {
c := NetResponse{
Protocol: "tcp",
Address: ":9999",
Timeout: internal.Duration{Duration: time.Second * 30},
Timeout: config.Duration(time.Second * 30),
}
// Gather
require.NoError(t, c.Gather(&acc))
@ -113,8 +113,8 @@ func TestTCPOK1(t *testing.T) {
Address: "127.0.0.1:2004",
Send: "test",
Expect: "test",
ReadTimeout: internal.Duration{Duration: time.Second * 3},
Timeout: internal.Duration{Duration: time.Second},
ReadTimeout: config.Duration(time.Second * 3),
Timeout: config.Duration(time.Second),
Protocol: "tcp",
}
// Start TCP server
@ -157,8 +157,8 @@ func TestTCPOK2(t *testing.T) {
Address: "127.0.0.1:2004",
Send: "test",
Expect: "test2",
ReadTimeout: internal.Duration{Duration: time.Second * 3},
Timeout: internal.Duration{Duration: time.Second},
ReadTimeout: config.Duration(time.Second * 3),
Timeout: config.Duration(time.Second),
Protocol: "tcp",
}
// Start TCP server
@ -237,8 +237,8 @@ func TestUDPOK1(t *testing.T) {
Address: "127.0.0.1:2004",
Send: "test",
Expect: "test",
ReadTimeout: internal.Duration{Duration: time.Second * 3},
Timeout: internal.Duration{Duration: time.Second},
ReadTimeout: config.Duration(time.Second * 3),
Timeout: config.Duration(time.Second),
Protocol: "udp",
}
// Start UDP server

View File

@ -12,14 +12,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type Nginx struct {
Urls []string
ResponseTimeout internal.Duration
ResponseTimeout config.Duration
tls.ClientConfig
// HTTP client
@ -86,15 +86,15 @@ func (n *Nginx) createHTTPClient() (*http.Client, error) {
return nil, err
}
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
client := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -13,14 +13,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type NginxPlus struct {
Urls []string `toml:"urls"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Urls []string `toml:"urls"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
client *http.Client
@ -82,8 +82,8 @@ func (n *NginxPlus) Gather(acc telegraf.Accumulator) error {
}
func (n *NginxPlus) createHTTPClient() (*http.Client, error) {
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
tlsConfig, err := n.ClientConfig.TLSConfig()
@ -95,7 +95,7 @@ func (n *NginxPlus) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -8,15 +8,15 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type NginxPlusAPI struct {
Urls []string `toml:"urls"`
APIVersion int64 `toml:"api_version"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Urls []string `toml:"urls"`
APIVersion int64 `toml:"api_version"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
client *http.Client
@ -106,8 +106,8 @@ func (n *NginxPlusAPI) Gather(acc telegraf.Accumulator) error {
}
func (n *NginxPlusAPI) createHTTPClient() (*http.Client, error) {
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
tlsConfig, err := n.ClientConfig.TLSConfig()
@ -119,7 +119,7 @@ func (n *NginxPlusAPI) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -12,14 +12,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type NginxSTS struct {
Urls []string `toml:"urls"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Urls []string `toml:"urls"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
client *http.Client
@ -81,8 +81,8 @@ func (n *NginxSTS) Gather(acc telegraf.Accumulator) error {
}
func (n *NginxSTS) createHTTPClient() (*http.Client, error) {
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
tlsConfig, err := n.ClientConfig.TLSConfig()
@ -94,7 +94,7 @@ func (n *NginxSTS) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -11,7 +11,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -55,7 +55,7 @@ type NginxUpstreamCheck struct {
Method string `toml:"method"`
Headers map[string]string `toml:"headers"`
HostHeader string `toml:"host_header"`
Timeout internal.Duration `toml:"timeout"`
Timeout config.Duration `toml:"timeout"`
tls.ClientConfig
client *http.Client
@ -67,7 +67,7 @@ func NewNginxUpstreamCheck() *NginxUpstreamCheck {
Method: "GET",
Headers: make(map[string]string),
HostHeader: "",
Timeout: internal.Duration{Duration: time.Second * 5},
Timeout: config.Duration(time.Second * 5),
}
}
@ -115,7 +115,7 @@ func (check *NginxUpstreamCheck) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: check.Timeout.Duration,
Timeout: time.Duration(check.Timeout),
}
return client, nil

View File

@ -12,14 +12,14 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
type NginxVTS struct {
Urls []string `toml:"urls"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Urls []string `toml:"urls"`
ResponseTimeout config.Duration `toml:"response_timeout"`
tls.ClientConfig
client *http.Client
@ -81,8 +81,8 @@ func (n *NginxVTS) Gather(acc telegraf.Accumulator) error {
}
func (n *NginxVTS) createHTTPClient() (*http.Client, error) {
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = time.Second * 5
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(time.Second * 5)
}
tlsConfig, err := n.ClientConfig.TLSConfig()
@ -94,7 +94,7 @@ func (n *NginxVTS) createHTTPClient() (*http.Client, error) {
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client, nil

View File

@ -11,16 +11,17 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
type runner func(cmdName string, Timeout internal.Duration, UseSudo bool, Server string, ConfigFile string) (*bytes.Buffer, error)
type runner func(cmdName string, timeout config.Duration, useSudo bool, Server string, ConfigFile string) (*bytes.Buffer, error)
// NSD is used to store configuration values
type NSD struct {
Binary string
Timeout internal.Duration
Timeout config.Duration
UseSudo bool
Server string
ConfigFile string
@ -29,7 +30,7 @@ type NSD struct {
}
var defaultBinary = "/usr/sbin/nsd-control"
var defaultTimeout = internal.Duration{Duration: time.Second}
var defaultTimeout = config.Duration(time.Second)
var sampleConfig = `
## Address of server to connect to, optionally ':port'. Defaults to the
@ -60,7 +61,7 @@ func (s *NSD) SampleConfig() string {
}
// Shell out to nsd_stat and return the output
func nsdRunner(cmdName string, Timeout internal.Duration, UseSudo bool, Server string, ConfigFile string) (*bytes.Buffer, error) {
func nsdRunner(cmdName string, timeout config.Duration, useSudo bool, Server string, ConfigFile string) (*bytes.Buffer, error) {
cmdArgs := []string{"stats_noreset"}
if Server != "" {
@ -78,14 +79,14 @@ func nsdRunner(cmdName string, Timeout internal.Duration, UseSudo bool, Server s
cmd := exec.Command(cmdName, cmdArgs...)
if UseSudo {
if useSudo {
cmdArgs = append([]string{cmdName}, cmdArgs...)
cmd = exec.Command("sudo", cmdArgs...)
}
var out bytes.Buffer
cmd.Stdout = &out
err := internal.RunTimeout(cmd, Timeout.Duration)
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running nsd-control: %s (%s %v)", err, cmdName, cmdArgs)
}

View File

@ -3,15 +3,18 @@ package nsd
import (
"bytes"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
func NSDControl(output string) func(string, internal.Duration, bool, string, string) (*bytes.Buffer, error) {
return func(string, internal.Duration, bool, string, string) (*bytes.Buffer, error) {
var TestTimeout = config.Duration(time.Second)
func NSDControl(output string) func(string, config.Duration, bool, string, string) (*bytes.Buffer, error) {
return func(string, config.Duration, bool, string, string) (*bytes.Buffer, error) {
return bytes.NewBuffer([]byte(output)), nil
}
}

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -19,7 +20,7 @@ const measurement = "nvidia_smi"
// NvidiaSMI holds the methods for this plugin
type NvidiaSMI struct {
BinPath string
Timeout internal.Duration
Timeout config.Duration
}
// Description returns the description of the NvidiaSMI plugin
@ -61,14 +62,14 @@ func init() {
inputs.Add("nvidia_smi", func() telegraf.Input {
return &NvidiaSMI{
BinPath: "/usr/bin/nvidia-smi",
Timeout: internal.Duration{Duration: 5 * time.Second},
Timeout: config.Duration(5 * time.Second),
}
})
}
func (smi *NvidiaSMI) pollSMI() ([]byte, error) {
// Construct and execute metrics query
ret, err := internal.CombinedOutputTimeout(exec.Command(smi.BinPath, "-q", "-x"), smi.Timeout.Duration)
ret, err := internal.CombinedOutputTimeout(exec.Command(smi.BinPath, "-q", "-x"), time.Duration(smi.Timeout))
if err != nil {
return nil, err
}

View File

@ -10,6 +10,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -34,19 +35,19 @@ var intI = map[string]int{
"poll": 4,
}
type runner func(cmdName string, Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error)
type runner func(cmdName string, timeout config.Duration, useSudo bool) (*bytes.Buffer, error)
// Openntpd is used to store configuration values
type Openntpd struct {
Binary string
Timeout internal.Duration
Timeout config.Duration
UseSudo bool
run runner
}
var defaultBinary = "/usr/sbin/ntpctl"
var defaultTimeout = internal.Duration{Duration: 5 * time.Second}
var defaultTimeout = config.Duration(5 * time.Second)
func (n *Openntpd) Description() string {
return "Get standard NTP query metrics from OpenNTPD."
@ -66,19 +67,19 @@ func (n *Openntpd) SampleConfig() string {
}
// Shell out to ntpctl and return the output
func openntpdRunner(cmdName string, Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
func openntpdRunner(cmdName string, timeout config.Duration, useSudo bool) (*bytes.Buffer, error) {
cmdArgs := []string{"-s", "peers"}
cmd := exec.Command(cmdName, cmdArgs...)
if UseSudo {
if useSudo {
cmdArgs = append([]string{cmdName}, cmdArgs...)
cmd = exec.Command("sudo", cmdArgs...)
}
var out bytes.Buffer
cmd.Stdout = &out
err := internal.RunTimeout(cmd, Timeout.Duration)
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running ntpctl: %s", err)
}

View File

@ -3,15 +3,18 @@ package openntpd
import (
"bytes"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
)
func OpenntpdCTL(output string) func(string, internal.Duration, bool) (*bytes.Buffer, error) {
return func(string, internal.Duration, bool) (*bytes.Buffer, error) {
var TestTimeout = config.Duration(time.Second)
func OpenntpdCTL(output string) func(string, config.Duration, bool) (*bytes.Buffer, error) {
return func(string, config.Duration, bool) (*bytes.Buffer, error) {
return bytes.NewBuffer([]byte(output)), nil
}
}

View File

@ -10,24 +10,25 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/filter"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/plugins/inputs"
)
type runner func(cmdName string, Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error)
type runner func(cmdName string, timeout config.Duration, useSudo bool) (*bytes.Buffer, error)
// Opensmtpd is used to store configuration values
type Opensmtpd struct {
Binary string
Timeout internal.Duration
Timeout config.Duration
UseSudo bool
run runner
}
var defaultBinary = "/usr/sbin/smtpctl"
var defaultTimeout = internal.Duration{Duration: time.Second}
var defaultTimeout = config.Duration(time.Second)
var sampleConfig = `
## If running as a restricted user you can prepend sudo for additional access:
@ -50,19 +51,19 @@ func (s *Opensmtpd) SampleConfig() string {
}
// Shell out to opensmtpd_stat and return the output
func opensmtpdRunner(cmdName string, Timeout internal.Duration, UseSudo bool) (*bytes.Buffer, error) {
func opensmtpdRunner(cmdName string, timeout config.Duration, useSudo bool) (*bytes.Buffer, error) {
cmdArgs := []string{"show", "stats"}
cmd := exec.Command(cmdName, cmdArgs...)
if UseSudo {
if useSudo {
cmdArgs = append([]string{cmdName}, cmdArgs...)
cmd = exec.Command("sudo", cmdArgs...)
}
var out bytes.Buffer
cmd.Stdout = &out
err := internal.RunTimeout(cmd, Timeout.Duration)
err := internal.RunTimeout(cmd, time.Duration(timeout))
if err != nil {
return &out, fmt.Errorf("error running smtpctl: %s", err)
}

View File

@ -2,14 +2,15 @@ package opensmtpd
import (
"bytes"
"github.com/influxdata/telegraf/internal"
"testing"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/assert"
"testing"
)
func SMTPCTL(output string) func(string, internal.Duration, bool) (*bytes.Buffer, error) {
return func(string, internal.Duration, bool) (*bytes.Buffer, error) {
func SMTPCTL(output string) func(string, config.Duration, bool) (*bytes.Buffer, error) {
return func(string, config.Duration, bool) (*bytes.Buffer, error) {
return bytes.NewBuffer([]byte(output)), nil
}
}

View File

@ -13,7 +13,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -30,13 +30,13 @@ const (
)
type OpenWeatherMap struct {
AppID string `toml:"app_id"`
CityID []string `toml:"city_id"`
Lang string `toml:"lang"`
Fetch []string `toml:"fetch"`
BaseURL string `toml:"base_url"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
Units string `toml:"units"`
AppID string `toml:"app_id"`
CityID []string `toml:"city_id"`
Lang string `toml:"lang"`
Fetch []string `toml:"fetch"`
BaseURL string `toml:"base_url"`
ResponseTimeout config.Duration `toml:"response_timeout"`
Units string `toml:"units"`
client *http.Client
baseURL *url.URL
@ -132,13 +132,13 @@ func (n *OpenWeatherMap) Gather(acc telegraf.Accumulator) error {
}
func (n *OpenWeatherMap) createHTTPClient() *http.Client {
if n.ResponseTimeout.Duration < time.Second {
n.ResponseTimeout.Duration = defaultResponseTimeout
if n.ResponseTimeout < config.Duration(time.Second) {
n.ResponseTimeout = config.Duration(defaultResponseTimeout)
}
client := &http.Client{
Transport: &http.Transport{},
Timeout: n.ResponseTimeout.Duration,
Timeout: time.Duration(n.ResponseTimeout),
}
return client
@ -299,9 +299,7 @@ func gatherForecast(acc telegraf.Accumulator, status *Status) {
func init() {
inputs.Add("openweathermap", func() telegraf.Input {
tmout := internal.Duration{
Duration: defaultResponseTimeout,
}
tmout := config.Duration(defaultResponseTimeout)
return &OpenWeatherMap{
ResponseTimeout: tmout,
BaseURL: defaultBaseURL,

View File

@ -5,7 +5,7 @@ import (
"strconv"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/postgresql"
_ "github.com/jackc/pgx/stdlib" // register driver
@ -193,11 +193,9 @@ func init() {
inputs.Add("pgbouncer", func() telegraf.Input {
return &PgBouncer{
Service: postgresql.Service{
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: internal.Duration{
Duration: 0,
},
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: config.Duration(0),
IsPgBouncer: true,
},
}

View File

@ -10,9 +10,10 @@ import (
"strconv"
"strings"
"sync"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/internal/globpath"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
@ -39,7 +40,7 @@ type poolStat map[string]metric
type phpfpm struct {
Urls []string
Timeout internal.Duration
Timeout config.Duration
tls.ClientConfig
client *http.Client
@ -96,7 +97,7 @@ func (p *phpfpm) Init() error {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: p.Timeout.Duration,
Timeout: time.Duration(p.Timeout),
}
return nil
}

View File

@ -9,7 +9,7 @@ import (
_ "github.com/jackc/pgx/stdlib"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
)
@ -195,11 +195,9 @@ func init() {
inputs.Add("postgresql", func() telegraf.Input {
return &Postgresql{
Service: Service{
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: internal.Duration{
Duration: 0,
},
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: config.Duration(0),
IsPgBouncer: false,
},
}

View File

@ -8,13 +8,14 @@ import (
"regexp"
"sort"
"strings"
"time"
"github.com/jackc/pgx"
"github.com/jackc/pgx/pgtype"
"github.com/jackc/pgx/stdlib"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
)
// pulled from lib/pq
@ -92,7 +93,7 @@ type Service struct {
Outputaddress string
MaxIdle int
MaxOpen int
MaxLifetime internal.Duration
MaxLifetime config.Duration
DB *sql.DB
IsPgBouncer bool
}
@ -145,7 +146,7 @@ func (p *Service) Start(telegraf.Accumulator) (err error) {
p.DB.SetMaxOpenConns(p.MaxOpen)
p.DB.SetMaxIdleConns(p.MaxIdle)
p.DB.SetConnMaxLifetime(p.MaxLifetime.Duration)
p.DB.SetConnMaxLifetime(time.Duration(p.MaxLifetime))
return nil
}

View File

@ -11,7 +11,7 @@ import (
_ "github.com/jackc/pgx/stdlib" //to register stdlib from PostgreSQL Driver and Toolkit
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/inputs"
"github.com/influxdata/telegraf/plugins/inputs/postgresql"
)
@ -342,11 +342,9 @@ func init() {
inputs.Add("postgresql_extensible", func() telegraf.Input {
return &Postgresql{
Service: postgresql.Service{
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: internal.Duration{
Duration: 0,
},
MaxIdle: 1,
MaxOpen: 1,
MaxLifetime: config.Duration(0),
IsPgBouncer: false,
},
}

View File

@ -14,7 +14,7 @@ import (
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/inputs"
parser_v2 "github.com/influxdata/telegraf/plugins/parsers/prometheus"
@ -48,7 +48,7 @@ type Prometheus struct {
Username string `toml:"username"`
Password string `toml:"password"`
ResponseTimeout internal.Duration `toml:"response_timeout"`
ResponseTimeout config.Duration `toml:"response_timeout"`
MetricVersion int `toml:"metric_version"`
@ -308,7 +308,7 @@ func (p *Prometheus) createHTTPClient() (*http.Client, error) {
TLSClientConfig: tlsCfg,
DisableKeepAlives: true,
},
Timeout: p.ResponseTimeout.Duration,
Timeout: time.Duration(p.ResponseTimeout),
}
return client, nil
@ -341,7 +341,7 @@ func (p *Prometheus) gatherURL(u URLAndAddress, acc telegraf.Accumulator) error
return c, err
},
},
Timeout: p.ResponseTimeout.Duration,
Timeout: time.Duration(p.ResponseTimeout),
}
} else {
if u.URL.Path == "" {
@ -474,7 +474,7 @@ func (p *Prometheus) Stop() {
func init() {
inputs.Add("prometheus", func() telegraf.Input {
return &Prometheus{
ResponseTimeout: internal.Duration{Duration: time.Second * 3},
ResponseTimeout: config.Duration(time.Second * 3),
kubernetesPods: map[string]URLAndAddress{},
URLTag: "url",
}

View File

@ -8,6 +8,7 @@ import (
"net/url"
"os"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
@ -66,7 +67,7 @@ func (px *Proxmox) Init() error {
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
},
Timeout: px.ResponseTimeout.Duration,
Timeout: time.Duration(px.ResponseTimeout),
}
return nil

Some files were not shown because too many files have changed in this diff Show More