From 9853bf6c54ff18ab0e14a141b7b4580a1e54976a Mon Sep 17 00:00:00 2001 From: Sven Rebhan <36194019+srebhan@users.noreply.github.com> Date: Fri, 9 Apr 2021 19:15:04 +0200 Subject: [PATCH] Get rid of deprecated internal.{Duration,Size,Number} (#8969) --- agent/agent.go | 22 +- cmd/telegraf/telegraf.go | 10 +- config/config.go | 18 +- config/config_test.go | 303 +++++++++++------- config/testdata/azure_monitor.toml | 4 + config/types_test.go | 46 +++ go.sum | 14 + internal/internal.go | 83 ----- internal/internal_test.go | 46 --- internal/snmp/config.go | 6 +- internal/snmp/wrapper.go | 3 +- logger/logger.go | 8 +- logger/logger_test.go | 10 +- plugins/aggregators/final/final.go | 8 +- plugins/aggregators/final/final_test.go | 4 +- plugins/inputs/activemq/activemq.go | 22 +- plugins/inputs/aliyuncms/aliyuncms.go | 61 ++-- plugins/inputs/aliyuncms/aliyuncms_test.go | 38 ++- plugins/inputs/apache/apache.go | 10 +- plugins/inputs/apcupsd/apcupsd.go | 8 +- plugins/inputs/aurora/aurora.go | 18 +- plugins/inputs/beat/beat.go | 8 +- plugins/inputs/burrow/burrow.go | 12 +- plugins/inputs/clickhouse/clickhouse.go | 21 +- plugins/inputs/cloud_pubsub/pubsub.go | 17 +- .../inputs/cloud_pubsub_push/pubsub_push.go | 28 +- .../cloud_pubsub_push/pubsub_push_test.go | 14 +- plugins/inputs/dcos/dcos.go | 12 +- plugins/inputs/docker/docker.go | 16 +- plugins/inputs/docker_log/docker_log.go | 28 +- plugins/inputs/docker_log/docker_log_test.go | 4 +- plugins/inputs/ecs/ecs.go | 8 +- plugins/inputs/elasticsearch/elasticsearch.go | 34 +- plugins/inputs/exec/exec.go | 11 +- plugins/inputs/fibaro/fibaro.go | 8 +- plugins/inputs/filecount/filecount.go | 24 +- plugins/inputs/filecount/filecount_test.go | 14 +- plugins/inputs/fireboard/fireboard.go | 14 +- plugins/inputs/github/github.go | 16 +- plugins/inputs/gnmi/gnmi.go | 22 +- plugins/inputs/gnmi/gnmi_test.go | 12 +- plugins/inputs/http/http.go | 7 +- .../http_listener_v2/http_listener_v2.go | 28 +- .../http_listener_v2/http_listener_v2_test.go | 10 +- plugins/inputs/http_response/http_response.go | 24 +- .../http_response/http_response_test.go | 66 ++-- plugins/inputs/httpjson/httpjson.go | 14 +- plugins/inputs/icinga2/icinga2.go | 12 +- plugins/inputs/influxdb/influxdb.go | 15 +- .../influxdb_listener/influxdb_listener.go | 39 +-- .../influxdb_listener_benchmark_test.go | 6 +- .../influxdb_listener_test.go | 4 +- .../influxdb_v2_listener.go | 17 +- .../influxdb_v2_listener_benchmark_test.go | 6 +- .../influxdb_v2_listener_test.go | 4 +- plugins/inputs/ipmi_sensor/ipmi.go | 9 +- plugins/inputs/ipmi_sensor/ipmi_test.go | 10 +- plugins/inputs/ipset/ipset.go | 13 +- plugins/inputs/ipset/ipset_test.go | 6 +- plugins/inputs/jenkins/jenkins.go | 22 +- plugins/inputs/jenkins/jenkins_test.go | 14 +- plugins/inputs/jolokia/jolokia.go | 16 +- plugins/inputs/jolokia2/jolokia_agent.go | 7 +- plugins/inputs/jolokia2/jolokia_proxy.go | 8 +- .../openconfig_telemetry.go | 30 +- .../openconfig_telemetry_test.go | 4 +- plugins/inputs/kapacitor/kapacitor.go | 8 +- plugins/inputs/kibana/kibana.go | 8 +- plugins/inputs/kube_inventory/kube_state.go | 22 +- plugins/inputs/kubernetes/kubernetes.go | 10 +- plugins/inputs/logstash/logstash.go | 8 +- plugins/inputs/mcrouter/mcrouter.go | 10 +- plugins/inputs/modbus/modbus.go | 42 +-- plugins/inputs/monit/monit.go | 7 +- plugins/inputs/mqtt_consumer/mqtt_consumer.go | 25 +- plugins/inputs/nats/nats.go | 6 +- plugins/inputs/neptune_apex/neptune_apex.go | 4 +- plugins/inputs/net_response/net_response.go | 20 +- .../inputs/net_response/net_response_test.go | 16 +- plugins/inputs/nginx/nginx.go | 10 +- plugins/inputs/nginx_plus/nginx_plus.go | 12 +- .../inputs/nginx_plus_api/nginx_plus_api.go | 14 +- plugins/inputs/nginx_sts/nginx_sts.go | 12 +- .../nginx_upstream_check.go | 8 +- plugins/inputs/nginx_vts/nginx_vts.go | 12 +- plugins/inputs/nsd/nsd.go | 13 +- plugins/inputs/nsd/nsd_test.go | 9 +- plugins/inputs/nvidia_smi/nvidia_smi.go | 7 +- plugins/inputs/openntpd/openntpd.go | 13 +- plugins/inputs/openntpd/openntpd_test.go | 9 +- plugins/inputs/opensmtpd/opensmtpd.go | 13 +- plugins/inputs/opensmtpd/opensmtpd_test.go | 9 +- .../inputs/openweathermap/openweathermap.go | 26 +- plugins/inputs/pgbouncer/pgbouncer.go | 10 +- plugins/inputs/phpfpm/phpfpm.go | 7 +- plugins/inputs/postgresql/postgresql.go | 10 +- plugins/inputs/postgresql/service.go | 7 +- .../postgresql_extensible.go | 10 +- plugins/inputs/prometheus/prometheus.go | 10 +- plugins/inputs/proxmox/proxmox.go | 3 +- plugins/inputs/proxmox/structs.go | 10 +- plugins/inputs/rabbitmq/rabbitmq.go | 14 +- plugins/inputs/ravendb/ravendb.go | 10 +- .../riemann_listener/riemann_listener.go | 26 +- .../riemann_listener/riemann_listener_test.go | 4 +- plugins/inputs/sensors/sensors.go | 9 +- plugins/inputs/sflow/sflow.go | 10 +- plugins/inputs/smart/smart.go | 37 +-- plugins/inputs/smart/smart_test.go | 46 +-- plugins/inputs/snmp/snmp.go | 6 +- plugins/inputs/snmp/snmp_test.go | 21 +- plugins/inputs/snmp_trap/snmp_trap.go | 15 +- plugins/inputs/snmp_trap/snmp_trap_test.go | 4 +- .../inputs/socket_listener/socket_listener.go | 31 +- .../socket_listener/socket_listener_test.go | 13 +- plugins/inputs/solr/solr.go | 9 +- plugins/inputs/stackdriver/stackdriver.go | 24 +- plugins/inputs/statsd/README.md | 2 +- plugins/inputs/statsd/statsd.go | 12 +- plugins/inputs/statsd/statsd_test.go | 7 +- plugins/inputs/syslog/commons_test.go | 10 +- plugins/inputs/syslog/nontransparent_test.go | 12 +- plugins/inputs/syslog/octetcounting_test.go | 12 +- plugins/inputs/syslog/syslog.go | 33 +- plugins/inputs/sysstat/sysstat.go | 7 +- .../systemd_units/systemd_units_linux.go | 15 +- .../systemd_units/systemd_units_linux_test.go | 4 +- plugins/inputs/tail/multiline.go | 9 +- plugins/inputs/tail/multiline_test.go | 12 +- plugins/inputs/tail/tail.go | 4 +- plugins/inputs/tail/tail_test.go | 21 +- plugins/inputs/tengine/tengine.go | 10 +- plugins/inputs/tomcat/tomcat.go | 8 +- plugins/inputs/unbound/unbound.go | 19 +- plugins/inputs/unbound/unbound_test.go | 3 +- plugins/inputs/uwsgi/uwsgi.go | 14 +- plugins/inputs/varnish/varnish.go | 17 +- plugins/inputs/varnish/varnish_test.go | 6 +- plugins/inputs/vsphere/client.go | 14 +- plugins/inputs/vsphere/endpoint.go | 24 +- plugins/inputs/vsphere/vsphere.go | 10 +- plugins/inputs/vsphere/vsphere_test.go | 6 +- .../win_perf_counters/win_perf_counters.go | 8 +- .../win_perf_counters_test.go | 10 +- plugins/inputs/x509_cert/x509_cert.go | 12 +- plugins/inputs/x509_cert/x509_cert_test.go | 16 +- plugins/inputs/zookeeper/zookeeper.go | 10 +- plugins/outputs/amon/amon.go | 13 +- plugins/outputs/amqp/amqp.go | 7 +- plugins/outputs/amqp/amqp_test.go | 48 +-- .../application_insights.go | 10 +- .../application_insights_test.go | 8 +- .../outputs/azure_monitor/azure_monitor.go | 10 +- plugins/outputs/bigquery/bigquery.go | 14 +- plugins/outputs/bigquery/bigquery_test.go | 4 +- plugins/outputs/cloud_pubsub/pubsub.go | 16 +- plugins/outputs/cloud_pubsub/topic_stubbed.go | 4 +- plugins/outputs/cratedb/cratedb.go | 10 +- plugins/outputs/cratedb/cratedb_test.go | 4 +- plugins/outputs/datadog/datadog.go | 13 +- plugins/outputs/dynatrace/dynatrace.go | 18 +- plugins/outputs/dynatrace/dynatrace_test.go | 4 +- .../outputs/elasticsearch/elasticsearch.go | 20 +- .../elasticsearch/elasticsearch_test.go | 14 +- plugins/outputs/exec/exec.go | 9 +- plugins/outputs/exec/exec_test.go | 4 +- plugins/outputs/file/file.go | 17 +- plugins/outputs/health/health.go | 19 +- plugins/outputs/http/http.go | 15 +- plugins/outputs/influxdb/influxdb.go | 12 +- plugins/outputs/influxdb/influxdb_test.go | 8 +- plugins/outputs/influxdb_v2/influxdb.go | 8 +- plugins/outputs/instrumental/instrumental.go | 21 +- plugins/outputs/librato/librato.go | 19 +- plugins/outputs/logzio/logzio.go | 14 +- plugins/outputs/loki/loki.go | 9 +- plugins/outputs/mqtt/mqtt.go | 11 +- plugins/outputs/newrelic/newrelic.go | 14 +- plugins/outputs/newrelic/newrelic_test.go | 6 +- .../prometheus_client/prometheus_client.go | 27 +- plugins/outputs/riemann/riemann.go | 26 +- .../outputs/socket_writer/socket_writer.go | 8 +- plugins/outputs/sumologic/sumologic.go | 20 +- plugins/outputs/syslog/syslog.go | 9 +- plugins/outputs/warp10/warp10.go | 20 +- .../yandex_cloud_monitoring.go | 14 +- plugins/processors/date/date.go | 14 +- plugins/processors/date/date_test.go | 4 +- plugins/processors/dedup/dedup.go | 12 +- plugins/processors/dedup/dedup_test.go | 4 +- plugins/processors/ifname/ifname.go | 3 +- plugins/processors/ifname/ifname_test.go | 5 +- plugins/processors/topk/topk.go | 26 +- plugins/processors/topk/topk_test.go | 6 +- 194 files changed, 1563 insertions(+), 1540 deletions(-) create mode 100644 config/testdata/azure_monitor.toml diff --git a/agent/agent.go b/agent/agent.go index 96e8596b851b2..78097bcd47731 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -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()) diff --git a/cmd/telegraf/telegraf.go b/cmd/telegraf/telegraf.go index 459f81a90dc7c..f7df792728b23 100644 --- a/cmd/telegraf/telegraf.go +++ b/cmd/telegraf/telegraf.go @@ -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) diff --git a/config/config.go b/config/config.go index 097fff385f531..610f79cc3fd7e 100644 --- a/config/config.go +++ b/config/config.go @@ -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. diff --git a/config/config_test.go b/config/config_test.go index e238dbade1e82..3095ffdf12b08 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -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) - - 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.") + expectedConfigs[0].Tags = make(map[string]string) - 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) - - exec := c.Inputs[1].Input.(*exec.Exec) - require.NotNil(t, exec.Log) - exec.Log = nil - - 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.") + expectedConfigs[1].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[2] = inputs.Inputs["memcached"]().(*MockupInputPlugin) + expectedPlugins[2].Servers = []string{"192.168.1.1"} - pstat := inputs.Inputs["procstat"]().(*procstat.Procstat) - pstat.PidFile = "/var/run/grafana-server.pid" - - pConfig := &models.InputConfig{Name: "procstat"} - pConfig.Tags = make(map[string]string) + 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) + + 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) + + // 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 + + // 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)) - - 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) + require.NoError(t, c.LoadConfig("./testdata/inline_table.toml")) + require.Len(t, c.Outputs, 2) + + 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) - - 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) + require.NoError(t, c.LoadConfig("./testdata/azure_monitor.toml")) + require.Len(t, c.Outputs, 2) + + 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{} }) +} diff --git a/config/testdata/azure_monitor.toml b/config/testdata/azure_monitor.toml new file mode 100644 index 0000000000000..6151bea9020c5 --- /dev/null +++ b/config/testdata/azure_monitor.toml @@ -0,0 +1,4 @@ +[[outputs.azure_monitor]] + +[[outputs.azure_monitor]] + namespace_prefix = "" diff --git a/config/types_test.go b/config/types_test.go index 8e35de6111c82..afff599e3d6e4 100644 --- a/config/types_test.go +++ b/config/types_test.go @@ -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)) +} diff --git a/go.sum b/go.sum index d67550751eed1..f2f65d843f712 100644 --- a/go.sum +++ b/go.sum @@ -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= diff --git a/internal/internal.go b/internal/internal.go index 8b0dfff1fd418..636d7f06a7014 100644 --- a/internal/internal.go +++ b/internal/internal.go @@ -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) { diff --git a/internal/internal_test.go b/internal/internal_test.go index 16980ecef93af..2bed302ee0a11 100644 --- a/internal/internal_test.go +++ b/internal/internal_test.go @@ -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)) diff --git a/internal/snmp/config.go b/internal/snmp/config.go index 9941f0682fe3d..0a200b7067787 100644 --- a/internal/snmp/config.go +++ b/internal/snmp/config.go @@ -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"` diff --git a/internal/snmp/wrapper.go b/internal/snmp/wrapper.go index 9825d5677ff73..9220098e37f73 100644 --- a/internal/snmp/wrapper.go +++ b/internal/snmp/wrapper.go @@ -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 diff --git a/logger/logger.go b/logger/logger.go index 58a8b906f6596..c365c057304aa 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -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 } diff --git a/logger/logger_test.go b/logger/logger_test.go index a5f53ca17e89b..8bb01e8e5328b 100644 --- a/logger/logger_test.go +++ b/logger/logger_test.go @@ -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) diff --git a/plugins/aggregators/final/final.go b/plugins/aggregators/final/final.go index 53ad0a47c9d95..3ef32a10ab39f 100644 --- a/plugins/aggregators/final/final.go +++ b/plugins/aggregators/final/final.go @@ -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 diff --git a/plugins/aggregators/final/final_test.go b/plugins/aggregators/final/final_test.go index 1b3367fa5b3ad..a4add9a5ce20c 100644 --- a/plugins/aggregators/final/final_test.go +++ b/plugins/aggregators/final/final_test.go @@ -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() diff --git a/plugins/inputs/activemq/activemq.go b/plugins/inputs/activemq/activemq.go index cb8793619ff8f..0674b7ae0fe52 100644 --- a/plugins/inputs/activemq/activemq.go +++ b/plugins/inputs/activemq/activemq.go @@ -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 diff --git a/plugins/inputs/aliyuncms/aliyuncms.go b/plugins/inputs/aliyuncms/aliyuncms.go index 6aebf99b836fa..3b521579b12de 100644 --- a/plugins/inputs/aliyuncms/aliyuncms.go +++ b/plugins/inputs/aliyuncms/aliyuncms.go @@ -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 : ## To figure out which fields are available, consult the Describe 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", } }) diff --git a/plugins/inputs/aliyuncms/aliyuncms_test.go b/plugins/inputs/aliyuncms/aliyuncms_test.go index a844ab4ee7a3a..b9028c8ba22a0 100644 --- a/plugins/inputs/aliyuncms/aliyuncms_test.go +++ b/plugins/inputs/aliyuncms/aliyuncms_test.go @@ -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"} ] }, diff --git a/plugins/inputs/apache/apache.go b/plugins/inputs/apache/apache.go index 12edc62cc845c..429d1cb9e69cc 100644 --- a/plugins/inputs/apache/apache.go +++ b/plugins/inputs/apache/apache.go @@ -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 diff --git a/plugins/inputs/apcupsd/apcupsd.go b/plugins/inputs/apcupsd/apcupsd.go index 4acadffe38dd2..b41a91b829af2 100644 --- a/plugins/inputs/apcupsd/apcupsd.go +++ b/plugins/inputs/apcupsd/apcupsd.go @@ -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) diff --git a/plugins/inputs/aurora/aurora.go b/plugins/inputs/aurora/aurora.go index fc6f82aadda17..04737adbabd86 100644 --- a/plugins/inputs/aurora/aurora.go +++ b/plugins/inputs/aurora/aurora.go @@ -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 { diff --git a/plugins/inputs/beat/beat.go b/plugins/inputs/beat/beat.go index 79769df9ddbbc..2d57a6deadfca 100644 --- a/plugins/inputs/beat/beat.go +++ b/plugins/inputs/beat/beat.go @@ -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 diff --git a/plugins/inputs/burrow/burrow.go b/plugins/inputs/burrow/burrow.go index 501fddf16ad77..d575ea7f5eb0e 100644 --- a/plugins/inputs/burrow/burrow.go +++ b/plugins/inputs/burrow/burrow.go @@ -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 diff --git a/plugins/inputs/clickhouse/clickhouse.go b/plugins/inputs/clickhouse/clickhouse.go index 866ddeb8c164f..4e87431c0b032 100644 --- a/plugins/inputs/clickhouse/clickhouse.go +++ b/plugins/inputs/clickhouse/clickhouse.go @@ -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 { diff --git a/plugins/inputs/cloud_pubsub/pubsub.go b/plugins/inputs/cloud_pubsub/pubsub.go index 230c459045727..806f84f61340d 100644 --- a/plugins/inputs/cloud_pubsub/pubsub.go +++ b/plugins/inputs/cloud_pubsub/pubsub.go @@ -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 ` diff --git a/plugins/inputs/cloud_pubsub_push/pubsub_push.go b/plugins/inputs/cloud_pubsub_push/pubsub_push.go index 575bdae61f8c9..5b434599a986f 100644 --- a/plugins/inputs/cloud_pubsub_push/pubsub_push.go +++ b/plugins/inputs/cloud_pubsub_push/pubsub_push.go @@ -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) diff --git a/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go b/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go index ccce488a81c6e..bd958e961dd0a 100644 --- a/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go +++ b/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go @@ -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) diff --git a/plugins/inputs/dcos/dcos.go b/plugins/inputs/dcos/dcos.go index 20cb47fd34288..25e4e4755cc30 100644 --- a/plugins/inputs/dcos/dcos.go +++ b/plugins/inputs/dcos/dcos.go @@ -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), } }) } diff --git a/plugins/inputs/docker/docker.go b/plugins/inputs/docker/docker.go index 087e106ad4112..1b44351178d41 100644 --- a/plugins/inputs/docker/docker.go +++ b/plugins/inputs/docker/docker.go @@ -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, diff --git a/plugins/inputs/docker_log/docker_log.go b/plugins/inputs/docker_log/docker_log.go index 878bf4a63fbe3..73bcefb3d887c 100644 --- a/plugins/inputs/docker_log/docker_log.go +++ b/plugins/inputs/docker_log/docker_log.go @@ -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, diff --git a/plugins/inputs/docker_log/docker_log_test.go b/plugins/inputs/docker_log/docker_log_test.go index c8903c9d8ec28..6d92b73ee6d41 100644 --- a/plugins/inputs/docker_log/docker_log_test.go +++ b/plugins/inputs/docker_log/docker_log_test.go @@ -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, diff --git a/plugins/inputs/ecs/ecs.go b/plugins/inputs/ecs/ecs.go index 2194257f1913d..d563fef5038d5 100644 --- a/plugins/inputs/ecs/ecs.go +++ b/plugins/inputs/ecs/ecs.go @@ -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, } diff --git a/plugins/inputs/elasticsearch/elasticsearch.go b/plugins/inputs/elasticsearch/elasticsearch.go index 505bb69835041..aac23d707edba 100644 --- a/plugins/inputs/elasticsearch/elasticsearch.go +++ b/plugins/inputs/elasticsearch/elasticsearch.go @@ -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 diff --git a/plugins/inputs/exec/exec.go b/plugins/inputs/exec/exec.go index fc498c799c966..3cd8beb029a7f 100644 --- a/plugins/inputs/exec/exec.go +++ b/plugins/inputs/exec/exec.go @@ -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) diff --git a/plugins/inputs/fibaro/fibaro.go b/plugins/inputs/fibaro/fibaro.go index 6cfe9e64834cf..b60eecfa8e2a6 100644 --- a/plugins/inputs/fibaro/fibaro.go +++ b/plugins/inputs/fibaro/fibaro.go @@ -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), } }) } diff --git a/plugins/inputs/filecount/filecount.go b/plugins/inputs/filecount/filecount.go index 87c98075487e1..cc72fb348386b 100644 --- a/plugins/inputs/filecount/filecount.go +++ b/plugins/inputs/filecount/filecount.go @@ -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{}, } diff --git a/plugins/inputs/filecount/filecount_test.go b/plugins/inputs/filecount/filecount_test.go index a4c073bf15d80..35bb0f080c73a 100644 --- a/plugins/inputs/filecount/filecount_test.go +++ b/plugins/inputs/filecount/filecount_test.go @@ -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()), } diff --git a/plugins/inputs/fireboard/fireboard.go b/plugins/inputs/fireboard/fireboard.go index 92846a0760cfd..eba11d6196409 100644 --- a/plugins/inputs/fireboard/fireboard.go +++ b/plugins/inputs/fireboard/fireboard.go @@ -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 } diff --git a/plugins/inputs/github/github.go b/plugins/inputs/github/github.go index c7e3888f9c4e6..020775cb43e8c 100644 --- a/plugins/inputs/github/github.go +++ b/plugins/inputs/github/github.go @@ -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), } }) } diff --git a/plugins/inputs/gnmi/gnmi.go b/plugins/inputs/gnmi/gnmi.go index 5d4c80edd5538..19207717a5582 100644 --- a/plugins/inputs/gnmi/gnmi.go +++ b/plugins/inputs/gnmi/gnmi.go @@ -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), } } diff --git a/plugins/inputs/gnmi/gnmi_test.go b/plugins/inputs/gnmi/gnmi_test.go index 1846fd67a9951..25840db46ef2f 100644 --- a/plugins/inputs/gnmi/gnmi_test.go +++ b/plugins/inputs/gnmi/gnmi_test.go @@ -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() diff --git a/plugins/inputs/http/http.go b/plugins/inputs/http/http.go index 58a5bd51040ed..3c5b80a8e3f95 100644 --- a/plugins/inputs/http/http.go +++ b/plugins/inputs/http/http.go @@ -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", } }) diff --git a/plugins/inputs/http_listener_v2/http_listener_v2.go b/plugins/inputs/http_listener_v2/http_listener_v2.go index 6a6d45592033d..89714bb0818b1 100644 --- a/plugins/inputs/http_listener_v2/http_listener_v2.go +++ b/plugins/inputs/http_listener_v2/http_listener_v2.go @@ -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 { diff --git a/plugins/inputs/http_listener_v2/http_listener_v2_test.go b/plugins/inputs/http_listener_v2/http_listener_v2_test.go index e4507984c3394..6b906f9cec3e3 100644 --- a/plugins/inputs/http_listener_v2/http_listener_v2_test.go +++ b/plugins/inputs/http_listener_v2/http_listener_v2_test.go @@ -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, } diff --git a/plugins/inputs/http_response/http_response.go b/plugins/inputs/http_response/http_response.go index 7ec46ea486ab0..d8a4e0e1438cd 100644 --- a/plugins/inputs/http_response/http_response.go +++ b/plugins/inputs/http_response/http_response.go @@ -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 == "" { diff --git a/plugins/inputs/http_response/http_response_test.go b/plugins/inputs/http_response/http_response_test.go index 4772024c569d1..557639027ff03 100644 --- a/plugins/inputs/http_response/http_response_test.go +++ b/plugins/inputs/http_response/http_response_test.go @@ -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", diff --git a/plugins/inputs/httpjson/httpjson.go b/plugins/inputs/httpjson/httpjson.go index 502a1473b9231..f5d97b90989c0 100644 --- a/plugins/inputs/httpjson/httpjson.go +++ b/plugins/inputs/httpjson/httpjson.go @@ -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), } }) } diff --git a/plugins/inputs/icinga2/icinga2.go b/plugins/inputs/icinga2/icinga2.go index 9dbf52f243e3f..17069e169c81b 100644 --- a/plugins/inputs/icinga2/icinga2.go +++ b/plugins/inputs/icinga2/icinga2.go @@ -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), } }) } diff --git a/plugins/inputs/influxdb/influxdb.go b/plugins/inputs/influxdb/influxdb.go index d7eb66153034a..b8c028f05aff8 100644 --- a/plugins/inputs/influxdb/influxdb.go +++ b/plugins/inputs/influxdb/influxdb.go @@ -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), } }) } diff --git a/plugins/inputs/influxdb_listener/influxdb_listener.go b/plugins/inputs/influxdb_listener/influxdb_listener.go index 269ba17d6fa67..6b5c67ea07999 100644 --- a/plugins/inputs/influxdb_listener/influxdb_listener.go +++ b/plugins/inputs/influxdb_listener/influxdb_listener.go @@ -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 diff --git a/plugins/inputs/influxdb_listener/influxdb_listener_benchmark_test.go b/plugins/inputs/influxdb_listener/influxdb_listener_benchmark_test.go index d3dc552192007..f0bfc695c98a3 100644 --- a/plugins/inputs/influxdb_listener/influxdb_listener_benchmark_test.go +++ b/plugins/inputs/influxdb_listener/influxdb_listener_benchmark_test.go @@ -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 } diff --git a/plugins/inputs/influxdb_listener/influxdb_listener_test.go b/plugins/inputs/influxdb_listener/influxdb_listener_test.go index 09c02fb7b0662..8a082a855a7f8 100644 --- a/plugins/inputs/influxdb_listener/influxdb_listener_test.go +++ b/plugins/inputs/influxdb_listener/influxdb_listener_test.go @@ -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, } diff --git a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go index ab1d83732c96a..64907d12a52dc 100644 --- a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go +++ b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener.go @@ -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 diff --git a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_benchmark_test.go b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_benchmark_test.go index e1e2c7090b359..219d59a93863e 100644 --- a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_benchmark_test.go +++ b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_benchmark_test.go @@ -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 } diff --git a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_test.go b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_test.go index 9d327b41bc377..be99c93f51a8a 100644 --- a/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_test.go +++ b/plugins/inputs/influxdb_v2_listener/influxdb_v2_listener_test.go @@ -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, } diff --git a/plugins/inputs/ipmi_sensor/ipmi.go b/plugins/inputs/ipmi_sensor/ipmi.go index 89ade652fbf55..c7f23dbc30e36 100644 --- a/plugins/inputs/ipmi_sensor/ipmi.go +++ b/plugins/inputs/ipmi_sensor/ipmi.go @@ -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 { diff --git a/plugins/inputs/ipmi_sensor/ipmi_test.go b/plugins/inputs/ipmi_sensor/ipmi_test.go index 80332abc0d924..cf53214dbbd66 100644 --- a/plugins/inputs/ipmi_sensor/ipmi_test.go +++ b/plugins/inputs/ipmi_sensor/ipmi_test.go @@ -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, } diff --git a/plugins/inputs/ipset/ipset.go b/plugins/inputs/ipset/ipset.go index e9f3ccabe1241..82854a35f44f3 100644 --- a/plugins/inputs/ipset/ipset.go +++ b/plugins/inputs/ipset/ipset.go @@ -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) } diff --git a/plugins/inputs/ipset/ipset_test.go b/plugins/inputs/ipset/ipset_test.go index 0480debe1bb4f..f205728c0dbad 100644 --- a/plugins/inputs/ipset/ipset_test.go +++ b/plugins/inputs/ipset/ipset_test.go @@ -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 }, } diff --git a/plugins/inputs/jenkins/jenkins.go b/plugins/inputs/jenkins/jenkins.go index fa5727ced32bc..6d764d175ce58 100644 --- a/plugins/inputs/jenkins/jenkins.go +++ b/plugins/inputs/jenkins/jenkins.go @@ -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, } diff --git a/plugins/inputs/jenkins/jenkins_test.go b/plugins/inputs/jenkins/jenkins_test.go index 833b36fcbd60d..b97da5a0f00a4 100644 --- a/plugins/inputs/jenkins/jenkins_test.go +++ b/plugins/inputs/jenkins/jenkins_test.go @@ -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{ "*", }, diff --git a/plugins/inputs/jolokia/jolokia.go b/plugins/inputs/jolokia/jolokia.go index 6e7a3d5a524fc..9e4cac511683b 100644 --- a/plugins/inputs/jolokia/jolokia.go +++ b/plugins/inputs/jolokia/jolokia.go @@ -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), }} } diff --git a/plugins/inputs/jolokia2/jolokia_agent.go b/plugins/inputs/jolokia2/jolokia_agent.go index 2489ac19ddc66..5b2e3da37c16e 100644 --- a/plugins/inputs/jolokia2/jolokia_agent.go +++ b/plugins/inputs/jolokia2/jolokia_agent.go @@ -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, }) } diff --git a/plugins/inputs/jolokia2/jolokia_proxy.go b/plugins/inputs/jolokia2/jolokia_proxy.go index 6428a88515aee..1f91e1cb911fe 100644 --- a/plugins/inputs/jolokia2/jolokia_proxy.go +++ b/plugins/inputs/jolokia2/jolokia_proxy.go @@ -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, }) diff --git a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go index ca087e12f6904..96dce5a88c7e7 100644 --- a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go +++ b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go @@ -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, } }) diff --git a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go index 99185e53d015d..8db4ce0d543bc 100644 --- a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go +++ b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go @@ -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{ diff --git a/plugins/inputs/kapacitor/kapacitor.go b/plugins/inputs/kapacitor/kapacitor.go index 073344ed41a93..b2e8da4cc0ef0 100644 --- a/plugins/inputs/kapacitor/kapacitor.go +++ b/plugins/inputs/kapacitor/kapacitor.go @@ -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), } }) } diff --git a/plugins/inputs/kibana/kibana.go b/plugins/inputs/kibana/kibana.go index 1626f78a25e1d..c94438eb38d4d 100644 --- a/plugins/inputs/kibana/kibana.go +++ b/plugins/inputs/kibana/kibana.go @@ -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 diff --git a/plugins/inputs/kube_inventory/kube_state.go b/plugins/inputs/kube_inventory/kube_state.go index 3aec920886f54..bcfae4ce8f52f 100644 --- a/plugins/inputs/kube_inventory/kube_state.go +++ b/plugins/inputs/kube_inventory/kube_state.go @@ -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{"*"}, diff --git a/plugins/inputs/kubernetes/kubernetes.go b/plugins/inputs/kubernetes/kubernetes.go index e4ebe268755ec..32bfc04a061e6 100644 --- a/plugins/inputs/kubernetes/kubernetes.go +++ b/plugins/inputs/kubernetes/kubernetes.go @@ -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) diff --git a/plugins/inputs/logstash/logstash.go b/plugins/inputs/logstash/logstash.go index c9833f028654d..76f75bc63a6a0 100644 --- a/plugins/inputs/logstash/logstash.go +++ b/plugins/inputs/logstash/logstash.go @@ -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 diff --git a/plugins/inputs/mcrouter/mcrouter.go b/plugins/inputs/mcrouter/mcrouter.go index b93044f1c1e6c..af197c3072089 100644 --- a/plugins/inputs/mcrouter/mcrouter.go +++ b/plugins/inputs/mcrouter/mcrouter.go @@ -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 { diff --git a/plugins/inputs/modbus/modbus.go b/plugins/inputs/modbus/modbus.go index d7c5b1d92f0c5..f4236c722f4cf 100644 --- a/plugins/inputs/modbus/modbus.go +++ b/plugins/inputs/modbus/modbus.go @@ -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 diff --git a/plugins/inputs/monit/monit.go b/plugins/inputs/monit/monit.go index a25efad58e723..1cb1a4ba57da9 100644 --- a/plugins/inputs/monit/monit.go +++ b/plugins/inputs/monit/monit.go @@ -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 } diff --git a/plugins/inputs/mqtt_consumer/mqtt_consumer.go b/plugins/inputs/mqtt_consumer/mqtt_consumer.go index 603b4228db5d1..815f27a727abf 100644 --- a/plugins/inputs/mqtt_consumer/mqtt_consumer.go +++ b/plugins/inputs/mqtt_consumer/mqtt_consumer.go @@ -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)) diff --git a/plugins/inputs/nats/nats.go b/plugins/inputs/nats/nats.go index 94e1ad74e1d69..53f688bb3bcd9 100644 --- a/plugins/inputs/nats/nats.go +++ b/plugins/inputs/nats/nats.go @@ -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 } diff --git a/plugins/inputs/neptune_apex/neptune_apex.go b/plugins/inputs/neptune_apex/neptune_apex.go index 8161ac7b4880a..dad4c8e5857f6 100644 --- a/plugins/inputs/neptune_apex/neptune_apex.go +++ b/plugins/inputs/neptune_apex/neptune_apex.go @@ -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 } diff --git a/plugins/inputs/net_response/net_response.go b/plugins/inputs/net_response/net_response.go index cb0e008f3d7c0..a7fcec4353c81 100644 --- a/plugins/inputs/net_response/net_response.go +++ b/plugins/inputs/net_response/net_response.go @@ -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 == "" { diff --git a/plugins/inputs/net_response/net_response_test.go b/plugins/inputs/net_response/net_response_test.go index 48e3d80dc23ef..34a7992e3ddf1 100644 --- a/plugins/inputs/net_response/net_response_test.go +++ b/plugins/inputs/net_response/net_response_test.go @@ -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 diff --git a/plugins/inputs/nginx/nginx.go b/plugins/inputs/nginx/nginx.go index a3aa3b7e5356a..5e15022708682 100644 --- a/plugins/inputs/nginx/nginx.go +++ b/plugins/inputs/nginx/nginx.go @@ -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 diff --git a/plugins/inputs/nginx_plus/nginx_plus.go b/plugins/inputs/nginx_plus/nginx_plus.go index d41c03c801a96..32a8516986f64 100644 --- a/plugins/inputs/nginx_plus/nginx_plus.go +++ b/plugins/inputs/nginx_plus/nginx_plus.go @@ -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 diff --git a/plugins/inputs/nginx_plus_api/nginx_plus_api.go b/plugins/inputs/nginx_plus_api/nginx_plus_api.go index b2ab91762ae58..09fe3fca3cb01 100644 --- a/plugins/inputs/nginx_plus_api/nginx_plus_api.go +++ b/plugins/inputs/nginx_plus_api/nginx_plus_api.go @@ -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 diff --git a/plugins/inputs/nginx_sts/nginx_sts.go b/plugins/inputs/nginx_sts/nginx_sts.go index 046460069c65d..d3e9118577f6f 100644 --- a/plugins/inputs/nginx_sts/nginx_sts.go +++ b/plugins/inputs/nginx_sts/nginx_sts.go @@ -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 diff --git a/plugins/inputs/nginx_upstream_check/nginx_upstream_check.go b/plugins/inputs/nginx_upstream_check/nginx_upstream_check.go index da2f7b08f989c..fb40643409056 100644 --- a/plugins/inputs/nginx_upstream_check/nginx_upstream_check.go +++ b/plugins/inputs/nginx_upstream_check/nginx_upstream_check.go @@ -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 diff --git a/plugins/inputs/nginx_vts/nginx_vts.go b/plugins/inputs/nginx_vts/nginx_vts.go index 57453c0b4e3b0..bca7c62db9b83 100644 --- a/plugins/inputs/nginx_vts/nginx_vts.go +++ b/plugins/inputs/nginx_vts/nginx_vts.go @@ -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 diff --git a/plugins/inputs/nsd/nsd.go b/plugins/inputs/nsd/nsd.go index ef6c20a9aad4c..f75f700eaa2f9 100644 --- a/plugins/inputs/nsd/nsd.go +++ b/plugins/inputs/nsd/nsd.go @@ -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) } diff --git a/plugins/inputs/nsd/nsd_test.go b/plugins/inputs/nsd/nsd_test.go index 67ea6863c5208..d64cad7dcea63 100644 --- a/plugins/inputs/nsd/nsd_test.go +++ b/plugins/inputs/nsd/nsd_test.go @@ -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 } } diff --git a/plugins/inputs/nvidia_smi/nvidia_smi.go b/plugins/inputs/nvidia_smi/nvidia_smi.go index f1ebfa38babb9..3e4fb03f04221 100644 --- a/plugins/inputs/nvidia_smi/nvidia_smi.go +++ b/plugins/inputs/nvidia_smi/nvidia_smi.go @@ -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 } diff --git a/plugins/inputs/openntpd/openntpd.go b/plugins/inputs/openntpd/openntpd.go index b4a35fb55b8d7..2689c9cc7c845 100644 --- a/plugins/inputs/openntpd/openntpd.go +++ b/plugins/inputs/openntpd/openntpd.go @@ -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) } diff --git a/plugins/inputs/openntpd/openntpd_test.go b/plugins/inputs/openntpd/openntpd_test.go index f9823e355f69a..f26419a71101e 100644 --- a/plugins/inputs/openntpd/openntpd_test.go +++ b/plugins/inputs/openntpd/openntpd_test.go @@ -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 } } diff --git a/plugins/inputs/opensmtpd/opensmtpd.go b/plugins/inputs/opensmtpd/opensmtpd.go index 47850db09f012..9ce6ec5421ff1 100644 --- a/plugins/inputs/opensmtpd/opensmtpd.go +++ b/plugins/inputs/opensmtpd/opensmtpd.go @@ -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) } diff --git a/plugins/inputs/opensmtpd/opensmtpd_test.go b/plugins/inputs/opensmtpd/opensmtpd_test.go index 4ae3eb9868d40..fb3afa82e0171 100644 --- a/plugins/inputs/opensmtpd/opensmtpd_test.go +++ b/plugins/inputs/opensmtpd/opensmtpd_test.go @@ -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 } } diff --git a/plugins/inputs/openweathermap/openweathermap.go b/plugins/inputs/openweathermap/openweathermap.go index 426d412d09114..fcc22343b435e 100644 --- a/plugins/inputs/openweathermap/openweathermap.go +++ b/plugins/inputs/openweathermap/openweathermap.go @@ -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, diff --git a/plugins/inputs/pgbouncer/pgbouncer.go b/plugins/inputs/pgbouncer/pgbouncer.go index 24a7f1e8fb7d2..2547a617e14d7 100644 --- a/plugins/inputs/pgbouncer/pgbouncer.go +++ b/plugins/inputs/pgbouncer/pgbouncer.go @@ -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, }, } diff --git a/plugins/inputs/phpfpm/phpfpm.go b/plugins/inputs/phpfpm/phpfpm.go index cc326c3b55577..77c4bf0aeee56 100644 --- a/plugins/inputs/phpfpm/phpfpm.go +++ b/plugins/inputs/phpfpm/phpfpm.go @@ -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 } diff --git a/plugins/inputs/postgresql/postgresql.go b/plugins/inputs/postgresql/postgresql.go index 3ce8963e90c3e..1f1c22dc00e21 100644 --- a/plugins/inputs/postgresql/postgresql.go +++ b/plugins/inputs/postgresql/postgresql.go @@ -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, }, } diff --git a/plugins/inputs/postgresql/service.go b/plugins/inputs/postgresql/service.go index d4be13ee7bca2..db4438e416939 100644 --- a/plugins/inputs/postgresql/service.go +++ b/plugins/inputs/postgresql/service.go @@ -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 } diff --git a/plugins/inputs/postgresql_extensible/postgresql_extensible.go b/plugins/inputs/postgresql_extensible/postgresql_extensible.go index ceb6c0be5fe9c..ef66c26cf9e7e 100644 --- a/plugins/inputs/postgresql_extensible/postgresql_extensible.go +++ b/plugins/inputs/postgresql_extensible/postgresql_extensible.go @@ -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, }, } diff --git a/plugins/inputs/prometheus/prometheus.go b/plugins/inputs/prometheus/prometheus.go index 319f96a69b70c..cc894fc7a7f8d 100644 --- a/plugins/inputs/prometheus/prometheus.go +++ b/plugins/inputs/prometheus/prometheus.go @@ -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", } diff --git a/plugins/inputs/proxmox/proxmox.go b/plugins/inputs/proxmox/proxmox.go index a66aa5286fac8..ec34a7b2f5a36 100644 --- a/plugins/inputs/proxmox/proxmox.go +++ b/plugins/inputs/proxmox/proxmox.go @@ -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 diff --git a/plugins/inputs/proxmox/structs.go b/plugins/inputs/proxmox/structs.go index ef207693e4b5f..c064150c061f6 100644 --- a/plugins/inputs/proxmox/structs.go +++ b/plugins/inputs/proxmox/structs.go @@ -6,15 +6,15 @@ import ( "net/url" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/common/tls" ) type Proxmox struct { - BaseURL string `toml:"base_url"` - APIToken string `toml:"api_token"` - ResponseTimeout internal.Duration `toml:"response_timeout"` - NodeName string `toml:"node_name"` + BaseURL string `toml:"base_url"` + APIToken string `toml:"api_token"` + ResponseTimeout config.Duration `toml:"response_timeout"` + NodeName string `toml:"node_name"` tls.ClientConfig diff --git a/plugins/inputs/rabbitmq/rabbitmq.go b/plugins/inputs/rabbitmq/rabbitmq.go index fa92fc744f97f..fd39bd090dbc5 100644 --- a/plugins/inputs/rabbitmq/rabbitmq.go +++ b/plugins/inputs/rabbitmq/rabbitmq.go @@ -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" ) @@ -40,8 +40,8 @@ type RabbitMQ struct { Password string `toml:"password"` tls.ClientConfig - ResponseHeaderTimeout internal.Duration `toml:"header_timeout"` - ClientTimeout internal.Duration `toml:"client_timeout"` + ResponseHeaderTimeout config.Duration `toml:"header_timeout"` + ClientTimeout config.Duration `toml:"client_timeout"` Nodes []string `toml:"nodes"` Queues []string `toml:"queues"` @@ -331,12 +331,12 @@ func (r *RabbitMQ) Gather(acc telegraf.Accumulator) error { return err } tr := &http.Transport{ - ResponseHeaderTimeout: r.ResponseHeaderTimeout.Duration, + ResponseHeaderTimeout: time.Duration(r.ResponseHeaderTimeout), TLSClientConfig: tlsCfg, } r.Client = &http.Client{ Transport: tr, - Timeout: r.ClientTimeout.Duration, + Timeout: time.Duration(r.ClientTimeout), } } @@ -762,8 +762,8 @@ func (r *RabbitMQ) shouldGatherFederationLink(link FederationLink) bool { func init() { inputs.Add("rabbitmq", func() telegraf.Input { return &RabbitMQ{ - ResponseHeaderTimeout: internal.Duration{Duration: DefaultResponseHeaderTimeout * time.Second}, - ClientTimeout: internal.Duration{Duration: DefaultClientTimeout * time.Second}, + ResponseHeaderTimeout: config.Duration(DefaultResponseHeaderTimeout * time.Second), + ClientTimeout: config.Duration(DefaultClientTimeout * time.Second), } }) } diff --git a/plugins/inputs/ravendb/ravendb.go b/plugins/inputs/ravendb/ravendb.go index f246bd8e97689..efc1b9517cc24 100644 --- a/plugins/inputs/ravendb/ravendb.go +++ b/plugins/inputs/ravendb/ravendb.go @@ -10,7 +10,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" @@ -28,7 +28,7 @@ type RavenDB struct { URL string `toml:"url"` Name string `toml:"name"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` StatsInclude []string `toml:"stats_include"` DbStatsDbs []string `toml:"db_stats_dbs"` @@ -133,12 +133,12 @@ func (r *RavenDB) ensureClient() error { return err } tr := &http.Transport{ - ResponseHeaderTimeout: r.Timeout.Duration, + ResponseHeaderTimeout: time.Duration(r.Timeout), TLSClientConfig: tlsCfg, } r.client = &http.Client{ Transport: tr, - Timeout: r.Timeout.Duration, + Timeout: time.Duration(r.Timeout), } return nil @@ -418,7 +418,7 @@ func (r *RavenDB) Init() error { func init() { inputs.Add("ravendb", func() telegraf.Input { return &RavenDB{ - Timeout: internal.Duration{Duration: defaultTimeout * time.Second}, + Timeout: config.Duration(defaultTimeout * time.Second), StatsInclude: []string{"server", "databases", "indexes", "collections"}, } }) diff --git a/plugins/inputs/riemann_listener/riemann_listener.go b/plugins/inputs/riemann_listener/riemann_listener.go index 5c075017a8430..b20094176ceb8 100644 --- a/plugins/inputs/riemann_listener/riemann_listener.go +++ b/plugins/inputs/riemann_listener/riemann_listener.go @@ -19,7 +19,7 @@ import ( "github.com/gogo/protobuf/proto" "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" riemanngo "github.com/riemann/riemann-go-client" @@ -27,12 +27,12 @@ import ( ) type RiemannSocketListener struct { - ServiceAddress string `toml:"service_address"` - MaxConnections int `toml:"max_connections"` - ReadBufferSize internal.Size `toml:"read_buffer_size"` - ReadTimeout *internal.Duration `toml:"read_timeout"` - KeepAlivePeriod *internal.Duration `toml:"keep_alive_period"` - SocketMode string `toml:"socket_mode"` + ServiceAddress string `toml:"service_address"` + MaxConnections int `toml:"max_connections"` + ReadBufferSize config.Size `toml:"read_buffer_size"` + ReadTimeout *config.Duration `toml:"read_timeout"` + KeepAlivePeriod *config.Duration `toml:"keep_alive_period"` + SocketMode string `toml:"socket_mode"` tlsint.ServerConfig wg sync.WaitGroup @@ -75,9 +75,9 @@ func (rsl *riemannListener) listen(ctx context.Context) { break } - if rsl.ReadBufferSize.Size > 0 { + if rsl.ReadBufferSize > 0 { if srb, ok := c.(setReadBufferer); ok { - if err := srb.SetReadBuffer(int(rsl.ReadBufferSize.Size)); err != nil { + if err := srb.SetReadBuffer(int(rsl.ReadBufferSize)); err != nil { rsl.Log.Warnf("Setting read buffer failed: %v", err) } } else { @@ -129,13 +129,13 @@ func (rsl *riemannListener) setKeepAlive(c net.Conn) error { if !ok { return fmt.Errorf("cannot set keep alive on a %s socket", strings.SplitN(rsl.ServiceAddress, "://", 2)[0]) } - if rsl.KeepAlivePeriod.Duration == 0 { + if *rsl.KeepAlivePeriod == 0 { return tcpc.SetKeepAlive(false) } if err := tcpc.SetKeepAlive(true); err != nil { return err } - return tcpc.SetKeepAlivePeriod(rsl.KeepAlivePeriod.Duration) + return tcpc.SetKeepAlivePeriod(time.Duration(*rsl.KeepAlivePeriod)) } func (rsl *riemannListener) removeConnection(c net.Conn) { @@ -175,8 +175,8 @@ func (rsl *riemannListener) read(conn net.Conn) { var err error for { - if rsl.ReadTimeout != nil && rsl.ReadTimeout.Duration > 0 { - if err := conn.SetDeadline(time.Now().Add(rsl.ReadTimeout.Duration)); err != nil { + if rsl.ReadTimeout != nil && *rsl.ReadTimeout > 0 { + if err := conn.SetDeadline(time.Now().Add(time.Duration(*rsl.ReadTimeout))); err != nil { rsl.Log.Warnf("Setting deadline failed: %v", err) } } diff --git a/plugins/inputs/riemann_listener/riemann_listener_test.go b/plugins/inputs/riemann_listener/riemann_listener_test.go index 92af46e8afd03..92dc829ac1312 100644 --- a/plugins/inputs/riemann_listener/riemann_listener_test.go +++ b/plugins/inputs/riemann_listener/riemann_listener_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" riemanngo "github.com/riemann/riemann-go-client" "github.com/stretchr/testify/require" @@ -18,7 +18,7 @@ func TestSocketListener_tcp(t *testing.T) { sl := newRiemannSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "tcp://127.0.0.1:5555" - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) acc := &testutil.Accumulator{} err := sl.Start(acc) diff --git a/plugins/inputs/sensors/sensors.go b/plugins/inputs/sensors/sensors.go index 01fd2a45af6ee..d3a8ba762f379 100644 --- a/plugins/inputs/sensors/sensors.go +++ b/plugins/inputs/sensors/sensors.go @@ -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" ) @@ -19,12 +20,12 @@ import ( var ( execCommand = exec.Command // execCommand is used to mock commands in tests. numberRegp = regexp.MustCompile("[0-9]+") - defaultTimeout = internal.Duration{Duration: 5 * time.Second} + defaultTimeout = config.Duration(5 * time.Second) ) type Sensors struct { - RemoveNumbers bool `toml:"remove_numbers"` - Timeout internal.Duration `toml:"timeout"` + RemoveNumbers bool `toml:"remove_numbers"` + Timeout config.Duration `toml:"timeout"` path string } @@ -59,7 +60,7 @@ func (s *Sensors) parse(acc telegraf.Accumulator) error { fields := map[string]interface{}{} chip := "" cmd := execCommand(s.path, "-A", "-u") - out, err := internal.StdOutputTimeout(cmd, s.Timeout.Duration) + out, err := internal.StdOutputTimeout(cmd, time.Duration(s.Timeout)) if err != nil { return fmt.Errorf("failed to run command %s: %s - %s", strings.Join(cmd.Args, " "), err, string(out)) } diff --git a/plugins/inputs/sflow/sflow.go b/plugins/inputs/sflow/sflow.go index 45578d5396cc3..3b18409c13a77 100644 --- a/plugins/inputs/sflow/sflow.go +++ b/plugins/inputs/sflow/sflow.go @@ -10,7 +10,7 @@ import ( "sync" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/inputs" ) @@ -31,8 +31,8 @@ const ( ) type SFlow struct { - ServiceAddress string `toml:"service_address"` - ReadBufferSize internal.Size `toml:"read_buffer_size"` + ServiceAddress string `toml:"service_address"` + ReadBufferSize config.Size `toml:"read_buffer_size"` Log telegraf.Logger `toml:"-"` @@ -83,8 +83,8 @@ func (s *SFlow) Start(acc telegraf.Accumulator) error { s.closer = conn s.addr = conn.LocalAddr() - if s.ReadBufferSize.Size > 0 { - if err := conn.SetReadBuffer(int(s.ReadBufferSize.Size)); err != nil { + if s.ReadBufferSize > 0 { + if err := conn.SetReadBuffer(int(s.ReadBufferSize)); err != nil { return err } } diff --git a/plugins/inputs/smart/smart.go b/plugins/inputs/smart/smart.go index 121edb0acf71b..4533ea768432d 100644 --- a/plugins/inputs/smart/smart.go +++ b/plugins/inputs/smart/smart.go @@ -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/inputs" ) @@ -268,17 +269,17 @@ var ( // Smart plugin reads metrics from storage devices supporting S.M.A.R.T. type Smart struct { - Path string `toml:"path"` //deprecated - to keep backward compatibility - PathSmartctl string `toml:"path_smartctl"` - PathNVMe string `toml:"path_nvme"` - Nocheck string `toml:"nocheck"` - EnableExtensions []string `toml:"enable_extensions"` - Attributes bool `toml:"attributes"` - Excludes []string `toml:"excludes"` - Devices []string `toml:"devices"` - UseSudo bool `toml:"use_sudo"` - Timeout internal.Duration `toml:"timeout"` - Log telegraf.Logger `toml:"-"` + Path string `toml:"path"` //deprecated - to keep backward compatibility + PathSmartctl string `toml:"path_smartctl"` + PathNVMe string `toml:"path_nvme"` + Nocheck string `toml:"nocheck"` + EnableExtensions []string `toml:"enable_extensions"` + Attributes bool `toml:"attributes"` + Excludes []string `toml:"excludes"` + Devices []string `toml:"devices"` + UseSudo bool `toml:"use_sudo"` + Timeout config.Duration `toml:"timeout"` + Log telegraf.Logger `toml:"-"` } type nvmeDevice struct { @@ -332,7 +333,7 @@ var sampleConfig = ` func newSmart() *Smart { return &Smart{ - Timeout: internal.Duration{Duration: time.Second * 30}, + Timeout: config.Duration(time.Second * 30), } } @@ -477,12 +478,12 @@ func (m *Smart) scanDevices(ignoreExcludes bool, scanArgs ...string) ([]string, } // Wrap with sudo -var runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { +var runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { cmd := exec.Command(command, args...) if sudo { cmd = exec.Command("sudo", append([]string{"-n", command}, args...)...) } - return internal.CombinedOutputTimeout(cmd, timeout.Duration) + return internal.CombinedOutputTimeout(cmd, time.Duration(timeout)) } func excludedDev(excludes []string, deviceLine string) bool { @@ -529,7 +530,7 @@ func (m *Smart) getVendorNVMeAttributes(acc telegraf.Accumulator, devices []stri wg.Wait() } -func getDeviceInfoForNVMeDisks(acc telegraf.Accumulator, devices []string, nvme string, timeout internal.Duration, useSudo bool) []nvmeDevice { +func getDeviceInfoForNVMeDisks(acc telegraf.Accumulator, devices []string, nvme string, timeout config.Duration, useSudo bool) []nvmeDevice { var NVMeDevices []nvmeDevice for _, device := range devices { @@ -549,7 +550,7 @@ func getDeviceInfoForNVMeDisks(acc telegraf.Accumulator, devices []string, nvme return NVMeDevices } -func gatherNVMeDeviceInfo(nvme, device string, timeout internal.Duration, useSudo bool) (string, string, string, error) { +func gatherNVMeDeviceInfo(nvme, device string, timeout config.Duration, useSudo bool) (string, string, string, error) { args := []string{"id-ctrl"} args = append(args, strings.Split(device, " ")...) out, err := runCmd(timeout, useSudo, nvme, args...) @@ -589,7 +590,7 @@ func findNVMeDeviceInfo(output string) (string, string, string, error) { return vid, sn, mn, nil } -func gatherIntelNVMeDisk(acc telegraf.Accumulator, timeout internal.Duration, usesudo bool, nvme string, device nvmeDevice, wg *sync.WaitGroup) { +func gatherIntelNVMeDisk(acc telegraf.Accumulator, timeout config.Duration, usesudo bool, nvme string, device nvmeDevice, wg *sync.WaitGroup) { defer wg.Done() args := []string{"intel", "smart-log-add"} @@ -636,7 +637,7 @@ func gatherIntelNVMeDisk(acc telegraf.Accumulator, timeout internal.Duration, us } } -func gatherDisk(acc telegraf.Accumulator, timeout internal.Duration, usesudo, collectAttributes bool, smartctl, nocheck, device string, wg *sync.WaitGroup) { +func gatherDisk(acc telegraf.Accumulator, timeout config.Duration, usesudo, collectAttributes bool, smartctl, nocheck, device string, wg *sync.WaitGroup) { defer wg.Done() // smartctl 5.41 & 5.42 have are broken regarding handling of --nocheck/-n args := []string{"--info", "--health", "--attributes", "--tolerance=verypermissive", "-n", nocheck, "--format=brief"} diff --git a/plugins/inputs/smart/smart_test.go b/plugins/inputs/smart/smart_test.go index e82307d391565..5a1799381cebe 100644 --- a/plugins/inputs/smart/smart_test.go +++ b/plugins/inputs/smart/smart_test.go @@ -7,7 +7,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/assert" "github.com/stretchr/testify/require" @@ -17,9 +17,9 @@ func TestGatherAttributes(t *testing.T) { s := newSmart() s.Attributes = true - assert.Equal(t, time.Second*30, s.Timeout.Duration) + assert.Equal(t, time.Second*30, time.Duration(s.Timeout)) - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { if len(args) > 0 { if args[0] == "--info" && args[7] == "/dev/ada0" { return []byte(mockInfoAttributeData), nil @@ -81,9 +81,9 @@ func TestGatherNoAttributes(t *testing.T) { s := newSmart() s.Attributes = false - assert.Equal(t, time.Second*30, s.Timeout.Duration) + assert.Equal(t, time.Second*30, time.Duration(s.Timeout)) - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { if len(args) > 0 { if args[0] == "--scan" && len(args) == 1 { return []byte(mockScanData), nil @@ -124,7 +124,7 @@ func TestExcludedDev(t *testing.T) { } func TestGatherSATAInfo(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(hgstSATAInfoData), nil } @@ -134,13 +134,13 @@ func TestGatherSATAInfo(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) assert.Equal(t, 101, acc.NFields(), "Wrong number of fields gathered") assert.Equal(t, uint64(20), acc.NMetrics(), "Wrong number of metrics gathered") } func TestGatherSATAInfo65(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(hgstSATAInfoData65), nil } @@ -150,13 +150,13 @@ func TestGatherSATAInfo65(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) assert.Equal(t, 91, acc.NFields(), "Wrong number of fields gathered") assert.Equal(t, uint64(18), acc.NMetrics(), "Wrong number of metrics gathered") } func TestGatherHgstSAS(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(hgstSASInfoData), nil } @@ -166,13 +166,13 @@ func TestGatherHgstSAS(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) assert.Equal(t, 6, acc.NFields(), "Wrong number of fields gathered") assert.Equal(t, uint64(4), acc.NMetrics(), "Wrong number of metrics gathered") } func TestGatherHtSAS(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(htSASInfoData), nil } @@ -182,13 +182,13 @@ func TestGatherHtSAS(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) testutil.RequireMetricsEqual(t, testHtsasAtributtes, acc.GetTelegrafMetrics(), testutil.SortMetrics(), testutil.IgnoreTime()) } func TestGatherSSD(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(ssdInfoData), nil } @@ -198,13 +198,13 @@ func TestGatherSSD(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) assert.Equal(t, 105, acc.NFields(), "Wrong number of fields gathered") assert.Equal(t, uint64(26), acc.NMetrics(), "Wrong number of metrics gathered") } func TestGatherSSDRaid(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(ssdRaidInfoData), nil } @@ -214,13 +214,13 @@ func TestGatherSSDRaid(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "", wg) assert.Equal(t, 74, acc.NFields(), "Wrong number of fields gathered") assert.Equal(t, uint64(15), acc.NMetrics(), "Wrong number of metrics gathered") } func TestGatherNvme(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(smartctlNvmeInfoData), nil } @@ -230,14 +230,14 @@ func TestGatherNvme(t *testing.T) { ) wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "nvme0", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "nvme0", wg) testutil.RequireMetricsEqual(t, testSmartctlNvmeAttributes, acc.GetTelegrafMetrics(), testutil.SortMetrics(), testutil.IgnoreTime()) } func TestGatherIntelNvme(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(nvmeIntelInfoData), nil } @@ -252,7 +252,7 @@ func TestGatherIntelNvme(t *testing.T) { ) wg.Add(1) - gatherIntelNVMeDisk(acc, internal.Duration{Duration: time.Second * 30}, true, "", device, wg) + gatherIntelNVMeDisk(acc, config.Duration(time.Second*30), true, "", device, wg) result := acc.GetTelegrafMetrics() testutil.RequireMetricsEqual(t, testIntelInvmeAttributes, result, @@ -292,7 +292,7 @@ func Test_difference(t *testing.T) { } func Test_integerOverflow(t *testing.T) { - runCmd = func(timeout internal.Duration, sudo bool, command string, args ...string) ([]byte, error) { + runCmd = func(timeout config.Duration, sudo bool, command string, args ...string) ([]byte, error) { return []byte(smartctlNvmeInfoDataWithOverflow), nil } @@ -303,7 +303,7 @@ func Test_integerOverflow(t *testing.T) { t.Run("If data raw_value is out of int64 range, there should be no metrics for that attribute", func(t *testing.T) { wg.Add(1) - gatherDisk(acc, internal.Duration{Duration: time.Second * 30}, true, true, "", "", "nvme0", wg) + gatherDisk(acc, config.Duration(time.Second*30), true, true, "", "", "nvme0", wg) result := acc.GetTelegrafMetrics() testutil.RequireMetricsEqual(t, testOverflowAttributes, result, diff --git a/plugins/inputs/snmp/snmp.go b/plugins/inputs/snmp/snmp.go index 8f88211d56924..325121be4d1a8 100644 --- a/plugins/inputs/snmp/snmp.go +++ b/plugins/inputs/snmp/snmp.go @@ -16,7 +16,7 @@ import ( "github.com/gosnmp/gosnmp" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal/snmp" "github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/wlog" @@ -26,7 +26,7 @@ const description = `Retrieves SNMP values from remote agents` const sampleConfig = ` ## Agent addresses to retrieve values from. ## format: agents = [":"] - ## scheme: optional, either udp, udp4, udp6, tcp, tcp4, tcp6. + ## scheme: optional, either udp, udp4, udp6, tcp, tcp4, tcp6. ## default is udp ## port: optional ## example: agents = ["udp://127.0.0.1:161"] @@ -314,7 +314,7 @@ func init() { ClientConfig: snmp.ClientConfig{ Retries: 3, MaxRepetitions: 10, - Timeout: internal.Duration{Duration: 5 * time.Second}, + Timeout: config.Duration(5 * time.Second), Version: 2, Community: "public", }, diff --git a/plugins/inputs/snmp/snmp_test.go b/plugins/inputs/snmp/snmp_test.go index b589a60f72969..ef849f07b138c 100644 --- a/plugins/inputs/snmp/snmp_test.go +++ b/plugins/inputs/snmp/snmp_test.go @@ -10,9 +10,8 @@ import ( "time" "github.com/gosnmp/gosnmp" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal/snmp" - config "github.com/influxdata/telegraf/internal/snmp" "github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/testutil" "github.com/influxdata/toml" @@ -93,8 +92,8 @@ func TestSampleConfig(t *testing.T) { expected := &Snmp{ Agents: []string{"udp://127.0.0.1:161"}, AgentHostTag: "", - ClientConfig: config.ClientConfig{ - Timeout: internal.Duration{Duration: 5 * time.Second}, + ClientConfig: snmp.ClientConfig{ + Timeout: config.Duration(5 * time.Second), Version: 2, Community: "public", MaxRepetitions: 10, @@ -239,8 +238,8 @@ func TestSnmpInit_noTranslate(t *testing.T) { func TestGetSNMPConnection_v2(t *testing.T) { s := &Snmp{ Agents: []string{"1.2.3.4:567", "1.2.3.4", "udp://127.0.0.1"}, - ClientConfig: config.ClientConfig{ - Timeout: internal.Duration{Duration: 3 * time.Second}, + ClientConfig: snmp.ClientConfig{ + Timeout: config.Duration(3 * time.Second), Retries: 4, Version: 2, Community: "foo", @@ -308,7 +307,7 @@ func stubTCPServer(wg *sync.WaitGroup) { func TestGetSNMPConnection_v3(t *testing.T) { s := &Snmp{ Agents: []string{"1.2.3.4"}, - ClientConfig: config.ClientConfig{ + ClientConfig: snmp.ClientConfig{ Version: 3, MaxRepetitions: 20, ContextName: "mycontext", @@ -356,7 +355,7 @@ func TestGetSNMPConnection_v3_blumenthal(t *testing.T) { Algorithm: gosnmp.AES192, Config: &Snmp{ Agents: []string{"1.2.3.4"}, - ClientConfig: config.ClientConfig{ + ClientConfig: snmp.ClientConfig{ Version: 3, MaxRepetitions: 20, ContextName: "mycontext", @@ -377,7 +376,7 @@ func TestGetSNMPConnection_v3_blumenthal(t *testing.T) { Algorithm: gosnmp.AES192C, Config: &Snmp{ Agents: []string{"1.2.3.4"}, - ClientConfig: config.ClientConfig{ + ClientConfig: snmp.ClientConfig{ Version: 3, MaxRepetitions: 20, ContextName: "mycontext", @@ -398,7 +397,7 @@ func TestGetSNMPConnection_v3_blumenthal(t *testing.T) { Algorithm: gosnmp.AES256, Config: &Snmp{ Agents: []string{"1.2.3.4"}, - ClientConfig: config.ClientConfig{ + ClientConfig: snmp.ClientConfig{ Version: 3, MaxRepetitions: 20, ContextName: "mycontext", @@ -419,7 +418,7 @@ func TestGetSNMPConnection_v3_blumenthal(t *testing.T) { Algorithm: gosnmp.AES256C, Config: &Snmp{ Agents: []string{"1.2.3.4"}, - ClientConfig: config.ClientConfig{ + ClientConfig: snmp.ClientConfig{ Version: 3, MaxRepetitions: 20, ContextName: "mycontext", diff --git a/plugins/inputs/snmp_trap/snmp_trap.go b/plugins/inputs/snmp_trap/snmp_trap.go index b02483af768c1..acc97790855e4 100644 --- a/plugins/inputs/snmp_trap/snmp_trap.go +++ b/plugins/inputs/snmp_trap/snmp_trap.go @@ -12,16 +12,17 @@ import ( "time" "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/inputs" "github.com/soniah/gosnmp" ) -var defaultTimeout = internal.Duration{Duration: time.Second * 5} +var defaultTimeout = config.Duration(time.Second * 5) type handler func(*gosnmp.SnmpPacket, *net.UDPAddr) -type execer func(internal.Duration, string, ...string) ([]byte, error) +type execer func(config.Duration, string, ...string) ([]byte, error) type mibEntry struct { mibName string @@ -29,9 +30,9 @@ type mibEntry struct { } type SnmpTrap struct { - ServiceAddress string `toml:"service_address"` - Timeout internal.Duration `toml:"timeout"` - Version string `toml:"version"` + ServiceAddress string `toml:"service_address"` + Timeout config.Duration `toml:"timeout"` + Version string `toml:"version"` // Settings for version 3 // Values: "noAuthNoPriv", "authNoPriv", "authPriv" @@ -111,11 +112,11 @@ func init() { }) } -func realExecCmd(timeout internal.Duration, arg0 string, args ...string) ([]byte, error) { +func realExecCmd(timeout config.Duration, arg0 string, args ...string) ([]byte, error) { cmd := exec.Command(arg0, args...) var out bytes.Buffer cmd.Stdout = &out - err := internal.RunTimeout(cmd, timeout.Duration) + err := internal.RunTimeout(cmd, time.Duration(timeout)) if err != nil { return nil, err } diff --git a/plugins/inputs/snmp_trap/snmp_trap_test.go b/plugins/inputs/snmp_trap/snmp_trap_test.go index 87938e9837790..062c2cf1fe153 100644 --- a/plugins/inputs/snmp_trap/snmp_trap_test.go +++ b/plugins/inputs/snmp_trap/snmp_trap_test.go @@ -11,7 +11,7 @@ import ( "github.com/soniah/gosnmp" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/require" @@ -36,7 +36,7 @@ func TestLoad(t *testing.T) { require.Equal(t, "coldStart", e.oidText) } -func fakeExecCmd(_ internal.Duration, x string, y ...string) ([]byte, error) { +func fakeExecCmd(_ config.Duration, x string, y ...string) ([]byte, error) { return nil, fmt.Errorf("mock " + x + " " + strings.Join(y, " ")) } diff --git a/plugins/inputs/socket_listener/socket_listener.go b/plugins/inputs/socket_listener/socket_listener.go index 4ffa01a3440a8..362316ee5c468 100644 --- a/plugins/inputs/socket_listener/socket_listener.go +++ b/plugins/inputs/socket_listener/socket_listener.go @@ -13,6 +13,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" @@ -47,9 +48,9 @@ func (ssl *streamSocketListener) listen() { break } - if ssl.ReadBufferSize.Size > 0 { + if ssl.ReadBufferSize > 0 { if srb, ok := c.(setReadBufferer); ok { - if err := srb.SetReadBuffer(int(ssl.ReadBufferSize.Size)); err != nil { + if err := srb.SetReadBuffer(int(ssl.ReadBufferSize)); err != nil { ssl.Log.Error(err.Error()) break } @@ -99,13 +100,13 @@ func (ssl *streamSocketListener) setKeepAlive(c net.Conn) error { if !ok { return fmt.Errorf("cannot set keep alive on a %s socket", strings.SplitN(ssl.ServiceAddress, "://", 2)[0]) } - if ssl.KeepAlivePeriod.Duration == 0 { + if *ssl.KeepAlivePeriod == 0 { return tcpc.SetKeepAlive(false) } if err := tcpc.SetKeepAlive(true); err != nil { return err } - return tcpc.SetKeepAlivePeriod(ssl.KeepAlivePeriod.Duration) + return tcpc.SetKeepAlivePeriod(time.Duration(*ssl.KeepAlivePeriod)) } func (ssl *streamSocketListener) removeConnection(c net.Conn) { @@ -126,8 +127,8 @@ func (ssl *streamSocketListener) read(c net.Conn) { scnr := bufio.NewScanner(decoder) for { - if ssl.ReadTimeout != nil && ssl.ReadTimeout.Duration > 0 { - if err := c.SetReadDeadline(time.Now().Add(ssl.ReadTimeout.Duration)); err != nil { + if ssl.ReadTimeout != nil && *ssl.ReadTimeout > 0 { + if err := c.SetReadDeadline(time.Now().Add(time.Duration(*ssl.ReadTimeout))); err != nil { ssl.Log.Error("setting read deadline failed: %v", err) return } @@ -193,13 +194,13 @@ func (psl *packetSocketListener) listen() { } type SocketListener struct { - ServiceAddress string `toml:"service_address"` - MaxConnections int `toml:"max_connections"` - ReadBufferSize internal.Size `toml:"read_buffer_size"` - ReadTimeout *internal.Duration `toml:"read_timeout"` - KeepAlivePeriod *internal.Duration `toml:"keep_alive_period"` - SocketMode string `toml:"socket_mode"` - ContentEncoding string `toml:"content_encoding"` + ServiceAddress string `toml:"service_address"` + MaxConnections int `toml:"max_connections"` + ReadBufferSize config.Size `toml:"read_buffer_size"` + ReadTimeout *config.Duration `toml:"read_timeout"` + KeepAlivePeriod *config.Duration `toml:"keep_alive_period"` + SocketMode string `toml:"socket_mode"` + ContentEncoding string `toml:"content_encoding"` tlsint.ServerConfig wg sync.WaitGroup @@ -372,9 +373,9 @@ func (sl *SocketListener) Start(acc telegraf.Accumulator) error { } } - if sl.ReadBufferSize.Size > 0 { + if sl.ReadBufferSize > 0 { if srb, ok := pc.(setReadBufferer); ok { - if err := srb.SetReadBuffer(int(sl.ReadBufferSize.Size)); err != nil { + if err := srb.SetReadBuffer(int(sl.ReadBufferSize)); err != nil { sl.Log.Warnf("Setting read buffer on a %s socket failed: %v", protocol, err) } } else { diff --git a/plugins/inputs/socket_listener/socket_listener_test.go b/plugins/inputs/socket_listener/socket_listener_test.go index 2a24850eaf889..c33e59f7129b6 100644 --- a/plugins/inputs/socket_listener/socket_listener_test.go +++ b/plugins/inputs/socket_listener/socket_listener_test.go @@ -13,6 +13,7 @@ import ( "testing" "time" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/testutil" "github.com/influxdata/wlog" @@ -99,7 +100,7 @@ func TestSocketListener_tcp(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "tcp://127.0.0.1:0" - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) acc := &testutil.Accumulator{} err := sl.Start(acc) @@ -118,7 +119,7 @@ func TestSocketListener_udp(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "udp://127.0.0.1:0" - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) acc := &testutil.Accumulator{} err := sl.Start(acc) @@ -144,7 +145,7 @@ func TestSocketListener_unix(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "unix://" + sock - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) acc := &testutil.Accumulator{} err = sl.Start(acc) @@ -174,7 +175,7 @@ func TestSocketListener_unixgram(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "unixgram://" + sock - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) acc := &testutil.Accumulator{} err = sl.Start(acc) @@ -193,7 +194,7 @@ func TestSocketListenerDecode_tcp(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "tcp://127.0.0.1:0" - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) sl.ContentEncoding = "gzip" acc := &testutil.Accumulator{} @@ -213,7 +214,7 @@ func TestSocketListenerDecode_udp(t *testing.T) { sl := newSocketListener() sl.Log = testutil.Logger{} sl.ServiceAddress = "udp://127.0.0.1:0" - sl.ReadBufferSize = internal.Size{Size: 1024} + sl.ReadBufferSize = config.Size(1024) sl.ContentEncoding = "gzip" acc := &testutil.Accumulator{} diff --git a/plugins/inputs/solr/solr.go b/plugins/inputs/solr/solr.go index 9a850bbdb0362..08531e7433b34 100644 --- a/plugins/inputs/solr/solr.go +++ b/plugins/inputs/solr/solr.go @@ -11,6 +11,7 @@ import ( "time" "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/inputs" ) @@ -36,7 +37,7 @@ type Solr struct { Servers []string Username string Password string - HTTPTimeout internal.Duration + HTTPTimeout config.Duration Cores []string client *http.Client } @@ -121,7 +122,7 @@ type Cache struct { // NewSolr return a new instance of Solr func NewSolr() *Solr { return &Solr{ - HTTPTimeout: internal.Duration{Duration: time.Second * 5}, + HTTPTimeout: config.Duration(time.Second * 5), } } @@ -461,11 +462,11 @@ func (s *Solr) mbeansURL(server string, core string) string { func (s *Solr) createHTTPClient() *http.Client { tr := &http.Transport{ - ResponseHeaderTimeout: s.HTTPTimeout.Duration, + ResponseHeaderTimeout: time.Duration(s.HTTPTimeout), } client := &http.Client{ Transport: tr, - Timeout: s.HTTPTimeout.Duration, + Timeout: time.Duration(s.HTTPTimeout), } return client diff --git a/plugins/inputs/stackdriver/stackdriver.go b/plugins/inputs/stackdriver/stackdriver.go index bcb3052756a43..885913f91dd1c 100644 --- a/plugins/inputs/stackdriver/stackdriver.go +++ b/plugins/inputs/stackdriver/stackdriver.go @@ -13,7 +13,7 @@ import ( googlepbduration "github.com/golang/protobuf/ptypes/duration" googlepbts "github.com/golang/protobuf/ptypes/timestamp" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal/limiter" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/inputs" // Imports the Stackdriver Monitoring client package. @@ -108,9 +108,9 @@ const ( ) var ( - defaultCacheTTL = internal.Duration{Duration: 1 * time.Hour} - defaultWindow = internal.Duration{Duration: 1 * time.Minute} - defaultDelay = internal.Duration{Duration: 5 * time.Minute} + defaultCacheTTL = config.Duration(1 * time.Hour) + defaultWindow = config.Duration(1 * time.Minute) + defaultDelay = config.Duration(5 * time.Minute) ) type ( @@ -118,9 +118,9 @@ type ( Stackdriver struct { Project string `toml:"project"` RateLimit int `toml:"rate_limit"` - Window internal.Duration `toml:"window"` - Delay internal.Duration `toml:"delay"` - CacheTTL internal.Duration `toml:"cache_ttl"` + Window config.Duration `toml:"window"` + Delay config.Duration `toml:"delay"` + CacheTTL config.Duration `toml:"cache_ttl"` MetricTypePrefixInclude []string `toml:"metric_type_prefix_include"` MetricTypePrefixExclude []string `toml:"metric_type_prefix_exclude"` GatherRawDistributionBuckets bool `toml:"gather_raw_distribution_buckets"` @@ -322,14 +322,14 @@ func (s *Stackdriver) Gather(acc telegraf.Accumulator) error { // Returns the start and end time for the next collection. func (s *Stackdriver) updateWindow(prevEnd time.Time) (time.Time, time.Time) { var start time.Time - if s.Window.Duration != 0 { - start = time.Now().Add(-s.Delay.Duration).Add(-s.Window.Duration) + if time.Duration(s.Window) != 0 { + start = time.Now().Add(-time.Duration(s.Delay)).Add(-time.Duration(s.Window)) } else if prevEnd.IsZero() { - start = time.Now().Add(-s.Delay.Duration).Add(-defaultWindow.Duration) + start = time.Now().Add(-time.Duration(s.Delay)).Add(-time.Duration(defaultWindow)) } else { start = prevEnd } - end := time.Now().Add(-s.Delay.Duration) + end := time.Now().Add(-time.Duration(s.Delay)) return start, end } @@ -579,7 +579,7 @@ func (s *Stackdriver) generatetimeSeriesConfs( s.timeSeriesConfCache = &timeSeriesConfCache{ TimeSeriesConfs: ret, Generated: time.Now(), - TTL: s.CacheTTL.Duration, + TTL: time.Duration(s.CacheTTL), } return ret, nil diff --git a/plugins/inputs/statsd/README.md b/plugins/inputs/statsd/README.md index a302f4095e63f..ca60dbe3a2a79 100644 --- a/plugins/inputs/statsd/README.md +++ b/plugins/inputs/statsd/README.md @@ -190,7 +190,7 @@ metric type: - **max_tcp_connections** []int: Maximum number of concurrent TCP connections to allow. Used when protocol is set to tcp. - **tcp_keep_alive** boolean: Enable TCP keep alive probes -- **tcp_keep_alive_period** internal.Duration: Specifies the keep-alive period for an active network connection +- **tcp_keep_alive_period** duration: Specifies the keep-alive period for an active network connection - **service_address** string: Address to listen for statsd UDP packets on - **delete_gauges** boolean: Delete gauges on every collection interval - **delete_counters** boolean: Delete counters on every collection interval diff --git a/plugins/inputs/statsd/statsd.go b/plugins/inputs/statsd/statsd.go index f47e3e16ec687..1aded7f9f1894 100644 --- a/plugins/inputs/statsd/statsd.go +++ b/plugins/inputs/statsd/statsd.go @@ -49,7 +49,7 @@ type Statsd struct { // Percentiles specifies the percentiles that will be calculated for timing // and histogram stats. - Percentiles []internal.Number + Percentiles []float64 PercentileLimit int DeleteGauges bool @@ -119,8 +119,8 @@ type Statsd struct { MaxTCPConnections int `toml:"max_tcp_connections"` - TCPKeepAlive bool `toml:"tcp_keep_alive"` - TCPKeepAlivePeriod *internal.Duration `toml:"tcp_keep_alive_period"` + TCPKeepAlive bool `toml:"tcp_keep_alive"` + TCPKeepAlivePeriod *config.Duration `toml:"tcp_keep_alive_period"` // Max duration for each metric to stay cached without being updated. MaxTTL config.Duration `toml:"max_ttl"` @@ -304,8 +304,8 @@ func (s *Statsd) Gather(acc telegraf.Accumulator) error { fields[prefix+"lower"] = stats.Lower() fields[prefix+"count"] = stats.Count() for _, percentile := range s.Percentiles { - name := fmt.Sprintf("%s%v_percentile", prefix, percentile.Value) - fields[name] = stats.Percentile(percentile.Value) + name := fmt.Sprintf("%s%v_percentile", prefix, percentile) + fields[name] = stats.Percentile(percentile) } } @@ -474,7 +474,7 @@ func (s *Statsd) tcpListen(listener *net.TCPListener) error { } if s.TCPKeepAlivePeriod != nil { - if err = conn.SetKeepAlivePeriod(s.TCPKeepAlivePeriod.Duration); err != nil { + if err = conn.SetKeepAlivePeriod(time.Duration(*s.TCPKeepAlivePeriod)); err != nil { return err } } diff --git a/plugins/inputs/statsd/statsd_test.go b/plugins/inputs/statsd/statsd_test.go index 3e91d4f960402..bef21b8de9eff 100644 --- a/plugins/inputs/statsd/statsd_test.go +++ b/plugins/inputs/statsd/statsd_test.go @@ -9,7 +9,6 @@ import ( "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" - "github.com/influxdata/telegraf/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -398,7 +397,7 @@ func TestParse_Counters(t *testing.T) { // Tests low-level functionality of timings func TestParse_Timings(t *testing.T) { s := NewTestStatsd() - s.Percentiles = []internal.Number{{Value: 90.0}} + s.Percentiles = []float64{90.0} acc := &testutil.Accumulator{} // Test that timings work @@ -1187,7 +1186,7 @@ func TestParse_MeasurementsWithMultipleValues(t *testing.T) { func TestParse_TimingsMultipleFieldsWithTemplate(t *testing.T) { s := NewTestStatsd() s.Templates = []string{"measurement.field"} - s.Percentiles = []internal.Number{{Value: 90.0}} + s.Percentiles = []float64{90.0} acc := &testutil.Accumulator{} validLines := []string{ @@ -1235,7 +1234,7 @@ func TestParse_TimingsMultipleFieldsWithTemplate(t *testing.T) { func TestParse_TimingsMultipleFieldsWithoutTemplate(t *testing.T) { s := NewTestStatsd() s.Templates = []string{} - s.Percentiles = []internal.Number{{Value: 90.0}} + s.Percentiles = []float64{90.0} acc := &testutil.Accumulator{} validLines := []string{ diff --git a/plugins/inputs/syslog/commons_test.go b/plugins/inputs/syslog/commons_test.go index 10f2ddf511d22..5b30b3778ec8e 100644 --- a/plugins/inputs/syslog/commons_test.go +++ b/plugins/inputs/syslog/commons_test.go @@ -4,7 +4,7 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" framing "github.com/influxdata/telegraf/internal/syslog" "github.com/influxdata/telegraf/testutil" ) @@ -40,17 +40,15 @@ func newUDPSyslogReceiver(address string, bestEffort bool) *Syslog { } } -func newTCPSyslogReceiver(address string, keepAlive *internal.Duration, maxConn int, bestEffort bool, f framing.Framing) *Syslog { - d := &internal.Duration{ - Duration: defaultReadTimeout, - } +func newTCPSyslogReceiver(address string, keepAlive *config.Duration, maxConn int, bestEffort bool, f framing.Framing) *Syslog { + d := config.Duration(defaultReadTimeout) s := &Syslog{ Address: address, now: func() time.Time { return defaultTime }, Framing: f, - ReadTimeout: d, + ReadTimeout: &d, BestEffort: bestEffort, Separator: "_", } diff --git a/plugins/inputs/syslog/nontransparent_test.go b/plugins/inputs/syslog/nontransparent_test.go index 9ec62238a17b0..4d29daaf53915 100644 --- a/plugins/inputs/syslog/nontransparent_test.go +++ b/plugins/inputs/syslog/nontransparent_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" framing "github.com/influxdata/telegraf/internal/syslog" "github.com/influxdata/telegraf/testutil" ) @@ -136,7 +136,7 @@ func getTestCasesForNonTransparent() []testCaseStream { return testCases } -func testStrictNonTransparent(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *internal.Duration) { +func testStrictNonTransparent(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *config.Duration) { for _, tc := range getTestCasesForNonTransparent() { t.Run(tc.name, func(t *testing.T) { // Creation of a strict mode receiver @@ -195,7 +195,7 @@ func testStrictNonTransparent(t *testing.T, protocol string, address string, wan } func testBestEffortNonTransparent(t *testing.T, protocol string, address string, wantTLS bool) { - keepAlive := (*internal.Duration)(nil) + keepAlive := (*config.Duration)(nil) for _, tc := range getTestCasesForNonTransparent() { t.Run(tc.name, func(t *testing.T) { // Creation of a best effort mode receiver @@ -260,11 +260,13 @@ func TestNonTransparentBestEffort_tcp_tls(t *testing.T) { } func TestNonTransparentStrictWithKeepAlive_tcp_tls(t *testing.T) { - testStrictNonTransparent(t, "tcp", address, true, &internal.Duration{Duration: time.Minute}) + d := config.Duration(time.Minute) + testStrictNonTransparent(t, "tcp", address, true, &d) } func TestNonTransparentStrictWithZeroKeepAlive_tcp_tls(t *testing.T) { - testStrictNonTransparent(t, "tcp", address, true, &internal.Duration{Duration: 0}) + d := config.Duration(0) + testStrictNonTransparent(t, "tcp", address, true, &d) } func TestNonTransparentStrict_unix(t *testing.T) { diff --git a/plugins/inputs/syslog/octetcounting_test.go b/plugins/inputs/syslog/octetcounting_test.go index 2f09822156a08..53fee69d112a5 100644 --- a/plugins/inputs/syslog/octetcounting_test.go +++ b/plugins/inputs/syslog/octetcounting_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" framing "github.com/influxdata/telegraf/internal/syslog" "github.com/influxdata/telegraf/testutil" ) @@ -336,7 +336,7 @@ func getTestCasesForOctetCounting() []testCaseStream { return testCases } -func testStrictOctetCounting(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *internal.Duration) { +func testStrictOctetCounting(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *config.Duration) { for _, tc := range getTestCasesForOctetCounting() { t.Run(tc.name, func(t *testing.T) { // Creation of a strict mode receiver @@ -395,7 +395,7 @@ func testStrictOctetCounting(t *testing.T, protocol string, address string, want } func testBestEffortOctetCounting(t *testing.T, protocol string, address string, wantTLS bool) { - keepAlive := (*internal.Duration)(nil) + keepAlive := (*config.Duration)(nil) for _, tc := range getTestCasesForOctetCounting() { t.Run(tc.name, func(t *testing.T) { // Creation of a best effort mode receiver @@ -460,11 +460,13 @@ func TestOctetCountingBestEffort_tcp_tls(t *testing.T) { } func TestOctetCountingStrictWithKeepAlive_tcp_tls(t *testing.T) { - testStrictOctetCounting(t, "tcp", address, true, &internal.Duration{Duration: time.Minute}) + d := config.Duration(time.Minute) + testStrictOctetCounting(t, "tcp", address, true, &d) } func TestOctetCountingStrictWithZeroKeepAlive_tcp_tls(t *testing.T) { - testStrictOctetCounting(t, "tcp", address, true, &internal.Duration{Duration: 0}) + d := config.Duration(0) + testStrictOctetCounting(t, "tcp", address, true, &d) } func TestOctetCountingStrict_unix(t *testing.T) { diff --git a/plugins/inputs/syslog/syslog.go b/plugins/inputs/syslog/syslog.go index 2bae730fb6e08..19e07913b72c4 100644 --- a/plugins/inputs/syslog/syslog.go +++ b/plugins/inputs/syslog/syslog.go @@ -19,7 +19,7 @@ import ( "github.com/influxdata/go-syslog/v2/rfc5424" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" framing "github.com/influxdata/telegraf/internal/syslog" tlsConfig "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/inputs" @@ -32,9 +32,9 @@ const ipMaxPacketSize = 64 * 1024 type Syslog struct { tlsConfig.ServerConfig Address string `toml:"server"` - KeepAlivePeriod *internal.Duration + KeepAlivePeriod *config.Duration MaxConnections int - ReadTimeout *internal.Duration + ReadTimeout *config.Duration Framing framing.Framing Trailer nontransparent.TrailerType BestEffort bool @@ -315,8 +315,8 @@ func (s *Syslog) handle(conn net.Conn, acc telegraf.Accumulator) { emit := func(r *syslog.Result) { s.store(*r, acc) - if s.ReadTimeout != nil && s.ReadTimeout.Duration > 0 { - if err := conn.SetReadDeadline(time.Now().Add(s.ReadTimeout.Duration)); err != nil { + if s.ReadTimeout != nil && time.Duration(*s.ReadTimeout) > 0 { + if err := conn.SetReadDeadline(time.Now().Add(time.Duration(*s.ReadTimeout))); err != nil { acc.AddError(fmt.Errorf("setting read deadline failed: %v", err)) } } @@ -342,8 +342,8 @@ func (s *Syslog) handle(conn net.Conn, acc telegraf.Accumulator) { p.Parse(conn) - if s.ReadTimeout != nil && s.ReadTimeout.Duration > 0 { - if err := conn.SetReadDeadline(time.Now().Add(s.ReadTimeout.Duration)); err != nil { + if s.ReadTimeout != nil && time.Duration(*s.ReadTimeout) > 0 { + if err := conn.SetReadDeadline(time.Now().Add(time.Duration(*s.ReadTimeout))); err != nil { acc.AddError(fmt.Errorf("setting read deadline failed: %v", err)) } } @@ -354,13 +354,13 @@ func (s *Syslog) setKeepAlive(c *net.TCPConn) error { return nil } - if s.KeepAlivePeriod.Duration == 0 { + if *s.KeepAlivePeriod == 0 { return c.SetKeepAlive(false) } if err := c.SetKeepAlive(true); err != nil { return err } - return c.SetKeepAlivePeriod(s.KeepAlivePeriod.Duration) + return c.SetKeepAlivePeriod(time.Duration(*s.KeepAlivePeriod)) } func (s *Syslog) store(res syslog.Result, acc telegraf.Accumulator) { @@ -460,16 +460,15 @@ func getNanoNow() time.Time { } func init() { + defaultTimeout := config.Duration(defaultReadTimeout) inputs.Add("syslog", func() telegraf.Input { return &Syslog{ - Address: ":6514", - now: getNanoNow, - ReadTimeout: &internal.Duration{ - Duration: defaultReadTimeout, - }, - Framing: framing.OctetCounting, - Trailer: nontransparent.LF, - Separator: "_", + Address: ":6514", + now: getNanoNow, + ReadTimeout: &defaultTimeout, + Framing: framing.OctetCounting, + Trailer: nontransparent.LF, + Separator: "_", } }) } diff --git a/plugins/inputs/sysstat/sysstat.go b/plugins/inputs/sysstat/sysstat.go index 6eb649ebaacdc..01b4db9fa4af9 100644 --- a/plugins/inputs/sysstat/sysstat.go +++ b/plugins/inputs/sysstat/sysstat.go @@ -16,6 +16,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 Sysstat struct { Sadc string `toml:"sadc_path"` // Force the execution time of sadc - SadcInterval internal.Duration `toml:"sadc_interval"` + SadcInterval config.Duration `toml:"sadc_interval"` // Sadf represents the path to the sadf cmd. Sadf string `toml:"sadf_path"` @@ -135,9 +136,9 @@ func (*Sysstat) SampleConfig() string { } func (s *Sysstat) Gather(acc telegraf.Accumulator) error { - if s.SadcInterval.Duration != 0 { + if time.Duration(s.SadcInterval) != 0 { // Collect interval is calculated as interval - parseInterval - s.interval = int(s.SadcInterval.Duration.Seconds()) + parseInterval + s.interval = int(time.Duration(s.SadcInterval).Seconds()) + parseInterval } if s.interval == 0 { diff --git a/plugins/inputs/systemd_units/systemd_units_linux.go b/plugins/inputs/systemd_units/systemd_units_linux.go index e7a4be077d7f4..e94b9432136e4 100644 --- a/plugins/inputs/systemd_units/systemd_units_linux.go +++ b/plugins/inputs/systemd_units/systemd_units_linux.go @@ -9,18 +9,19 @@ import ( "time" "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/inputs" ) // SystemdUnits is a telegraf plugin to gather systemd unit status type SystemdUnits struct { - Timeout internal.Duration + Timeout config.Duration UnitType string `toml:"unittype"` systemctl systemctl } -type systemctl func(Timeout internal.Duration, UnitType string) (*bytes.Buffer, error) +type systemctl func(timeout config.Duration, unitType string) (*bytes.Buffer, error) const measurement = "systemd_units" @@ -112,7 +113,7 @@ var subMap = map[string]int{ } var ( - defaultTimeout = internal.Duration{Duration: time.Second} + defaultTimeout = config.Duration(time.Second) defaultUnitType = "service" ) @@ -191,20 +192,20 @@ func (s *SystemdUnits) Gather(acc telegraf.Accumulator) error { return nil } -func setSystemctl(Timeout internal.Duration, UnitType string) (*bytes.Buffer, error) { +func setSystemctl(timeout config.Duration, unitType string) (*bytes.Buffer, error) { // is systemctl available ? systemctlPath, err := exec.LookPath("systemctl") if err != nil { return nil, err } - cmd := exec.Command(systemctlPath, "list-units", "--all", "--plain", fmt.Sprintf("--type=%s", UnitType), "--no-legend") + cmd := exec.Command(systemctlPath, "list-units", "--all", "--plain", fmt.Sprintf("--type=%s", unitType), "--no-legend") 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 systemctl list-units --all --plain --type=%s --no-legend: %s", UnitType, err) + return &out, fmt.Errorf("error running systemctl list-units --all --plain --type=%s --no-legend: %s", unitType, err) } return &out, nil diff --git a/plugins/inputs/systemd_units/systemd_units_linux_test.go b/plugins/inputs/systemd_units/systemd_units_linux_test.go index 01af08105998d..a6cfbd6552771 100644 --- a/plugins/inputs/systemd_units/systemd_units_linux_test.go +++ b/plugins/inputs/systemd_units/systemd_units_linux_test.go @@ -6,7 +6,7 @@ import ( "reflect" "testing" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" ) @@ -74,7 +74,7 @@ func TestSystemdUnits(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { systemdUnits := &SystemdUnits{ - systemctl: func(Timeout internal.Duration, UnitType string) (*bytes.Buffer, error) { + systemctl: func(timeout config.Duration, unitType string) (*bytes.Buffer, error) { return bytes.NewBufferString(tt.line), nil }, } diff --git a/plugins/inputs/tail/multiline.go b/plugins/inputs/tail/multiline.go index 58a9b9e1e588c..7ea2e460b88d6 100644 --- a/plugins/inputs/tail/multiline.go +++ b/plugins/inputs/tail/multiline.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" ) // Indicates relation to the multiline event: previous or next @@ -23,7 +23,7 @@ type MultilineConfig struct { Pattern string MatchWhichLine MultilineMatchWhichLine `toml:"match_which_line"` InvertMatch bool - Timeout *internal.Duration + Timeout *config.Duration } const ( @@ -43,8 +43,9 @@ func (m *MultilineConfig) NewMultiline() (*Multiline, error) { if r, err = regexp.Compile(m.Pattern); err != nil { return nil, err } - if m.Timeout == nil || m.Timeout.Duration.Nanoseconds() == int64(0) { - m.Timeout = &internal.Duration{Duration: 5 * time.Second} + if m.Timeout == nil || time.Duration(*m.Timeout).Nanoseconds() == int64(0) { + d := config.Duration(5 * time.Second) + m.Timeout = &d } } diff --git a/plugins/inputs/tail/multiline_test.go b/plugins/inputs/tail/multiline_test.go index 44bfafb2ba25f..26a7e80292772 100644 --- a/plugins/inputs/tail/multiline_test.go +++ b/plugins/inputs/tail/multiline_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/stretchr/testify/assert" ) @@ -32,20 +32,20 @@ func TestMultilineConfigError(t *testing.T) { } func TestMultilineConfigTimeoutSpecified(t *testing.T) { - duration, _ := time.ParseDuration("10s") + duration := config.Duration(10 * time.Second) c := &MultilineConfig{ Pattern: ".*", MatchWhichLine: Previous, - Timeout: &internal.Duration{Duration: duration}, + Timeout: &duration, } m, err := c.NewMultiline() assert.NoError(t, err, "Configuration was OK.") - assert.Equal(t, duration, m.config.Timeout.Duration) + assert.Equal(t, duration, *m.config.Timeout) } func TestMultilineConfigDefaultTimeout(t *testing.T) { - duration, _ := time.ParseDuration("5s") + duration := config.Duration(5 * time.Second) c := &MultilineConfig{ Pattern: ".*", MatchWhichLine: Previous, @@ -53,7 +53,7 @@ func TestMultilineConfigDefaultTimeout(t *testing.T) { m, err := c.NewMultiline() assert.NoError(t, err, "Configuration was OK.") - assert.Equal(t, duration, m.config.Timeout.Duration) + assert.Equal(t, duration, *m.config.Timeout) } func TestMultilineIsEnabled(t *testing.T) { diff --git a/plugins/inputs/tail/tail.go b/plugins/inputs/tail/tail.go index 84a91635540bf..d84c09ff8d3c2 100644 --- a/plugins/inputs/tail/tail.go +++ b/plugins/inputs/tail/tail.go @@ -325,7 +325,7 @@ func (t *Tail) receiver(parser parsers.Parser, tailer *tail.Tail) { // The multiline mode requires a timer in order to flush the multiline buffer // if no new lines are incoming. if t.multiline.IsEnabled() { - timer = time.NewTimer(t.MultilineConfig.Timeout.Duration) + timer = time.NewTimer(time.Duration(*t.MultilineConfig.Timeout)) timeout = timer.C } @@ -337,7 +337,7 @@ func (t *Tail) receiver(parser parsers.Parser, tailer *tail.Tail) { line = nil if timer != nil { - timer.Reset(t.MultilineConfig.Timeout.Duration) + timer.Reset(time.Duration(*t.MultilineConfig.Timeout)) } select { diff --git a/plugins/inputs/tail/tail_test.go b/plugins/inputs/tail/tail_test.go index 0d8460a251a72..b855691e6f1ab 100644 --- a/plugins/inputs/tail/tail_test.go +++ b/plugins/inputs/tail/tail_test.go @@ -14,7 +14,7 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/parsers/csv" "github.com/influxdata/telegraf/plugins/parsers/influx" @@ -120,9 +120,9 @@ func TestTailDosLineEndings(t *testing.T) { func TestGrokParseLogFilesWithMultiline(t *testing.T) { //we make sure the timeout won't kick in - duration, _ := time.ParseDuration("100s") - - tt := NewTestTail() + d, _ := time.ParseDuration("100s") + duration := config.Duration(d) + tt := NewTail() tt.Log = testutil.Logger{} tt.FromBeginning = true tt.Files = []string{filepath.Join(testdataDir, "test_multiline.log")} @@ -130,7 +130,7 @@ func TestGrokParseLogFilesWithMultiline(t *testing.T) { Pattern: `^[^\[]`, MatchWhichLine: Previous, InvertMatch: false, - Timeout: &internal.Duration{Duration: duration}, + Timeout: &duration, } tt.SetParserFunc(createGrokParser) @@ -183,9 +183,10 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) { require.NoError(t, tmpfile.Sync()) // set tight timeout for tests - duration := 10 * time.Millisecond + d := 10 * time.Millisecond + duration := config.Duration(d) + tt := NewTail() - tt := NewTestTail() tt.Log = testutil.Logger{} tt.FromBeginning = true tt.Files = []string{tmpfile.Name()} @@ -193,7 +194,7 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) { Pattern: `^[^\[]`, MatchWhichLine: Previous, InvertMatch: false, - Timeout: &internal.Duration{Duration: duration}, + Timeout: &duration, } tt.SetParserFunc(createGrokParser) @@ -236,7 +237,7 @@ func TestGrokParseLogFilesWithMultilineTimeout(t *testing.T) { func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *testing.T) { //we make sure the timeout won't kick in - duration := 100 * time.Second + duration := config.Duration(100 * time.Second) tt := NewTestTail() tt.Log = testutil.Logger{} @@ -246,7 +247,7 @@ func TestGrokParseLogFilesWithMultilineTailerCloseFlushesMultilineBuffer(t *test Pattern: `^[^\[]`, MatchWhichLine: Previous, InvertMatch: false, - Timeout: &internal.Duration{Duration: duration}, + Timeout: &duration, } tt.SetParserFunc(createGrokParser) diff --git a/plugins/inputs/tengine/tengine.go b/plugins/inputs/tengine/tengine.go index 846a5411dba33..1787354c22cff 100644 --- a/plugins/inputs/tengine/tengine.go +++ b/plugins/inputs/tengine/tengine.go @@ -14,14 +14,14 @@ import ( "io" "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 Tengine struct { Urls []string - ResponseTimeout internal.Duration + ResponseTimeout config.Duration tls.ClientConfig client *http.Client @@ -87,15 +87,15 @@ func (n *Tengine) 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 diff --git a/plugins/inputs/tomcat/tomcat.go b/plugins/inputs/tomcat/tomcat.go index 60081e1295b6c..5b869fb4d8c76 100644 --- a/plugins/inputs/tomcat/tomcat.go +++ b/plugins/inputs/tomcat/tomcat.go @@ -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/common/tls" "github.com/influxdata/telegraf/plugins/inputs" ) @@ -63,7 +63,7 @@ type Tomcat struct { URL string Username string Password string - Timeout internal.Duration + Timeout config.Duration tls.ClientConfig client *http.Client @@ -199,7 +199,7 @@ func (s *Tomcat) createHTTPClient() (*http.Client, error) { Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, - Timeout: s.Timeout.Duration, + Timeout: time.Duration(s.Timeout), } return client, nil @@ -211,7 +211,7 @@ func init() { URL: "http://127.0.0.1:8080/manager/status/all?XML=true", Username: "tomcat", Password: "s3cret", - Timeout: internal.Duration{Duration: 5 * time.Second}, + Timeout: config.Duration(5 * time.Second), } }) } diff --git a/plugins/inputs/unbound/unbound.go b/plugins/inputs/unbound/unbound.go index 441d44c852f92..72a9e4db5965d 100644 --- a/plugins/inputs/unbound/unbound.go +++ b/plugins/inputs/unbound/unbound.go @@ -12,6 +12,7 @@ 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" @@ -21,18 +22,18 @@ type runner func(unbound Unbound) (*bytes.Buffer, error) // Unbound is used to store configuration values type Unbound struct { - Binary string `toml:"binary"` - Timeout internal.Duration `toml:"timeout"` - UseSudo bool `toml:"use_sudo"` - Server string `toml:"server"` - ThreadAsTag bool `toml:"thread_as_tag"` - ConfigFile string `toml:"config_file"` + Binary string `toml:"binary"` + Timeout config.Duration `toml:"timeout"` + UseSudo bool `toml:"use_sudo"` + Server string `toml:"server"` + ThreadAsTag bool `toml:"thread_as_tag"` + ConfigFile string `toml:"config_file"` run runner } var defaultBinary = "/usr/sbin/unbound-control" -var defaultTimeout = internal.Duration{Duration: time.Second} +var defaultTimeout = config.Duration(time.Second) var sampleConfig = ` ## Address of server to connect to, read from unbound conf default, optionally ':port' @@ -82,7 +83,7 @@ func unboundRunner(unbound Unbound) (*bytes.Buffer, error) { // Unbound control requires an IP address, and we want to be nice to the user resolver := net.Resolver{} - ctx, lookUpCancel := context.WithTimeout(context.Background(), unbound.Timeout.Duration) + ctx, lookUpCancel := context.WithTimeout(context.Background(), time.Duration(unbound.Timeout)) defer lookUpCancel() serverIps, err := resolver.LookupIPAddr(ctx, host) if err != nil { @@ -112,7 +113,7 @@ func unboundRunner(unbound Unbound) (*bytes.Buffer, error) { var out bytes.Buffer cmd.Stdout = &out - err := internal.RunTimeout(cmd, unbound.Timeout.Duration) + err := internal.RunTimeout(cmd, time.Duration(unbound.Timeout)) if err != nil { return &out, fmt.Errorf("error running unbound-control: %s (%s %v)", err, unbound.Binary, cmdArgs) } diff --git a/plugins/inputs/unbound/unbound_test.go b/plugins/inputs/unbound/unbound_test.go index cac0316d7db01..d3900602441f1 100644 --- a/plugins/inputs/unbound/unbound_test.go +++ b/plugins/inputs/unbound/unbound_test.go @@ -4,9 +4,8 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" - "github.com/influxdata/telegraf/testutil" + "github.com/stretchr/testify/assert" ) func UnboundControl(output string) func(unbound Unbound) (*bytes.Buffer, error) { diff --git a/plugins/inputs/uwsgi/uwsgi.go b/plugins/inputs/uwsgi/uwsgi.go index 81dd3c350cf3d..f536e4b27c44f 100644 --- a/plugins/inputs/uwsgi/uwsgi.go +++ b/plugins/inputs/uwsgi/uwsgi.go @@ -15,14 +15,14 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/inputs" ) // Uwsgi server struct type Uwsgi struct { - Servers []string `toml:"servers"` - Timeout internal.Duration `toml:"timeout"` + Servers []string `toml:"servers"` + Timeout config.Duration `toml:"timeout"` client *http.Client } @@ -51,7 +51,7 @@ func (u *Uwsgi) SampleConfig() string { func (u *Uwsgi) Gather(acc telegraf.Accumulator) error { if u.client == nil { u.client = &http.Client{ - Timeout: u.Timeout.Duration, + Timeout: time.Duration(u.Timeout), } } wg := &sync.WaitGroup{} @@ -85,13 +85,13 @@ func (u *Uwsgi) gatherServer(acc telegraf.Accumulator, url *url.URL) error { switch url.Scheme { case "tcp": - r, err = net.DialTimeout(url.Scheme, url.Host, u.Timeout.Duration) + r, err = net.DialTimeout(url.Scheme, url.Host, time.Duration(u.Timeout)) if err != nil { return err } s.source = url.Host case "unix": - r, err = net.DialTimeout(url.Scheme, url.Path, u.Timeout.Duration) + r, err = net.DialTimeout(url.Scheme, url.Path, time.Duration(u.Timeout)) if err != nil { return err } @@ -216,7 +216,7 @@ func (u *Uwsgi) gatherCores(acc telegraf.Accumulator, s *StatsServer) { func init() { inputs.Add("uwsgi", func() telegraf.Input { return &Uwsgi{ - Timeout: internal.Duration{Duration: 5 * time.Second}, + Timeout: config.Duration(5 * time.Second), } }) } diff --git a/plugins/inputs/varnish/varnish.go b/plugins/inputs/varnish/varnish.go index c2dcce699d55b..e4f18bee42ed3 100644 --- a/plugins/inputs/varnish/varnish.go +++ b/plugins/inputs/varnish/varnish.go @@ -12,12 +12,13 @@ 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, UseSudo bool, InstanceName string, Timeout internal.Duration) (*bytes.Buffer, error) +type runner func(cmdName string, useSudo bool, instanceName string, timeout config.Duration) (*bytes.Buffer, error) // Varnish is used to store configuration values type Varnish struct { @@ -25,7 +26,7 @@ type Varnish struct { Binary string UseSudo bool InstanceName string - Timeout internal.Duration + Timeout config.Duration filter filter.Filter run runner @@ -33,7 +34,7 @@ type Varnish struct { var defaultStats = []string{"MAIN.cache_hit", "MAIN.cache_miss", "MAIN.uptime"} var defaultBinary = "/usr/bin/varnishstat" -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: @@ -66,16 +67,16 @@ func (s *Varnish) SampleConfig() string { } // Shell out to varnish_stat and return the output -func varnishRunner(cmdName string, UseSudo bool, InstanceName string, Timeout internal.Duration) (*bytes.Buffer, error) { +func varnishRunner(cmdName string, useSudo bool, instanceName string, timeout config.Duration) (*bytes.Buffer, error) { cmdArgs := []string{"-1"} - if InstanceName != "" { - cmdArgs = append(cmdArgs, []string{"-n", InstanceName}...) + if instanceName != "" { + cmdArgs = append(cmdArgs, []string{"-n", instanceName}...) } cmd := exec.Command(cmdName, cmdArgs...) - if UseSudo { + if useSudo { cmdArgs = append([]string{cmdName}, cmdArgs...) cmdArgs = append([]string{"-n"}, cmdArgs...) cmd = exec.Command("sudo", cmdArgs...) @@ -84,7 +85,7 @@ func varnishRunner(cmdName string, UseSudo bool, InstanceName string, Timeout in 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 varnishstat: %s", err) } diff --git a/plugins/inputs/varnish/varnish_test.go b/plugins/inputs/varnish/varnish_test.go index 2642782fe806d..4ba9e941a52ee 100644 --- a/plugins/inputs/varnish/varnish_test.go +++ b/plugins/inputs/varnish/varnish_test.go @@ -10,12 +10,12 @@ import ( "github.com/stretchr/testify/assert" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" ) -func fakeVarnishStat(output string) func(string, bool, string, internal.Duration) (*bytes.Buffer, error) { - return func(string, bool, string, internal.Duration) (*bytes.Buffer, error) { +func fakeVarnishStat(output string) func(string, bool, string, config.Duration) (*bytes.Buffer, error) { + return func(string, bool, string, config.Duration) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } } diff --git a/plugins/inputs/vsphere/client.go b/plugins/inputs/vsphere/client.go index 0eae3be6ffb97..2795c94ae6698 100644 --- a/plugins/inputs/vsphere/client.go +++ b/plugins/inputs/vsphere/client.go @@ -75,11 +75,11 @@ func (cf *ClientFactory) GetClient(ctx context.Context) (*Client, error) { // Execute a dummy call against the server to make sure the client is // still functional. If not, try to log back in. If that doesn't work, // we give up. - ctx1, cancel1 := context.WithTimeout(ctx, cf.parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(cf.parent.Timeout)) defer cancel1() if _, err := methods.GetCurrentTime(ctx1, cf.client.Client); err != nil { cf.parent.Log.Info("Client session seems to have time out. Reauthenticating!") - ctx2, cancel2 := context.WithTimeout(ctx, cf.parent.Timeout.Duration) + ctx2, cancel2 := context.WithTimeout(ctx, time.Duration(cf.parent.Timeout)) defer cancel2() if err := cf.client.Client.SessionManager.Login(ctx2, url.UserPassword(cf.parent.Username, cf.parent.Password)); err != nil { if !retrying { @@ -131,7 +131,7 @@ func NewClient(ctx context.Context, vSphereURL *url.URL, vs *VSphere) (*Client, } } - ctx1, cancel1 := context.WithTimeout(ctx, vs.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(vs.Timeout)) defer cancel1() vimClient, err := vim25.NewClient(ctx1, soapClient) if err != nil { @@ -141,7 +141,7 @@ func NewClient(ctx context.Context, vSphereURL *url.URL, vs *VSphere) (*Client, // If TSLKey is specified, try to log in as an extension using a cert. if vs.TLSKey != "" { - ctx2, cancel2 := context.WithTimeout(ctx, vs.Timeout.Duration) + ctx2, cancel2 := context.WithTimeout(ctx, time.Duration(vs.Timeout)) defer cancel2() if err := sm.LoginExtensionByCertificate(ctx2, vs.TLSKey); err != nil { return nil, err @@ -161,7 +161,7 @@ func NewClient(ctx context.Context, vSphereURL *url.URL, vs *VSphere) (*Client, } } - c.Timeout = vs.Timeout.Duration + c.Timeout = time.Duration(vs.Timeout) m := view.NewManager(c.Client) v, err := m.CreateContainerView(ctx, c.ServiceContent.RootFolder, []string{}, true) @@ -178,10 +178,10 @@ func NewClient(ctx context.Context, vSphereURL *url.URL, vs *VSphere) (*Client, Root: v, Perf: p, Valid: true, - Timeout: vs.Timeout.Duration, + Timeout: time.Duration(vs.Timeout), } // Adjust max query size if needed - ctx3, cancel3 := context.WithTimeout(ctx, vs.Timeout.Duration) + ctx3, cancel3 := context.WithTimeout(ctx, time.Duration(vs.Timeout)) defer cancel3() n, err := client.GetMaxQueryMetrics(ctx3) if err != nil { diff --git a/plugins/inputs/vsphere/endpoint.go b/plugins/inputs/vsphere/endpoint.go index 85fda786b17ba..bff3701653c8d 100644 --- a/plugins/inputs/vsphere/endpoint.go +++ b/plugins/inputs/vsphere/endpoint.go @@ -258,7 +258,7 @@ func isSimple(include []string, exclude []string) bool { } func (e *Endpoint) startDiscovery(ctx context.Context) { - e.discoveryTicker = time.NewTicker(e.Parent.ObjectDiscoveryInterval.Duration) + e.discoveryTicker = time.NewTicker(time.Duration(e.Parent.ObjectDiscoveryInterval)) go func() { for { select { @@ -300,7 +300,7 @@ func (e *Endpoint) init(ctx context.Context) error { } } - if e.Parent.ObjectDiscoveryInterval.Duration > 0 { + if time.Duration(e.Parent.ObjectDiscoveryInterval) > 0 { e.Parent.Log.Debug("Running initial discovery") e.initalDiscovery(ctx) } @@ -339,7 +339,7 @@ func (e *Endpoint) getMetadata(ctx context.Context, obj *objectRef, sampling int return nil, err } - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() metrics, err := client.Perf.AvailableMetric(ctx1, obj.ref.Reference(), sampling) if err != nil { @@ -367,7 +367,7 @@ func (e *Endpoint) getAncestorName(ctx context.Context, client *Client, resource path = append(path, here.Reference().String()) o := object.NewCommon(client.Client.Client, r) var result mo.ManagedEntity - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() err := o.Properties(ctx1, here, []string{"parent", "name"}, &result) if err != nil { @@ -429,7 +429,7 @@ func (e *Endpoint) discover(ctx context.Context) error { paths: res.paths, excludePaths: res.excludePaths} - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) objects, err := res.getObjects(ctx1, e, &rf) cancel1() if err != nil { @@ -588,7 +588,7 @@ func (e *Endpoint) complexMetadataSelect(ctx context.Context, res *resourceKind, func getDatacenters(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectMap, error) { var resources []mo.Datacenter - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() err := filter.FindAll(ctx1, &resources) if err != nil { @@ -609,7 +609,7 @@ func getDatacenters(ctx context.Context, e *Endpoint, filter *ResourceFilter) (o func getClusters(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectMap, error) { var resources []mo.ClusterComputeResource - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() err := filter.FindAll(ctx1, &resources) if err != nil { @@ -623,7 +623,7 @@ func getClusters(ctx context.Context, e *Endpoint, filter *ResourceFilter) (obje // We're not interested in the immediate parent (a folder), but the data center. p, ok := cache[r.Parent.Value] if !ok { - ctx2, cancel2 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx2, cancel2 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel2() client, err := e.clientFactory.GetClient(ctx2) if err != nil { @@ -631,7 +631,7 @@ func getClusters(ctx context.Context, e *Endpoint, filter *ResourceFilter) (obje } o := object.NewFolder(client.Client.Client, *r.Parent) var folder mo.Folder - ctx3, cancel3 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx3, cancel3 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel3() err = o.Properties(ctx3, *r.Parent, []string{"parent"}, &folder) if err != nil { @@ -679,7 +679,7 @@ func getHosts(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectM func getVMs(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectMap, error) { var resources []mo.VirtualMachine - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() err := filter.FindAll(ctx1, &resources) if err != nil { @@ -769,7 +769,7 @@ func getVMs(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectMap func getDatastores(ctx context.Context, e *Endpoint, filter *ResourceFilter) (objectMap, error) { var resources []mo.Datastore - ctx1, cancel1 := context.WithTimeout(ctx, e.Parent.Timeout.Duration) + ctx1, cancel1 := context.WithTimeout(ctx, time.Duration(e.Parent.Timeout)) defer cancel1() err := filter.FindAll(ctx1, &resources) if err != nil { @@ -840,7 +840,7 @@ func (e *Endpoint) Collect(ctx context.Context, acc telegraf.Accumulator) error } // If discovery interval is disabled (0), discover on each collection cycle - if e.Parent.ObjectDiscoveryInterval.Duration == 0 { + if time.Duration(e.Parent.ObjectDiscoveryInterval) == 0 { err := e.discover(ctx) if err != nil { return err diff --git a/plugins/inputs/vsphere/vsphere.go b/plugins/inputs/vsphere/vsphere.go index a18a5ca70f982..7e688b73c55fc 100644 --- a/plugins/inputs/vsphere/vsphere.go +++ b/plugins/inputs/vsphere/vsphere.go @@ -6,7 +6,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/vmware/govmomi/vim25/soap" @@ -54,8 +54,8 @@ type VSphere struct { CollectConcurrency int DiscoverConcurrency int ForceDiscoverOnInit bool - ObjectDiscoveryInterval internal.Duration - Timeout internal.Duration + ObjectDiscoveryInterval config.Duration + Timeout config.Duration endpoints []*Endpoint cancel context.CancelFunc @@ -364,8 +364,8 @@ func init() { CollectConcurrency: 1, DiscoverConcurrency: 1, ForceDiscoverOnInit: true, - ObjectDiscoveryInterval: internal.Duration{Duration: time.Second * 300}, - Timeout: internal.Duration{Duration: time.Second * 60}, + ObjectDiscoveryInterval: config.Duration(time.Second * 300), + Timeout: config.Duration(time.Second * 60), } }) } diff --git a/plugins/inputs/vsphere/vsphere_test.go b/plugins/inputs/vsphere/vsphere_test.go index 3dcde06f5e583..ae2ce57b9a88e 100644 --- a/plugins/inputs/vsphere/vsphere_test.go +++ b/plugins/inputs/vsphere/vsphere_test.go @@ -11,7 +11,7 @@ import ( "time" "unsafe" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" itls "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/testutil" "github.com/influxdata/toml" @@ -147,8 +147,8 @@ func defaultVSphere() *VSphere { MaxQueryObjects: 256, MaxQueryMetrics: 256, - ObjectDiscoveryInterval: internal.Duration{Duration: time.Second * 300}, - Timeout: internal.Duration{Duration: time.Second * 20}, + ObjectDiscoveryInterval: config.Duration(time.Second * 300), + Timeout: config.Duration(time.Second * 20), ForceDiscoverOnInit: true, DiscoverConcurrency: 1, CollectConcurrency: 1, diff --git a/plugins/inputs/win_perf_counters/win_perf_counters.go b/plugins/inputs/win_perf_counters/win_perf_counters.go index 73cc7dc7311d4..4bcbbfb1b2318 100644 --- a/plugins/inputs/win_perf_counters/win_perf_counters.go +++ b/plugins/inputs/win_perf_counters/win_perf_counters.go @@ -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" ) @@ -143,7 +143,7 @@ type Win_PerfCounters struct { PreVistaSupport bool UsePerfCounterTime bool Object []perfobject - CountersRefreshInterval internal.Duration + CountersRefreshInterval config.Duration UseWildcardsExpansion bool Log telegraf.Logger @@ -345,7 +345,7 @@ func (m *Win_PerfCounters) Gather(acc telegraf.Accumulator) error { // Parse the config once var err error - if m.lastRefreshed.IsZero() || (m.CountersRefreshInterval.Duration.Nanoseconds() > 0 && m.lastRefreshed.Add(m.CountersRefreshInterval.Duration).Before(time.Now())) { + if m.lastRefreshed.IsZero() || (m.CountersRefreshInterval > 0 && m.lastRefreshed.Add(time.Duration(m.CountersRefreshInterval)).Before(time.Now())) { if m.counters != nil { m.counters = m.counters[:0] } @@ -477,6 +477,6 @@ func isKnownCounterDataError(err error) bool { func init() { inputs.Add("win_perf_counters", func() telegraf.Input { - return &Win_PerfCounters{query: &PerformanceQueryImpl{}, CountersRefreshInterval: internal.Duration{Duration: time.Second * 60}} + return &Win_PerfCounters{query: &PerformanceQueryImpl{}, CountersRefreshInterval: config.Duration(time.Second * 60)} }) } diff --git a/plugins/inputs/win_perf_counters/win_perf_counters_test.go b/plugins/inputs/win_perf_counters/win_perf_counters_test.go index a11f0ace8da3a..930e923754ac8 100644 --- a/plugins/inputs/win_perf_counters/win_perf_counters_test.go +++ b/plugins/inputs/win_perf_counters/win_perf_counters_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -734,7 +734,7 @@ func TestGatherRefreshingWithExpansion(t *testing.T) { Object: perfObjects, UseWildcardsExpansion: true, query: fpm, - CountersRefreshInterval: internal.Duration{Duration: time.Second * 10}, + CountersRefreshInterval: config.Duration(time.Second * 10), } var acc1 testutil.Accumulator err = m.Gather(&acc1) @@ -791,7 +791,7 @@ func TestGatherRefreshingWithExpansion(t *testing.T) { acc2.AssertContainsTaggedFields(t, measurement, fields1, tags1) acc2.AssertContainsTaggedFields(t, measurement, fields2, tags2) acc2.AssertDoesNotContainsTaggedFields(t, measurement, fields3, tags3) - time.Sleep(m.CountersRefreshInterval.Duration) + time.Sleep(time.Duration(m.CountersRefreshInterval)) var acc3 testutil.Accumulator err = m.Gather(&acc3) @@ -827,7 +827,7 @@ func TestGatherRefreshingWithoutExpansion(t *testing.T) { Object: perfObjects, UseWildcardsExpansion: false, query: fpm, - CountersRefreshInterval: internal.Duration{Duration: time.Second * 10}} + CountersRefreshInterval: config.Duration(time.Second * 10)} var acc1 testutil.Accumulator err = m.Gather(&acc1) assert.Len(t, m.counters, 2) @@ -902,7 +902,7 @@ func TestGatherRefreshingWithoutExpansion(t *testing.T) { fpm.Open() - time.Sleep(m.CountersRefreshInterval.Duration) + time.Sleep(time.Duration(m.CountersRefreshInterval)) var acc3 testutil.Accumulator err = m.Gather(&acc3) diff --git a/plugins/inputs/x509_cert/x509_cert.go b/plugins/inputs/x509_cert/x509_cert.go index 3128b90686d0c..7c1b0657c7e80 100644 --- a/plugins/inputs/x509_cert/x509_cert.go +++ b/plugins/inputs/x509_cert/x509_cert.go @@ -15,7 +15,7 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal/globpath" _tls "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/inputs" @@ -43,9 +43,9 @@ const description = "Reads metrics from a SSL certificate" // X509Cert holds the configuration of the plugin. type X509Cert struct { - Sources []string `toml:"sources"` - Timeout internal.Duration `toml:"timeout"` - ServerName string `toml:"server_name"` + Sources []string `toml:"sources"` + Timeout config.Duration `toml:"timeout"` + ServerName string `toml:"server_name"` tlsCfg *tls.Config _tls.ClientConfig locations []*url.URL @@ -252,7 +252,7 @@ func (c *X509Cert) Gather(acc telegraf.Accumulator) error { } for _, location := range append(c.locations, collectedUrls...) { - certs, err := c.getCert(location, c.Timeout.Duration*time.Second) + certs, err := c.getCert(location, time.Duration(c.Timeout)) if err != nil { acc.AddError(fmt.Errorf("cannot get SSL cert '%s': %s", location, err.Error())) } @@ -322,7 +322,7 @@ func init() { inputs.Add("x509_cert", func() telegraf.Input { return &X509Cert{ Sources: []string{}, - Timeout: internal.Duration{Duration: 5 * time.Second}, // set default timeout to 5s + Timeout: config.Duration(5 * time.Second), // set default timeout to 5s } }) } diff --git a/plugins/inputs/x509_cert/x509_cert_test.go b/plugins/inputs/x509_cert/x509_cert_test.go index 4aafd3cb4090b..3253c9ac9c7ae 100644 --- a/plugins/inputs/x509_cert/x509_cert_test.go +++ b/plugins/inputs/x509_cert/x509_cert_test.go @@ -17,7 +17,7 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" _tls "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/testutil" ) @@ -60,7 +60,7 @@ func TestGatherRemoteIntegration(t *testing.T) { pair, err := tls.X509KeyPair([]byte(pki.ReadServerCert()), []byte(pki.ReadServerKey())) require.NoError(t, err) - config := &tls.Config{ + cfg := &tls.Config{ InsecureSkipVerify: true, Certificates: []tls.Certificate{pair}, } @@ -68,13 +68,13 @@ func TestGatherRemoteIntegration(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { if test.unset { - config.Certificates = nil - config.GetCertificate = func(i *tls.ClientHelloInfo) (*tls.Certificate, error) { + cfg.Certificates = nil + cfg.GetCertificate = func(i *tls.ClientHelloInfo) (*tls.Certificate, error) { return nil, nil } } - ln, err := tls.Listen("tcp", ":0", config) + ln, err := tls.Listen("tcp", ":0", cfg) require.NoError(t, err) defer ln.Close() @@ -85,7 +85,7 @@ func TestGatherRemoteIntegration(t *testing.T) { sconn.Close() } - serverConfig := config.Clone() + serverConfig := cfg.Clone() srv := tls.Server(sconn, serverConfig) if test.noshake { @@ -100,7 +100,7 @@ func TestGatherRemoteIntegration(t *testing.T) { sc := X509Cert{ Sources: []string{test.server}, - Timeout: internal.Duration{Duration: test.timeout}, + Timeout: config.Duration(test.timeout), } require.NoError(t, sc.Init()) @@ -306,7 +306,7 @@ func TestGatherCertMustNotTimeout(t *testing.T) { duration := time.Duration(15) * time.Second m := &X509Cert{ Sources: []string{"https://www.influxdata.com:443"}, - Timeout: internal.Duration{Duration: duration}, + Timeout: config.Duration(duration), } require.NoError(t, m.Init()) diff --git a/plugins/inputs/zookeeper/zookeeper.go b/plugins/inputs/zookeeper/zookeeper.go index 48c00a1d3ef7f..82a05bc1778b2 100644 --- a/plugins/inputs/zookeeper/zookeeper.go +++ b/plugins/inputs/zookeeper/zookeeper.go @@ -12,7 +12,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" ) @@ -22,7 +22,7 @@ var zookeeperFormatRE = regexp.MustCompile(`^zk_(\w[\w\.\-]*)\s+([\w\.\-]+)`) // Zookeeper is a zookeeper plugin type Zookeeper struct { Servers []string - Timeout internal.Duration + Timeout config.Duration EnableTLS bool `toml:"enable_tls"` EnableSSL bool `toml:"enable_ssl"` // deprecated in 1.7; use enable_tls @@ -89,11 +89,11 @@ func (z *Zookeeper) Gather(acc telegraf.Accumulator) error { z.initialized = true } - if z.Timeout.Duration < 1*time.Second { - z.Timeout.Duration = defaultTimeout + if z.Timeout < config.Duration(1*time.Second) { + z.Timeout = config.Duration(defaultTimeout) } - ctx, cancel := context.WithTimeout(ctx, z.Timeout.Duration) + ctx, cancel := context.WithTimeout(ctx, time.Duration(z.Timeout)) defer cancel() if len(z.Servers) == 0 { diff --git a/plugins/outputs/amon/amon.go b/plugins/outputs/amon/amon.go index 0ee62f1e94fc2..5bbbba9814e38 100644 --- a/plugins/outputs/amon/amon.go +++ b/plugins/outputs/amon/amon.go @@ -6,17 +6,18 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" ) type Amon struct { - ServerKey string `toml:"server_key"` - AmonInstance string `toml:"amon_instance"` - Timeout internal.Duration `toml:"timeout"` - Log telegraf.Logger `toml:"-"` + ServerKey string `toml:"server_key"` + AmonInstance string `toml:"amon_instance"` + Timeout config.Duration `toml:"timeout"` + Log telegraf.Logger `toml:"-"` client *http.Client } @@ -51,7 +52,7 @@ func (a *Amon) Connect() error { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: a.Timeout.Duration, + Timeout: time.Duration(a.Timeout), } return nil } diff --git a/plugins/outputs/amqp/amqp.go b/plugins/outputs/amqp/amqp.go index 8bf469a590248..95da1f99b0f9f 100644 --- a/plugins/outputs/amqp/amqp.go +++ b/plugins/outputs/amqp/amqp.go @@ -6,6 +6,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/outputs" @@ -50,7 +51,7 @@ type AMQP struct { RetentionPolicy string `toml:"retention_policy"` // deprecated in 1.7; use headers Precision string `toml:"precision"` // deprecated; has no effect Headers map[string]string `toml:"headers"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` UseBatchFormat bool `toml:"use_batch_format"` ContentEncoding string `toml:"content_encoding"` Log telegraf.Logger `toml:"-"` @@ -319,7 +320,7 @@ func (q *AMQP) makeClientConfig() (*ClientConfig, error) { exchangeType: q.ExchangeType, exchangePassive: q.ExchangePassive, encoding: q.ContentEncoding, - timeout: q.Timeout.Duration, + timeout: time.Duration(q.Timeout), } switch q.ExchangeDurability { @@ -397,7 +398,7 @@ func init() { AuthMethod: DefaultAuthMethod, Database: DefaultDatabase, RetentionPolicy: DefaultRetentionPolicy, - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), connect: connect, } }) diff --git a/plugins/outputs/amqp/amqp_test.go b/plugins/outputs/amqp/amqp_test.go index 537dd7d049b8c..05c25ea515194 100644 --- a/plugins/outputs/amqp/amqp_test.go +++ b/plugins/outputs/amqp/amqp_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/streadway/amqp" "github.com/stretchr/testify/require" ) @@ -53,24 +53,24 @@ func TestConnect(t *testing.T) { AuthMethod: DefaultAuthMethod, Database: DefaultDatabase, RetentionPolicy: DefaultRetentionPolicy, - Timeout: internal.Duration{Duration: time.Second * 5}, - connect: func(config *ClientConfig) (Client, error) { + Timeout: config.Duration(time.Second * 5), + connect: func(_ *ClientConfig) (Client, error) { return NewMockClient(), nil }, }, errFunc: func(t *testing.T, output *AMQP, err error) { - config := output.config - require.Equal(t, []string{DefaultURL}, config.brokers) - require.Equal(t, "", config.exchange) - require.Equal(t, "topic", config.exchangeType) - require.Equal(t, false, config.exchangePassive) - require.Equal(t, true, config.exchangeDurable) - require.Equal(t, amqp.Table(nil), config.exchangeArguments) + cfg := output.config + require.Equal(t, []string{DefaultURL}, cfg.brokers) + require.Equal(t, "", cfg.exchange) + require.Equal(t, "topic", cfg.exchangeType) + require.Equal(t, false, cfg.exchangePassive) + require.Equal(t, true, cfg.exchangeDurable) + require.Equal(t, amqp.Table(nil), cfg.exchangeArguments) require.Equal(t, amqp.Table{ "database": DefaultDatabase, "retention_policy": DefaultRetentionPolicy, - }, config.headers) - require.Equal(t, amqp.Transient, config.deliveryMode) + }, cfg.headers) + require.Equal(t, amqp.Transient, cfg.deliveryMode) require.NoError(t, err) }, }, @@ -80,15 +80,15 @@ func TestConnect(t *testing.T) { Headers: map[string]string{ "foo": "bar", }, - connect: func(config *ClientConfig) (Client, error) { + connect: func(_ *ClientConfig) (Client, error) { return NewMockClient(), nil }, }, errFunc: func(t *testing.T, output *AMQP, err error) { - config := output.config + cfg := output.config require.Equal(t, amqp.Table{ "foo": "bar", - }, config.headers) + }, cfg.headers) require.NoError(t, err) }, }, @@ -98,15 +98,15 @@ func TestConnect(t *testing.T) { ExchangeArguments: map[string]string{ "foo": "bar", }, - connect: func(config *ClientConfig) (Client, error) { + connect: func(_ *ClientConfig) (Client, error) { return NewMockClient(), nil }, }, errFunc: func(t *testing.T, output *AMQP, err error) { - config := output.config + cfg := output.config require.Equal(t, amqp.Table{ "foo": "bar", - }, config.exchangeArguments) + }, cfg.exchangeArguments) require.NoError(t, err) }, }, @@ -116,18 +116,18 @@ func TestConnect(t *testing.T) { URL: "amqp://foo:bar@localhost", Username: "telegraf", Password: "pa$$word", - connect: func(config *ClientConfig) (Client, error) { + connect: func(_ *ClientConfig) (Client, error) { return NewMockClient(), nil }, }, errFunc: func(t *testing.T, output *AMQP, err error) { - config := output.config + cfg := output.config require.Equal(t, []amqp.Authentication{ &amqp.PlainAuth{ Username: "telegraf", Password: "pa$$word", }, - }, config.auth) + }, cfg.auth) require.NoError(t, err) }, @@ -136,13 +136,13 @@ func TestConnect(t *testing.T) { name: "url support", output: &AMQP{ URL: DefaultURL, - connect: func(config *ClientConfig) (Client, error) { + connect: func(_ *ClientConfig) (Client, error) { return NewMockClient(), nil }, }, errFunc: func(t *testing.T, output *AMQP, err error) { - config := output.config - require.Equal(t, []string{DefaultURL}, config.brokers) + cfg := output.config + require.Equal(t, []string{DefaultURL}, cfg.brokers) require.NoError(t, err) }, }, diff --git a/plugins/outputs/application_insights/application_insights.go b/plugins/outputs/application_insights/application_insights.go index 6bcb924865780..950a9fcf7e3ff 100644 --- a/plugins/outputs/application_insights/application_insights.go +++ b/plugins/outputs/application_insights/application_insights.go @@ -8,7 +8,7 @@ import ( "github.com/Microsoft/ApplicationInsights-Go/appinsights" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" ) @@ -24,7 +24,7 @@ type DiagnosticsMessageSubscriber interface { type ApplicationInsights struct { InstrumentationKey string `toml:"instrumentation_key"` EndpointURL string `toml:"endpoint_url"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` EnableDiagnosticLogging bool `toml:"enable_diagnostic_logging"` ContextTagSources map[string]string `toml:"context_tag_sources"` Log telegraf.Logger `toml:"-"` @@ -112,8 +112,8 @@ func (a *ApplicationInsights) Close() error { select { case <-a.transmitter.Close(): a.Log.Info("Closed") - case <-time.After(a.Timeout.Duration): - a.Log.Warnf("Close operation timed out after %v", a.Timeout.Duration) + case <-time.After(time.Duration(a.Timeout)): + a.Log.Warnf("Close operation timed out after %v", time.Duration(a.Timeout)) } return nil @@ -337,7 +337,7 @@ func toInt(value interface{}) (int, error) { func init() { outputs.Add("application_insights", func() telegraf.Output { return &ApplicationInsights{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), diagMsgSubscriber: diagnosticsMessageSubscriber{}, // It is very common to set Cloud.RoleName and Cloud.RoleInstance context properties, hence initial capacity of two ContextTagSources: make(map[string]string, 2), diff --git a/plugins/outputs/application_insights/application_insights_test.go b/plugins/outputs/application_insights/application_insights_test.go index 8d4fb755646f5..ce36c141b2b52 100644 --- a/plugins/outputs/application_insights/application_insights_test.go +++ b/plugins/outputs/application_insights/application_insights_test.go @@ -9,7 +9,7 @@ import ( "github.com/Microsoft/ApplicationInsights-Go/appinsights" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/outputs/application_insights/mocks" "github.com/stretchr/testify/assert" @@ -25,7 +25,7 @@ func TestConnectFailsIfNoIkey(t *testing.T) { ai := ApplicationInsights{ transmitter: transmitter, // Very long timeout to ensure we do not rely on timeouts for closing the transmitter - Timeout: internal.Duration{Duration: time.Hour}, + Timeout: config.Duration(time.Hour), Log: testutil.Logger{}, } @@ -41,7 +41,7 @@ func TestOutputCloseTimesOut(t *testing.T) { ai := ApplicationInsights{ transmitter: transmitter, - Timeout: internal.Duration{Duration: time.Millisecond * 50}, + Timeout: config.Duration(time.Millisecond * 50), Log: testutil.Logger{}, } @@ -66,7 +66,7 @@ func TestCloseRemovesDiagMsgListener(t *testing.T) { ai := ApplicationInsights{ transmitter: transmitter, - Timeout: internal.Duration{Duration: time.Hour}, + Timeout: config.Duration(time.Hour), EnableDiagnosticLogging: true, diagMsgSubscriber: diagMsgSubscriber, InstrumentationKey: "1234", // Fake, but necessary to enable tracking diff --git a/plugins/outputs/azure_monitor/azure_monitor.go b/plugins/outputs/azure_monitor/azure_monitor.go index c295b553f963a..193c9b2c40c4f 100644 --- a/plugins/outputs/azure_monitor/azure_monitor.go +++ b/plugins/outputs/azure_monitor/azure_monitor.go @@ -16,7 +16,7 @@ import ( "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure/auth" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/selfstat" @@ -25,7 +25,7 @@ import ( // AzureMonitor allows publishing of metrics to the Azure Monitor custom metrics // service type AzureMonitor struct { - Timeout internal.Duration + Timeout config.Duration NamespacePrefix string `toml:"namespace_prefix"` StringsAsDimensions bool `toml:"strings_as_dimensions"` Region string `toml:"region"` @@ -144,15 +144,15 @@ func (a *AzureMonitor) SampleConfig() string { func (a *AzureMonitor) Connect() error { a.cache = make(map[time.Time]map[uint64]*aggregate, 36) - if a.Timeout.Duration == 0 { - a.Timeout.Duration = defaultRequestTimeout + if a.Timeout == 0 { + a.Timeout = config.Duration(defaultRequestTimeout) } a.client = &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: a.Timeout.Duration, + Timeout: time.Duration(a.Timeout), } var err error diff --git a/plugins/outputs/bigquery/bigquery.go b/plugins/outputs/bigquery/bigquery.go index fd1f3c7bc6f4b..41af19d38d88e 100644 --- a/plugins/outputs/bigquery/bigquery.go +++ b/plugins/outputs/bigquery/bigquery.go @@ -13,15 +13,15 @@ import ( "google.golang.org/api/option" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" ) const timeStampFieldName = "timestamp" -var defaultTimeout = internal.Duration{Duration: 5 * time.Second} +var defaultTimeout = config.Duration(5 * time.Second) -const sampleConfig = ` +const sampleConfig = ` ## Credentials File credentials_file = "/path/to/service/account/key.json" @@ -43,8 +43,8 @@ type BigQuery struct { Project string `toml:"project"` Dataset string `toml:"dataset"` - Timeout internal.Duration `toml:"timeout"` - ReplaceHyphenTo string `toml:"replace_hyphen_to"` + Timeout config.Duration `toml:"timeout"` + ReplaceHyphenTo string `toml:"replace_hyphen_to"` Log telegraf.Logger `toml:"-"` @@ -85,7 +85,7 @@ func (s *BigQuery) setUpDefaultClient() error { var credentialsOption option.ClientOption ctx := context.Background() - ctx, cancel := context.WithTimeout(ctx, s.Timeout.Duration) + ctx, cancel := context.WithTimeout(ctx, time.Duration(s.Timeout)) defer cancel() if s.CredentialsFile != "" { @@ -205,7 +205,7 @@ func valueToBqType(v interface{}) bigquery.FieldType { func (s *BigQuery) insertToTable(metricName string, metrics []bigquery.ValueSaver) { ctx := context.Background() - ctx, cancel := context.WithTimeout(ctx, s.Timeout.Duration) + ctx, cancel := context.WithTimeout(ctx, time.Duration(s.Timeout)) defer cancel() tableName := s.metricToTable(metricName) diff --git a/plugins/outputs/bigquery/bigquery_test.go b/plugins/outputs/bigquery/bigquery_test.go index 34d889fcb4c14..dd029f23f7ff6 100644 --- a/plugins/outputs/bigquery/bigquery_test.go +++ b/plugins/outputs/bigquery/bigquery_test.go @@ -10,7 +10,7 @@ import ( "time" "cloud.google.com/go/bigquery" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/require" "google.golang.org/api/option" @@ -21,7 +21,7 @@ const ( ) var testingHost string -var testDuration = internal.Duration{Duration: 5 * time.Second} +var testDuration = config.Duration(5 * time.Second) var receivedBody map[string]json.RawMessage type Row struct { diff --git a/plugins/outputs/cloud_pubsub/pubsub.go b/plugins/outputs/cloud_pubsub/pubsub.go index 9fd89eadf0897..38f037dd13296 100644 --- a/plugins/outputs/cloud_pubsub/pubsub.go +++ b/plugins/outputs/cloud_pubsub/pubsub.go @@ -5,9 +5,11 @@ import ( "encoding/base64" "fmt" "sync" + "time" "cloud.google.com/go/pubsub" "github.com/influxdata/telegraf" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers" @@ -71,12 +73,12 @@ type PubSub struct { Topic string `toml:"topic"` Attributes map[string]string `toml:"attributes"` - SendBatched bool `toml:"send_batched"` - PublishCountThreshold int `toml:"publish_count_threshold"` - PublishByteThreshold int `toml:"publish_byte_threshold"` - PublishNumGoroutines int `toml:"publish_num_go_routines"` - PublishTimeout internal.Duration `toml:"publish_timeout"` - Base64Data bool `toml:"base64_data"` + SendBatched bool `toml:"send_batched"` + PublishCountThreshold int `toml:"publish_count_threshold"` + PublishByteThreshold int `toml:"publish_byte_threshold"` + PublishNumGoroutines int `toml:"publish_num_go_routines"` + PublishTimeout config.Duration `toml:"publish_timeout"` + Base64Data bool `toml:"base64_data"` Log telegraf.Logger `toml:"-"` @@ -190,7 +192,7 @@ func (ps *PubSub) publishSettings() pubsub.PublishSettings { settings.NumGoroutines = ps.PublishNumGoroutines } - if ps.PublishTimeout.Duration > 0 { + if time.Duration(ps.PublishTimeout) > 0 { settings.CountThreshold = 1 } diff --git a/plugins/outputs/cloud_pubsub/topic_stubbed.go b/plugins/outputs/cloud_pubsub/topic_stubbed.go index e23a765366704..c66e573a60115 100644 --- a/plugins/outputs/cloud_pubsub/topic_stubbed.go +++ b/plugins/outputs/cloud_pubsub/topic_stubbed.go @@ -13,7 +13,7 @@ import ( "cloud.google.com/go/pubsub" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/plugins/serializers" "google.golang.org/api/support/bundler" @@ -84,7 +84,7 @@ func getTestResources(tT *testing.T, settings pubsub.PublishSettings, testM []te PublishCountThreshold: settings.CountThreshold, PublishByteThreshold: settings.ByteThreshold, PublishNumGoroutines: settings.NumGoroutines, - PublishTimeout: internal.Duration{Duration: settings.Timeout}, + PublishTimeout: config.Duration(settings.Timeout), } ps.SetSerializer(s) diff --git a/plugins/outputs/cratedb/cratedb.go b/plugins/outputs/cratedb/cratedb.go index 1c8aff47aa248..6e43b58f71563 100644 --- a/plugins/outputs/cratedb/cratedb.go +++ b/plugins/outputs/cratedb/cratedb.go @@ -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/outputs" _ "github.com/jackc/pgx/stdlib" //to register stdlib from PostgreSQL Driver and Toolkit ) @@ -21,7 +21,7 @@ const MaxInt64 = int64(^uint64(0) >> 1) type CrateDB struct { URL string - Timeout internal.Duration + Timeout config.Duration Table string TableCreate bool `toml:"table_create"` DB *sql.DB @@ -55,7 +55,7 @@ CREATE TABLE IF NOT EXISTS ` + c.Table + ` ( PRIMARY KEY ("timestamp", "hash_id","day") ) PARTITIONED BY("day"); ` - ctx, cancel := context.WithTimeout(context.Background(), c.Timeout.Duration) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.Timeout)) defer cancel() if _, err := db.ExecContext(ctx, sql); err != nil { return err @@ -66,7 +66,7 @@ CREATE TABLE IF NOT EXISTS ` + c.Table + ` ( } func (c *CrateDB) Write(metrics []telegraf.Metric) error { - ctx, cancel := context.WithTimeout(context.Background(), c.Timeout.Duration) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(c.Timeout)) defer cancel() if sql, err := insertSQL(c.Table, metrics); err != nil { return err @@ -233,7 +233,7 @@ func (c *CrateDB) Close() error { func init() { outputs.Add("cratedb", func() telegraf.Output { return &CrateDB{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } }) } diff --git a/plugins/outputs/cratedb/cratedb_test.go b/plugins/outputs/cratedb/cratedb_test.go index 43297afe2e5e7..8d7fe1c80ae0a 100644 --- a/plugins/outputs/cratedb/cratedb_test.go +++ b/plugins/outputs/cratedb/cratedb_test.go @@ -9,7 +9,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" "github.com/stretchr/testify/require" @@ -37,7 +37,7 @@ func TestConnectAndWriteIntegration(t *testing.T) { c := &CrateDB{ URL: url, Table: table, - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), TableCreate: true, } diff --git a/plugins/outputs/datadog/datadog.go b/plugins/outputs/datadog/datadog.go index 6b5d4437b63b1..0e019de0eb334 100644 --- a/plugins/outputs/datadog/datadog.go +++ b/plugins/outputs/datadog/datadog.go @@ -8,17 +8,18 @@ import ( "net/http" "net/url" "strings" + "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" ) type Datadog struct { - Apikey string `toml:"apikey"` - Timeout internal.Duration `toml:"timeout"` - URL string `toml:"url"` - Log telegraf.Logger `toml:"-"` + Apikey string `toml:"apikey"` + Timeout config.Duration `toml:"timeout"` + URL string `toml:"url"` + Log telegraf.Logger `toml:"-"` client *http.Client } @@ -58,7 +59,7 @@ func (d *Datadog) Connect() error { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: d.Timeout.Duration, + Timeout: time.Duration(d.Timeout), } return nil } diff --git a/plugins/outputs/dynatrace/dynatrace.go b/plugins/outputs/dynatrace/dynatrace.go index 2c57d6fc584a0..0b13f5886fd83 100644 --- a/plugins/outputs/dynatrace/dynatrace.go +++ b/plugins/outputs/dynatrace/dynatrace.go @@ -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/common/tls" "github.com/influxdata/telegraf/plugins/outputs" ) @@ -31,12 +31,12 @@ var ( // Dynatrace Configuration for the Dynatrace output plugin type Dynatrace struct { - URL string `toml:"url"` - APIToken string `toml:"api_token"` - Prefix string `toml:"prefix"` - Log telegraf.Logger `toml:"-"` - Timeout internal.Duration `toml:"timeout"` - AddCounterMetrics []string `toml:"additional_counters"` + URL string `toml:"url"` + APIToken string `toml:"api_token"` + Prefix string `toml:"prefix"` + Log telegraf.Logger `toml:"-"` + Timeout config.Duration `toml:"timeout"` + AddCounterMetrics []string `toml:"additional_counters"` State map[string]string SendCounter int @@ -312,7 +312,7 @@ func (d *Dynatrace) Init() error { Proxy: http.ProxyFromEnvironment, TLSClientConfig: tlsCfg, }, - Timeout: d.Timeout.Duration, + Timeout: time.Duration(d.Timeout), } return nil } @@ -320,7 +320,7 @@ func (d *Dynatrace) Init() error { func init() { outputs.Add("dynatrace", func() telegraf.Output { return &Dynatrace{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), SendCounter: 0, } }) diff --git a/plugins/outputs/dynatrace/dynatrace_test.go b/plugins/outputs/dynatrace/dynatrace_test.go index 45f4f24d7d73e..6dc558836a59c 100644 --- a/plugins/outputs/dynatrace/dynatrace_test.go +++ b/plugins/outputs/dynatrace/dynatrace_test.go @@ -3,7 +3,7 @@ package dynatrace import ( "encoding/json" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/require" @@ -22,7 +22,7 @@ func TestNilMetrics(t *testing.T) { defer ts.Close() d := &Dynatrace{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } d.URL = ts.URL diff --git a/plugins/outputs/elasticsearch/elasticsearch.go b/plugins/outputs/elasticsearch/elasticsearch.go index c41495ec07df5..6d85b7e97742f 100644 --- a/plugins/outputs/elasticsearch/elasticsearch.go +++ b/plugins/outputs/elasticsearch/elasticsearch.go @@ -14,7 +14,7 @@ import ( "crypto/sha256" "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/outputs" "gopkg.in/olivere/elastic.v5" @@ -28,8 +28,8 @@ type Elasticsearch struct { Username string Password string EnableSniffer bool - Timeout internal.Duration - HealthCheckInterval internal.Duration + Timeout config.Duration + HealthCheckInterval config.Duration ManageTemplate bool TemplateName string OverwriteTemplate bool @@ -174,7 +174,7 @@ func (a *Elasticsearch) Connect() error { return fmt.Errorf("Elasticsearch urls or index_name is not defined") } - ctx, cancel := context.WithTimeout(context.Background(), a.Timeout.Duration) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.Timeout)) defer cancel() var clientOptions []elastic.ClientOptionFunc @@ -189,14 +189,14 @@ func (a *Elasticsearch) Connect() error { httpclient := &http.Client{ Transport: tr, - Timeout: a.Timeout.Duration, + Timeout: time.Duration(a.Timeout), } clientOptions = append(clientOptions, elastic.SetHttpClient(httpclient), elastic.SetSniff(a.EnableSniffer), elastic.SetURL(a.URLs...), - elastic.SetHealthcheckInterval(a.HealthCheckInterval.Duration), + elastic.SetHealthcheckInterval(time.Duration(a.HealthCheckInterval)), ) if a.Username != "" && a.Password != "" { @@ -205,7 +205,7 @@ func (a *Elasticsearch) Connect() error { ) } - if a.HealthCheckInterval.Duration == 0 { + if time.Duration(a.HealthCheckInterval) == 0 { clientOptions = append(clientOptions, elastic.SetHealthcheck(false), ) @@ -295,7 +295,7 @@ func (a *Elasticsearch) Write(metrics []telegraf.Metric) error { bulkRequest.Add(br) } - ctx, cancel := context.WithTimeout(context.Background(), a.Timeout.Duration) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(a.Timeout)) defer cancel() res, err := bulkRequest.Do(ctx) @@ -438,8 +438,8 @@ func (a *Elasticsearch) Close() error { func init() { outputs.Add("elasticsearch", func() telegraf.Output { return &Elasticsearch{ - Timeout: internal.Duration{Duration: time.Second * 5}, - HealthCheckInterval: internal.Duration{Duration: time.Second * 10}, + Timeout: config.Duration(time.Second * 5), + HealthCheckInterval: config.Duration(time.Second * 10), } }) } diff --git a/plugins/outputs/elasticsearch/elasticsearch_test.go b/plugins/outputs/elasticsearch/elasticsearch_test.go index d21d191cb0e52..baf6e3162555c 100644 --- a/plugins/outputs/elasticsearch/elasticsearch_test.go +++ b/plugins/outputs/elasticsearch/elasticsearch_test.go @@ -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" ) @@ -21,11 +21,11 @@ func TestConnectAndWriteIntegration(t *testing.T) { e := &Elasticsearch{ URLs: urls, IndexName: "test-%Y.%m.%d", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), ManageTemplate: true, TemplateName: "telegraf", OverwriteTemplate: false, - HealthCheckInterval: internal.Duration{Duration: time.Second * 10}, + HealthCheckInterval: config.Duration(time.Second * 10), } // Verify that we can connect to Elasticsearch @@ -49,7 +49,7 @@ func TestTemplateManagementEmptyTemplateIntegration(t *testing.T) { e := &Elasticsearch{ URLs: urls, IndexName: "test-%Y.%m.%d", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), ManageTemplate: true, TemplateName: "", OverwriteTemplate: true, @@ -69,13 +69,13 @@ func TestTemplateManagementIntegration(t *testing.T) { e := &Elasticsearch{ URLs: urls, IndexName: "test-%Y.%m.%d", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), ManageTemplate: true, TemplateName: "telegraf", OverwriteTemplate: true, } - ctx, cancel := context.WithTimeout(context.Background(), e.Timeout.Duration) + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(e.Timeout)) defer cancel() err := e.Connect() @@ -95,7 +95,7 @@ func TestTemplateInvalidIndexPatternIntegration(t *testing.T) { e := &Elasticsearch{ URLs: urls, IndexName: "{{host}}-%Y.%m.%d", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), ManageTemplate: true, TemplateName: "telegraf", OverwriteTemplate: true, diff --git a/plugins/outputs/exec/exec.go b/plugins/outputs/exec/exec.go index 25637bd1984c0..b0313a382045a 100644 --- a/plugins/outputs/exec/exec.go +++ b/plugins/outputs/exec/exec.go @@ -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/outputs" "github.com/influxdata/telegraf/plugins/serializers" @@ -19,8 +20,8 @@ const maxStderrBytes = 512 // Exec defines the exec output plugin. type Exec struct { - Command []string `toml:"command"` - Timeout internal.Duration `toml:"timeout"` + Command []string `toml:"command"` + Timeout config.Duration `toml:"timeout"` runner Runner serializer serializers.Serializer @@ -82,7 +83,7 @@ func (e *Exec) Write(metrics []telegraf.Metric) error { return nil } - return e.runner.Run(e.Timeout.Duration, e.Command, &buffer) + return e.runner.Run(time.Duration(e.Timeout), e.Command, &buffer) } // Runner provides an interface for running exec.Cmd. @@ -155,7 +156,7 @@ func init() { outputs.Add("exec", func() telegraf.Output { return &Exec{ runner: &CommandRunner{}, - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } }) } diff --git a/plugins/outputs/exec/exec_test.go b/plugins/outputs/exec/exec_test.go index f57bf50a1b571..e75e1829d3894 100644 --- a/plugins/outputs/exec/exec_test.go +++ b/plugins/outputs/exec/exec_test.go @@ -7,7 +7,7 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/serializers" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/require" @@ -52,7 +52,7 @@ func TestExec(t *testing.T) { t.Run(tt.name, func(t *testing.T) { e := &Exec{ Command: tt.command, - Timeout: internal.Duration{Duration: time.Second}, + Timeout: config.Duration(time.Second), runner: &CommandRunner{}, } diff --git a/plugins/outputs/file/file.go b/plugins/outputs/file/file.go index 16cb923ee2db5..0c8ff903e97bc 100644 --- a/plugins/outputs/file/file.go +++ b/plugins/outputs/file/file.go @@ -4,21 +4,22 @@ import ( "fmt" "io" "os" + "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/internal/rotate" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers" ) type File struct { - Files []string `toml:"files"` - RotationInterval internal.Duration `toml:"rotation_interval"` - RotationMaxSize internal.Size `toml:"rotation_max_size"` - RotationMaxArchives int `toml:"rotation_max_archives"` - UseBatchFormat bool `toml:"use_batch_format"` - Log telegraf.Logger `toml:"-"` + Files []string `toml:"files"` + RotationInterval config.Duration `toml:"rotation_interval"` + RotationMaxSize config.Size `toml:"rotation_max_size"` + RotationMaxArchives int `toml:"rotation_max_archives"` + UseBatchFormat bool `toml:"use_batch_format"` + Log telegraf.Logger `toml:"-"` writer io.Writer closers []io.Closer @@ -69,7 +70,7 @@ func (f *File) Connect() error { writers = append(writers, os.Stdout) } else { of, err := rotate.NewFileWriter( - file, f.RotationInterval.Duration, f.RotationMaxSize.Size, f.RotationMaxArchives) + file, time.Duration(f.RotationInterval), int64(f.RotationMaxSize), f.RotationMaxArchives) if err != nil { return err } diff --git a/plugins/outputs/health/health.go b/plugins/outputs/health/health.go index 7447c404c9b2d..4541659cec030 100644 --- a/plugins/outputs/health/health.go +++ b/plugins/outputs/health/health.go @@ -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/outputs" @@ -67,11 +68,11 @@ type Checker interface { } type Health struct { - ServiceAddress string `toml:"service_address"` - ReadTimeout internal.Duration `toml:"read_timeout"` - WriteTimeout internal.Duration `toml:"write_timeout"` - BasicUsername string `toml:"basic_username"` - BasicPassword string `toml:"basic_password"` + ServiceAddress string `toml:"service_address"` + ReadTimeout config.Duration `toml:"read_timeout"` + WriteTimeout config.Duration `toml:"write_timeout"` + BasicUsername string `toml:"basic_username"` + BasicPassword string `toml:"basic_password"` tlsint.ServerConfig Compares []*Compares `toml:"compares"` @@ -141,8 +142,8 @@ func (h *Health) Connect() error { h.server = &http.Server{ Addr: h.ServiceAddress, Handler: authHandler(h), - ReadTimeout: h.ReadTimeout.Duration, - WriteTimeout: h.WriteTimeout.Duration, + ReadTimeout: time.Duration(h.ReadTimeout), + WriteTimeout: time.Duration(h.WriteTimeout), TLSConfig: h.tlsConf, } @@ -257,8 +258,8 @@ func (h *Health) isHealthy() bool { func NewHealth() *Health { return &Health{ ServiceAddress: defaultServiceAddress, - ReadTimeout: internal.Duration{Duration: defaultReadTimeout}, - WriteTimeout: internal.Duration{Duration: defaultWriteTimeout}, + ReadTimeout: config.Duration(defaultReadTimeout), + WriteTimeout: config.Duration(defaultWriteTimeout), healthy: true, } } diff --git a/plugins/outputs/http/http.go b/plugins/outputs/http/http.go index 53d51f3e7c0e1..82ae230eceb0f 100644 --- a/plugins/outputs/http/http.go +++ b/plugins/outputs/http/http.go @@ -11,6 +11,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/outputs" @@ -79,7 +80,7 @@ const ( type HTTP struct { URL string `toml:"url"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` Method string `toml:"method"` Username string `toml:"username"` Password string `toml:"password"` @@ -89,7 +90,7 @@ type HTTP struct { TokenURL string `toml:"token_url"` Scopes []string `toml:"scopes"` ContentEncoding string `toml:"content_encoding"` - IdleConnTimeout internal.Duration `toml:"idle_conn_timeout"` + IdleConnTimeout config.Duration `toml:"idle_conn_timeout"` tls.ClientConfig client *http.Client @@ -110,9 +111,9 @@ func (h *HTTP) createClient(ctx context.Context) (*http.Client, error) { Transport: &http.Transport{ TLSClientConfig: tlsCfg, Proxy: http.ProxyFromEnvironment, - IdleConnTimeout: h.IdleConnTimeout.Duration, + IdleConnTimeout: time.Duration(h.IdleConnTimeout), }, - Timeout: h.Timeout.Duration, + Timeout: time.Duration(h.Timeout), } if h.ClientID != "" && h.ClientSecret != "" && h.TokenURL != "" { @@ -138,8 +139,8 @@ func (h *HTTP) Connect() error { return fmt.Errorf("invalid method [%s] %s", h.URL, h.Method) } - if h.Timeout.Duration == 0 { - h.Timeout.Duration = defaultClientTimeout + if h.Timeout == 0 { + h.Timeout = config.Duration(defaultClientTimeout) } ctx := context.Background() @@ -228,7 +229,7 @@ func (h *HTTP) write(reqBody []byte) error { func init() { outputs.Add("http", func() telegraf.Output { return &HTTP{ - Timeout: internal.Duration{Duration: defaultClientTimeout}, + Timeout: config.Duration(defaultClientTimeout), Method: defaultMethod, URL: defaultURL, } diff --git a/plugins/outputs/influxdb/influxdb.go b/plugins/outputs/influxdb/influxdb.go index 49ca7d6435249..0bb4c01cc6996 100644 --- a/plugins/outputs/influxdb/influxdb.go +++ b/plugins/outputs/influxdb/influxdb.go @@ -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/common/tls" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers/influx" @@ -43,8 +43,8 @@ type InfluxDB struct { ExcludeRetentionPolicyTag bool `toml:"exclude_retention_policy_tag"` UserAgent string `toml:"user_agent"` WriteConsistency string `toml:"write_consistency"` - Timeout internal.Duration `toml:"timeout"` - UDPPayload internal.Size `toml:"udp_payload"` + Timeout config.Duration `toml:"timeout"` + UDPPayload config.Size `toml:"udp_payload"` HTTPProxy string `toml:"http_proxy"` HTTPHeaders map[string]string `toml:"http_headers"` ContentEncoding string `toml:"content_encoding"` @@ -239,7 +239,7 @@ func (i *InfluxDB) Write(metrics []telegraf.Metric) error { func (i *InfluxDB) udpClient(url *url.URL) (Client, error) { config := &UDPConfig{ URL: url, - MaxPayloadSize: int(i.UDPPayload.Size), + MaxPayloadSize: int(i.UDPPayload), Serializer: i.newSerializer(), Log: i.Log, } @@ -260,7 +260,7 @@ func (i *InfluxDB) httpClient(ctx context.Context, url *url.URL, proxy *url.URL) config := &HTTPConfig{ URL: url, - Timeout: i.Timeout.Duration, + Timeout: time.Duration(i.Timeout), TLSConfig: tlsConfig, UserAgent: i.UserAgent, Username: i.Username, @@ -308,7 +308,7 @@ func (i *InfluxDB) newSerializer() *influx.Serializer { func init() { outputs.Add("influxdb", func() telegraf.Output { return &InfluxDB{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), CreateHTTPClientF: func(config *HTTPConfig) (Client, error) { return NewHTTPClient(*config) }, diff --git a/plugins/outputs/influxdb/influxdb_test.go b/plugins/outputs/influxdb/influxdb_test.go index 476211069af7b..9de246ec7f3f7 100644 --- a/plugins/outputs/influxdb/influxdb_test.go +++ b/plugins/outputs/influxdb/influxdb_test.go @@ -7,7 +7,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/plugins/common/tls" "github.com/influxdata/telegraf/plugins/outputs/influxdb" @@ -95,7 +95,7 @@ func TestConnectUDPConfig(t *testing.T) { output := influxdb.InfluxDB{ URLs: []string{"udp://localhost:8089"}, - UDPPayload: internal.Size{Size: 42}, + UDPPayload: config.Size(42), CreateUDPClientF: func(config *influxdb.UDPConfig) (influxdb.Client, error) { actual = config @@ -120,7 +120,7 @@ func TestConnectHTTPConfig(t *testing.T) { Database: "telegraf", RetentionPolicy: "default", WriteConsistency: "any", - Timeout: internal.Duration{Duration: 5 * time.Second}, + Timeout: config.Duration(5 * time.Second), Username: "guy", Password: "smiley", UserAgent: "telegraf", @@ -153,7 +153,7 @@ func TestConnectHTTPConfig(t *testing.T) { require.Equal(t, output.URLs[0], actual.URL.String()) require.Equal(t, output.UserAgent, actual.UserAgent) - require.Equal(t, output.Timeout.Duration, actual.Timeout) + require.Equal(t, time.Duration(output.Timeout), actual.Timeout) require.Equal(t, output.Username, actual.Username) require.Equal(t, output.Password, actual.Password) require.Equal(t, output.HTTPProxy, actual.Proxy.String()) diff --git a/plugins/outputs/influxdb_v2/influxdb.go b/plugins/outputs/influxdb_v2/influxdb.go index c7dd20a5ca0db..e188ddbae94d1 100644 --- a/plugins/outputs/influxdb_v2/influxdb.go +++ b/plugins/outputs/influxdb_v2/influxdb.go @@ -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/common/tls" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers/influx" @@ -87,7 +87,7 @@ type InfluxDB struct { Bucket string `toml:"bucket"` BucketTag string `toml:"bucket_tag"` ExcludeBucketTag bool `toml:"exclude_bucket_tag"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` HTTPHeaders map[string]string `toml:"http_headers"` HTTPProxy string `toml:"http_proxy"` UserAgent string `toml:"user_agent"` @@ -183,7 +183,7 @@ func (i *InfluxDB) getHTTPClient(url *url.URL, proxy *url.URL) (Client, error) { Bucket: i.Bucket, BucketTag: i.BucketTag, ExcludeBucketTag: i.ExcludeBucketTag, - Timeout: i.Timeout.Duration, + Timeout: time.Duration(i.Timeout), Headers: i.HTTPHeaders, Proxy: proxy, UserAgent: i.UserAgent, @@ -212,7 +212,7 @@ func (i *InfluxDB) newSerializer() *influx.Serializer { func init() { outputs.Add("influxdb_v2", func() telegraf.Output { return &InfluxDB{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), ContentEncoding: "gzip", } }) diff --git a/plugins/outputs/instrumental/instrumental.go b/plugins/outputs/instrumental/instrumental.go index ab6f05f866f4e..87148ed08d9d9 100644 --- a/plugins/outputs/instrumental/instrumental.go +++ b/plugins/outputs/instrumental/instrumental.go @@ -7,9 +7,10 @@ import ( "net" "regexp" "strings" + "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers" "github.com/influxdata/telegraf/plugins/serializers/graphite" @@ -21,14 +22,14 @@ var ( ) type Instrumental struct { - Host string `toml:"host"` - APIToken string `toml:"api_token"` - Prefix string `toml:"prefix"` - DataFormat string `toml:"data_format"` - Template string `toml:"template"` - Templates []string `toml:"templates"` - Timeout internal.Duration `toml:"timeout"` - Debug bool `toml:"debug"` + Host string `toml:"host"` + APIToken string `toml:"api_token"` + Prefix string `toml:"prefix"` + DataFormat string `toml:"data_format"` + Template string `toml:"template"` + Templates []string `toml:"templates"` + Timeout config.Duration `toml:"timeout"` + Debug bool `toml:"debug"` Log telegraf.Logger `toml:"-"` @@ -57,7 +58,7 @@ var sampleConfig = ` ` func (i *Instrumental) Connect() error { - connection, err := net.DialTimeout("tcp", i.Host+":8000", i.Timeout.Duration) + connection, err := net.DialTimeout("tcp", i.Host+":8000", time.Duration(i.Timeout)) if err != nil { i.conn = nil diff --git a/plugins/outputs/librato/librato.go b/plugins/outputs/librato/librato.go index 1d9f6725206a8..d4aa3e6e92bb7 100644 --- a/plugins/outputs/librato/librato.go +++ b/plugins/outputs/librato/librato.go @@ -7,22 +7,23 @@ import ( "io/ioutil" "net/http" "regexp" + "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" "github.com/influxdata/telegraf/plugins/serializers/graphite" ) // Librato structure for configuration and client type Librato struct { - APIUser string `toml:"api_user"` - APIToken string `toml:"api_token"` - Debug bool `toml:"debug"` - SourceTag string `toml:"source_tag"` // Deprecated, keeping for backward-compatibility - Timeout internal.Duration `toml:"timeout"` - Template string `toml:"template"` - Log telegraf.Logger `toml:"-"` + APIUser string `toml:"api_user"` + APIToken string `toml:"api_token"` + Debug bool `toml:"debug"` + SourceTag string `toml:"source_tag"` // Deprecated, keeping for backward-compatibility + Timeout config.Duration `toml:"timeout"` + Template string `toml:"template"` + Log telegraf.Logger `toml:"-"` APIUrl string client *http.Client @@ -83,7 +84,7 @@ func (l *Librato) Connect() error { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: l.Timeout.Duration, + Timeout: time.Duration(l.Timeout), } return nil } diff --git a/plugins/outputs/logzio/logzio.go b/plugins/outputs/logzio/logzio.go index b0ca8c7b3bc80..caec293b1c46f 100644 --- a/plugins/outputs/logzio/logzio.go +++ b/plugins/outputs/logzio/logzio.go @@ -10,7 +10,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/outputs" ) @@ -39,10 +39,10 @@ var sampleConfig = ` ` type Logzio struct { - Log telegraf.Logger `toml:"-"` - Timeout internal.Duration `toml:"timeout"` - Token string `toml:"token"` - URL string `toml:"url"` + Log telegraf.Logger `toml:"-"` + Timeout config.Duration `toml:"timeout"` + Token string `toml:"token"` + URL string `toml:"url"` tls.ClientConfig client *http.Client @@ -77,7 +77,7 @@ func (l *Logzio) Connect() error { Proxy: http.ProxyFromEnvironment, TLSClientConfig: tlsCfg, }, - Timeout: l.Timeout.Duration, + Timeout: time.Duration(l.Timeout), } return nil @@ -169,7 +169,7 @@ func init() { outputs.Add("logzio", func() telegraf.Output { return &Logzio{ URL: defaultLogzioURL, - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } }) } diff --git a/plugins/outputs/loki/loki.go b/plugins/outputs/loki/loki.go index c097d21fd8bf0..21cc66776d682 100644 --- a/plugins/outputs/loki/loki.go +++ b/plugins/outputs/loki/loki.go @@ -11,6 +11,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/outputs" @@ -52,7 +53,7 @@ var sampleConfig = ` type Loki struct { Domain string `toml:"domain"` Endpoint string `toml:"endpoint"` - Timeout internal.Duration `toml:"timeout"` + Timeout config.Duration `toml:"timeout"` Username string `toml:"username"` Password string `toml:"password"` Headers map[string]string `toml:"headers"` @@ -86,7 +87,7 @@ func (l *Loki) createClient(ctx context.Context) (*http.Client, error) { TLSClientConfig: tlsCfg, Proxy: http.ProxyFromEnvironment, }, - Timeout: l.Timeout.Duration, + Timeout: time.Duration(l.Timeout), } if l.ClientID != "" && l.ClientSecret != "" && l.TokenURL != "" { @@ -114,8 +115,8 @@ func (l *Loki) Connect() (err error) { l.url = fmt.Sprintf("%s%s", l.Domain, l.Endpoint) - if l.Timeout.Duration == 0 { - l.Timeout.Duration = defaultClientTimeout + if l.Timeout == 0 { + l.Timeout = config.Duration(defaultClientTimeout) } ctx := context.Background() diff --git a/plugins/outputs/mqtt/mqtt.go b/plugins/outputs/mqtt/mqtt.go index 0e07b1bca8ab7..584a79ffd2ef1 100644 --- a/plugins/outputs/mqtt/mqtt.go +++ b/plugins/outputs/mqtt/mqtt.go @@ -9,6 +9,7 @@ import ( paho "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/outputs" @@ -66,7 +67,7 @@ type MQTT struct { Username string Password string Database string - Timeout internal.Duration + Timeout config.Duration TopicPrefix string QoS int `toml:"qos"` ClientID string `toml:"client_id"` @@ -180,7 +181,7 @@ func (m *MQTT) Write(metrics []telegraf.Metric) error { func (m *MQTT) publish(topic string, body []byte) error { token := m.client.Publish(topic, byte(m.QoS), m.Retain, body) - token.WaitTimeout(m.Timeout.Duration) + token.WaitTimeout(time.Duration(m.Timeout)) if token.Error() != nil { return token.Error() } @@ -191,10 +192,10 @@ func (m *MQTT) createOpts() (*paho.ClientOptions, error) { opts := paho.NewClientOptions() opts.KeepAlive = 0 - if m.Timeout.Duration < time.Second { - m.Timeout.Duration = 5 * time.Second + if m.Timeout < config.Duration(time.Second) { + m.Timeout = config.Duration(5 * time.Second) } - opts.WriteTimeout = m.Timeout.Duration + opts.WriteTimeout = time.Duration(m.Timeout) if m.ClientID != "" { opts.SetClientID(m.ClientID) diff --git a/plugins/outputs/newrelic/newrelic.go b/plugins/outputs/newrelic/newrelic.go index ccd8b50d70b11..4f67c5de06914 100644 --- a/plugins/outputs/newrelic/newrelic.go +++ b/plugins/outputs/newrelic/newrelic.go @@ -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/outputs" "github.com/newrelic/newrelic-telemetry-sdk-go/cumulative" "github.com/newrelic/newrelic-telemetry-sdk-go/telemetry" @@ -17,10 +17,10 @@ import ( // NewRelic nr structure type NewRelic struct { - InsightsKey string `toml:"insights_key"` - MetricPrefix string `toml:"metric_prefix"` - Timeout internal.Duration `toml:"timeout"` - HTTPProxy string `toml:"http_proxy"` + InsightsKey string `toml:"insights_key"` + MetricPrefix string `toml:"metric_prefix"` + Timeout config.Duration `toml:"timeout"` + HTTPProxy string `toml:"http_proxy"` harvestor *telemetry.Harvester dc *cumulative.DeltaCalculator @@ -67,7 +67,7 @@ func (nr *NewRelic) Connect() error { func(cfg *telemetry.Config) { cfg.Product = "NewRelic-Telegraf-Plugin" cfg.ProductVersion = "1.0" - cfg.HarvestTimeout = nr.Timeout.Duration + cfg.HarvestTimeout = time.Duration(nr.Timeout) cfg.Client = &nr.client cfg.ErrorLogger = func(e map[string]interface{}) { var errorString string @@ -161,7 +161,7 @@ func (nr *NewRelic) Write(metrics []telegraf.Metric) error { func init() { outputs.Add("newrelic", func() telegraf.Output { return &NewRelic{ - Timeout: internal.Duration{Duration: time.Second * 15}, + Timeout: config.Duration(time.Second * 15), } }) } diff --git a/plugins/outputs/newrelic/newrelic_test.go b/plugins/outputs/newrelic/newrelic_test.go index 2d679bf3cecbc..7071176fcfae8 100644 --- a/plugins/outputs/newrelic/newrelic_test.go +++ b/plugins/outputs/newrelic/newrelic_test.go @@ -6,7 +6,7 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" "github.com/newrelic/newrelic-telemetry-sdk-go/telemetry" "github.com/stretchr/testify/assert" @@ -17,7 +17,7 @@ func TestBasic(t *testing.T) { nr := &NewRelic{ MetricPrefix: "Test", InsightsKey: "12345", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } if testing.Short() { t.Skip("skipping test in short mode.") @@ -161,7 +161,7 @@ func TestNewRelic_Connect(t *testing.T) { name: "Test: Insights key and Timeout", newrelic: &NewRelic{ InsightsKey: "12312133", - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), }, wantErr: false, }, diff --git a/plugins/outputs/prometheus_client/prometheus_client.go b/plugins/outputs/prometheus_client/prometheus_client.go index b9ef7c3a6eb47..a37404f268056 100644 --- a/plugins/outputs/prometheus_client/prometheus_client.go +++ b/plugins/outputs/prometheus_client/prometheus_client.go @@ -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/outputs" @@ -23,7 +24,7 @@ import ( var ( defaultListen = ":9273" defaultPath = "/metrics" - defaultExpirationInterval = internal.Duration{Duration: 60 * time.Second} + defaultExpirationInterval = config.Duration(60 * time.Second) ) var sampleConfig = ` @@ -79,16 +80,16 @@ type Collector interface { } type PrometheusClient struct { - Listen string `toml:"listen"` - MetricVersion int `toml:"metric_version"` - BasicUsername string `toml:"basic_username"` - BasicPassword string `toml:"basic_password"` - IPRange []string `toml:"ip_range"` - ExpirationInterval internal.Duration `toml:"expiration_interval"` - Path string `toml:"path"` - CollectorsExclude []string `toml:"collectors_exclude"` - StringAsLabel bool `toml:"string_as_label"` - ExportTimestamp bool `toml:"export_timestamp"` + Listen string `toml:"listen"` + MetricVersion int `toml:"metric_version"` + BasicUsername string `toml:"basic_username"` + BasicPassword string `toml:"basic_password"` + IPRange []string `toml:"ip_range"` + ExpirationInterval config.Duration `toml:"expiration_interval"` + Path string `toml:"path"` + CollectorsExclude []string `toml:"collectors_exclude"` + StringAsLabel bool `toml:"string_as_label"` + ExportTimestamp bool `toml:"export_timestamp"` tlsint.ServerConfig Log telegraf.Logger `toml:"-"` @@ -133,13 +134,13 @@ func (p *PrometheusClient) Init() error { fallthrough case 1: p.Log.Warnf("Use of deprecated configuration: metric_version = 1; please update to metric_version = 2") - p.collector = v1.NewCollector(p.ExpirationInterval.Duration, p.StringAsLabel, p.Log) + p.collector = v1.NewCollector(time.Duration(p.ExpirationInterval), p.StringAsLabel, p.Log) err := registry.Register(p.collector) if err != nil { return err } case 2: - p.collector = v2.NewCollector(p.ExpirationInterval.Duration, p.StringAsLabel, p.ExportTimestamp) + p.collector = v2.NewCollector(time.Duration(p.ExpirationInterval), p.StringAsLabel, p.ExportTimestamp) err := registry.Register(p.collector) if err != nil { return err diff --git a/plugins/outputs/riemann/riemann.go b/plugins/outputs/riemann/riemann.go index 9c202d8cf9af3..bad1e44a0c1a1 100644 --- a/plugins/outputs/riemann/riemann.go +++ b/plugins/outputs/riemann/riemann.go @@ -10,21 +10,21 @@ import ( "github.com/amir/raidman" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/outputs" ) type Riemann struct { - URL string `toml:"url"` - TTL float32 `toml:"ttl"` - Separator string `toml:"separator"` - MeasurementAsAttribute bool `toml:"measurement_as_attribute"` - StringAsState bool `toml:"string_as_state"` - TagKeys []string `toml:"tag_keys"` - Tags []string `toml:"tags"` - DescriptionText string `toml:"description_text"` - Timeout internal.Duration `toml:"timeout"` - Log telegraf.Logger `toml:"-"` + URL string `toml:"url"` + TTL float32 `toml:"ttl"` + Separator string `toml:"separator"` + MeasurementAsAttribute bool `toml:"measurement_as_attribute"` + StringAsState bool `toml:"string_as_state"` + TagKeys []string `toml:"tag_keys"` + Tags []string `toml:"tags"` + DescriptionText string `toml:"description_text"` + Timeout config.Duration `toml:"timeout"` + Log telegraf.Logger `toml:"-"` client *raidman.Client } @@ -68,7 +68,7 @@ func (r *Riemann) Connect() error { return err } - client, err := raidman.DialWithTimeout(parsedURL.Scheme, parsedURL.Host, r.Timeout.Duration) + client, err := raidman.DialWithTimeout(parsedURL.Scheme, parsedURL.Host, time.Duration(r.Timeout)) if err != nil { r.client = nil return err @@ -217,7 +217,7 @@ func (r *Riemann) tags(tags map[string]string) []string { func init() { outputs.Add("riemann", func() telegraf.Output { return &Riemann{ - Timeout: internal.Duration{Duration: time.Second * 5}, + Timeout: config.Duration(time.Second * 5), } }) } diff --git a/plugins/outputs/socket_writer/socket_writer.go b/plugins/outputs/socket_writer/socket_writer.go index dae7edc0e806f..2546faa6779d7 100644 --- a/plugins/outputs/socket_writer/socket_writer.go +++ b/plugins/outputs/socket_writer/socket_writer.go @@ -6,8 +6,10 @@ import ( "log" "net" "strings" + "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/outputs" @@ -17,7 +19,7 @@ import ( type SocketWriter struct { ContentEncoding string `toml:"content_encoding"` Address string - KeepAlivePeriod *internal.Duration + KeepAlivePeriod *config.Duration tlsint.ClientConfig serializers.Serializer @@ -117,13 +119,13 @@ func (sw *SocketWriter) setKeepAlive(c net.Conn) error { if !ok { return fmt.Errorf("cannot set keep alive on a %s socket", strings.SplitN(sw.Address, "://", 2)[0]) } - if sw.KeepAlivePeriod.Duration == 0 { + if *sw.KeepAlivePeriod == 0 { return tcpc.SetKeepAlive(false) } if err := tcpc.SetKeepAlive(true); err != nil { return err } - return tcpc.SetKeepAlivePeriod(sw.KeepAlivePeriod.Duration) + return tcpc.SetKeepAlivePeriod(time.Duration(*sw.KeepAlivePeriod)) } // Write writes the given metrics to the destination. diff --git a/plugins/outputs/sumologic/sumologic.go b/plugins/outputs/sumologic/sumologic.go index 22b64a8e6a114..088210b9d1ff9 100644 --- a/plugins/outputs/sumologic/sumologic.go +++ b/plugins/outputs/sumologic/sumologic.go @@ -27,7 +27,7 @@ const ( ## Data format to be used for sending metrics. ## This will set the "Content-Type" header accordingly. - ## Currently supported formats: + ## Currently supported formats: ## * graphite - for Content-Type of application/vnd.sumologic.graphite ## * carbon2 - for Content-Type of application/vnd.sumologic.carbon2 ## * prometheus - for Content-Type of application/vnd.sumologic.prometheus @@ -42,7 +42,7 @@ const ( ## Timeout used for HTTP request # timeout = "5s" - + ## Max HTTP request body size in bytes before compression (if applied). ## By default 1MB is recommended. ## NOTE: @@ -92,9 +92,9 @@ const ( ) type SumoLogic struct { - URL string `toml:"url"` - Timeout internal.Duration `toml:"timeout"` - MaxRequstBodySize config.Size `toml:"max_request_body_size"` + URL string `toml:"url"` + Timeout config.Duration `toml:"timeout"` + MaxRequstBodySize config.Size `toml:"max_request_body_size"` SourceName string `toml:"source_name"` SourceHost string `toml:"source_host"` @@ -143,7 +143,7 @@ func (s *SumoLogic) createClient() *http.Client { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: s.Timeout.Duration, + Timeout: time.Duration(s.Timeout), } } @@ -152,8 +152,8 @@ func (s *SumoLogic) Connect() error { return errors.Wrap(s.err, "sumologic: incorrect configuration") } - if s.Timeout.Duration == 0 { - s.Timeout.Duration = defaultClientTimeout + if s.Timeout == 0 { + s.Timeout = config.Duration(defaultClientTimeout) } s.client = s.createClient() @@ -329,9 +329,7 @@ func setHeaderIfSetInConfig(r *http.Request, h header, value string) { func Default() *SumoLogic { return &SumoLogic{ - Timeout: internal.Duration{ - Duration: defaultClientTimeout, - }, + Timeout: config.Duration(defaultClientTimeout), MaxRequstBodySize: defaultMaxRequestBodySize, headers: make(map[string]string), } diff --git a/plugins/outputs/syslog/syslog.go b/plugins/outputs/syslog/syslog.go index 1b46d02e210b0..39f1f6ec5817d 100644 --- a/plugins/outputs/syslog/syslog.go +++ b/plugins/outputs/syslog/syslog.go @@ -7,11 +7,12 @@ import ( "net" "strconv" "strings" + "time" "github.com/influxdata/go-syslog/v2/nontransparent" "github.com/influxdata/go-syslog/v2/rfc5424" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" framing "github.com/influxdata/telegraf/internal/syslog" tlsint "github.com/influxdata/telegraf/plugins/common/tls" "github.com/influxdata/telegraf/plugins/outputs" @@ -19,7 +20,7 @@ import ( type Syslog struct { Address string - KeepAlivePeriod *internal.Duration + KeepAlivePeriod *config.Duration DefaultSdid string DefaultSeverityCode uint8 DefaultFacilityCode uint8 @@ -149,13 +150,13 @@ func (s *Syslog) setKeepAlive(c net.Conn) error { if !ok { return fmt.Errorf("cannot set keep alive on a %s socket", strings.SplitN(s.Address, "://", 2)[0]) } - if s.KeepAlivePeriod.Duration == 0 { + if *s.KeepAlivePeriod == 0 { return tcpc.SetKeepAlive(false) } if err := tcpc.SetKeepAlive(true); err != nil { return err } - return tcpc.SetKeepAlivePeriod(s.KeepAlivePeriod.Duration) + return tcpc.SetKeepAlivePeriod(time.Duration(*s.KeepAlivePeriod)) } func (s *Syslog) Close() error { diff --git a/plugins/outputs/warp10/warp10.go b/plugins/outputs/warp10/warp10.go index 32018329f0984..7826047d7873d 100644 --- a/plugins/outputs/warp10/warp10.go +++ b/plugins/outputs/warp10/warp10.go @@ -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/outputs" ) @@ -25,12 +25,12 @@ const ( // Warp10 output plugin type Warp10 struct { - Prefix string `toml:"prefix"` - WarpURL string `toml:"warp_url"` - Token string `toml:"token"` - Timeout internal.Duration `toml:"timeout"` - PrintErrorBody bool `toml:"print_error_body"` - MaxStringErrorSize int `toml:"max_string_error_size"` + Prefix string `toml:"prefix"` + WarpURL string `toml:"warp_url"` + Token string `toml:"token"` + Timeout config.Duration `toml:"timeout"` + PrintErrorBody bool `toml:"print_error_body"` + MaxStringErrorSize int `toml:"max_string_error_size"` client *http.Client tls.ClientConfig } @@ -76,8 +76,8 @@ func (w *Warp10) createClient() (*http.Client, error) { return nil, err } - if w.Timeout.Duration == 0 { - w.Timeout.Duration = defaultClientTimeout + if w.Timeout == 0 { + w.Timeout = config.Duration(defaultClientTimeout) } client := &http.Client{ @@ -85,7 +85,7 @@ func (w *Warp10) createClient() (*http.Client, error) { TLSClientConfig: tlsCfg, Proxy: http.ProxyFromEnvironment, }, - Timeout: w.Timeout.Duration, + Timeout: time.Duration(w.Timeout), } return client, nil diff --git a/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring.go b/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring.go index b3578be904da0..c6eb9db2ae5b5 100644 --- a/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring.go +++ b/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring.go @@ -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/outputs" "github.com/influxdata/telegraf/selfstat" ) @@ -17,9 +17,9 @@ import ( // YandexCloudMonitoring allows publishing of metrics to the Yandex Cloud Monitoring custom metrics // service type YandexCloudMonitoring struct { - Timeout internal.Duration `toml:"timeout"` - EndpointURL string `toml:"endpoint_url"` - Service string `toml:"service"` + Timeout config.Duration `toml:"timeout"` + EndpointURL string `toml:"endpoint_url"` + Service string `toml:"service"` Log telegraf.Logger @@ -86,8 +86,8 @@ func (a *YandexCloudMonitoring) SampleConfig() string { // Connect initializes the plugin and validates connectivity func (a *YandexCloudMonitoring) Connect() error { - if a.Timeout.Duration <= 0 { - a.Timeout.Duration = defaultRequestTimeout + if a.Timeout <= 0 { + a.Timeout = config.Duration(defaultRequestTimeout) } if a.EndpointURL == "" { a.EndpointURL = defaultEndpointURL @@ -106,7 +106,7 @@ func (a *YandexCloudMonitoring) Connect() error { Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, - Timeout: a.Timeout.Duration, + Timeout: time.Duration(a.Timeout), } var err error diff --git a/plugins/processors/date/date.go b/plugins/processors/date/date.go index ef8609811c1f7..b1705826dc912 100644 --- a/plugins/processors/date/date.go +++ b/plugins/processors/date/date.go @@ -5,7 +5,7 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/plugins/processors" ) @@ -37,11 +37,11 @@ const sampleConfig = ` const defaultTimezone = "UTC" type Date struct { - TagKey string `toml:"tag_key"` - FieldKey string `toml:"field_key"` - DateFormat string `toml:"date_format"` - DateOffset internal.Duration `toml:"date_offset"` - Timezone string `toml:"timezone"` + TagKey string `toml:"tag_key"` + FieldKey string `toml:"field_key"` + DateFormat string `toml:"date_format"` + DateOffset config.Duration `toml:"date_offset"` + Timezone string `toml:"timezone"` location *time.Location } @@ -70,7 +70,7 @@ func (d *Date) Init() error { func (d *Date) Apply(in ...telegraf.Metric) []telegraf.Metric { for _, point := range in { - tm := point.Time().In(d.location).Add(d.DateOffset.Duration) + tm := point.Time().In(d.location).Add(time.Duration(d.DateOffset)) if len(d.TagKey) > 0 { point.AddTag(d.TagKey, tm.Format(d.DateFormat)) } else if len(d.FieldKey) > 0 { diff --git a/plugins/processors/date/date_test.go b/plugins/processors/date/date_test.go index 9bafc0654adff..c6d98051e7dec 100644 --- a/plugins/processors/date/date_test.go +++ b/plugins/processors/date/date_test.go @@ -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" "github.com/stretchr/testify/assert" @@ -165,7 +165,7 @@ func TestDateOffset(t *testing.T) { plugin := &Date{ TagKey: "hour", DateFormat: "15", - DateOffset: internal.Duration{Duration: 2 * time.Hour}, + DateOffset: config.Duration(2 * time.Hour), } err := plugin.Init() diff --git a/plugins/processors/dedup/dedup.go b/plugins/processors/dedup/dedup.go index 3823b393e27fd..1ffe183256a1c 100644 --- a/plugins/processors/dedup/dedup.go +++ b/plugins/processors/dedup/dedup.go @@ -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/processors" ) @@ -14,7 +14,7 @@ var sampleConfig = ` ` type Dedup struct { - DedupInterval internal.Duration `toml:"dedup_interval"` + DedupInterval config.Duration `toml:"dedup_interval"` FlushTime time.Time Cache map[uint64]telegraf.Metric } @@ -36,13 +36,13 @@ func remove(slice []telegraf.Metric, i int) []telegraf.Metric { // Remove expired items from cache func (d *Dedup) cleanup() { // No need to cleanup cache too often. Lets save some CPU - if time.Since(d.FlushTime) < d.DedupInterval.Duration { + if time.Since(d.FlushTime) < time.Duration(d.DedupInterval) { return } d.FlushTime = time.Now() keep := make(map[uint64]telegraf.Metric) for id, metric := range d.Cache { - if time.Since(metric.Time()) < d.DedupInterval.Duration { + if time.Since(metric.Time()) < time.Duration(d.DedupInterval) { keep[id] = metric } } @@ -68,7 +68,7 @@ func (d *Dedup) Apply(metrics ...telegraf.Metric) []telegraf.Metric { } // If cache item has expired then refresh it - if time.Since(m.Time()) >= d.DedupInterval.Duration { + if time.Since(m.Time()) >= time.Duration(d.DedupInterval) { d.save(metric, id) continue } @@ -120,7 +120,7 @@ func (d *Dedup) Apply(metrics ...telegraf.Metric) []telegraf.Metric { func init() { processors.Add("dedup", func() telegraf.Processor { return &Dedup{ - DedupInterval: internal.Duration{Duration: 10 * time.Minute}, + DedupInterval: config.Duration(10 * time.Minute), FlushTime: time.Now(), Cache: make(map[uint64]telegraf.Metric), } diff --git a/plugins/processors/dedup/dedup_test.go b/plugins/processors/dedup/dedup_test.go index b2fc9ca1fc546..80dde9057b0da 100644 --- a/plugins/processors/dedup/dedup_test.go +++ b/plugins/processors/dedup/dedup_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" ) @@ -24,7 +24,7 @@ func createMetric(value int64, when time.Time) telegraf.Metric { func createDedup(initTime time.Time) Dedup { return Dedup{ - DedupInterval: internal.Duration{Duration: 10 * time.Minute}, + DedupInterval: config.Duration(10 * time.Minute), FlushTime: initTime, Cache: make(map[uint64]telegraf.Metric), } diff --git a/plugins/processors/ifname/ifname.go b/plugins/processors/ifname/ifname.go index 52a9161b0f6fe..714578779a7a0 100644 --- a/plugins/processors/ifname/ifname.go +++ b/plugins/processors/ifname/ifname.go @@ -8,7 +8,6 @@ import ( "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" - "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal/snmp" "github.com/influxdata/telegraf/plugins/common/parallel" si "github.com/influxdata/telegraf/plugins/inputs/snmp" @@ -338,7 +337,7 @@ func init() { ClientConfig: snmp.ClientConfig{ Retries: 3, MaxRepetitions: 10, - Timeout: internal.Duration{Duration: 5 * time.Second}, + Timeout: config.Duration(5 * time.Second), Version: 2, Community: "public", }, diff --git a/plugins/processors/ifname/ifname_test.go b/plugins/processors/ifname/ifname_test.go index cea03cfd3fe62..4052818f7509b 100644 --- a/plugins/processors/ifname/ifname_test.go +++ b/plugins/processors/ifname/ifname_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" "github.com/influxdata/telegraf/config" - "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/internal/snmp" si "github.com/influxdata/telegraf/plugins/inputs/snmp" "github.com/influxdata/telegraf/testutil" @@ -25,7 +24,7 @@ func TestTable(t *testing.T) { config := snmp.ClientConfig{ Version: 2, - Timeout: internal.Duration{Duration: 5 * time.Second}, // Doesn't work with 0 timeout + Timeout: config.Duration(5 * time.Second), // Doesn't work with 0 timeout } gs, err := snmp.NewWrapper(config) require.NoError(t, err) @@ -51,7 +50,7 @@ func TestIfNameIntegration(t *testing.T) { CacheSize: 1000, ClientConfig: snmp.ClientConfig{ Version: 2, - Timeout: internal.Duration{Duration: 5 * time.Second}, // Doesn't work with 0 timeout + Timeout: config.Duration(5 * time.Second), // Doesn't work with 0 timeout }, } err := d.Init() diff --git a/plugins/processors/topk/topk.go b/plugins/processors/topk/topk.go index 28a2cb7fc2498..d94d452ace262 100644 --- a/plugins/processors/topk/topk.go +++ b/plugins/processors/topk/topk.go @@ -7,23 +7,23 @@ 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/metric" "github.com/influxdata/telegraf/plugins/processors" ) type TopK struct { - Period internal.Duration `toml:"period"` - K int `toml:"k"` - GroupBy []string `toml:"group_by"` - Fields []string `toml:"fields"` - Aggregation string `toml:"aggregation"` - Bottomk bool `toml:"bottomk"` - AddGroupByTag string `toml:"add_groupby_tag"` - AddRankFields []string `toml:"add_rank_fields"` - AddAggregateFields []string `toml:"add_aggregate_fields"` - Log telegraf.Logger `toml:"-"` + Period config.Duration `toml:"period"` + K int `toml:"k"` + GroupBy []string `toml:"group_by"` + Fields []string `toml:"fields"` + Aggregation string `toml:"aggregation"` + Bottomk bool `toml:"bottomk"` + AddGroupByTag string `toml:"add_groupby_tag"` + AddRankFields []string `toml:"add_rank_fields"` + AddAggregateFields []string `toml:"add_aggregate_fields"` + Log telegraf.Logger `toml:"-"` cache map[string][]telegraf.Metric tagsGlobs filter.Filter @@ -37,7 +37,7 @@ func New() *TopK { topk := TopK{} // Setup defaults - topk.Period = internal.Duration{Duration: time.Second * time.Duration(10)} + topk.Period = config.Duration(time.Second * time.Duration(10)) topk.K = 10 topk.Fields = []string{"value"} topk.Aggregation = "mean" @@ -231,7 +231,7 @@ func (t *TopK) Apply(in ...telegraf.Metric) []telegraf.Metric { // If enough time has passed elapsed := time.Since(t.lastAggregation) - if elapsed >= t.Period.Duration { + if elapsed >= time.Duration(t.Period) { return t.push() } diff --git a/plugins/processors/topk/topk_test.go b/plugins/processors/topk/topk_test.go index 9df10c761eddf..27e18e34a564e 100644 --- a/plugins/processors/topk/topk_test.go +++ b/plugins/processors/topk/topk_test.go @@ -5,11 +5,11 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/internal" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/testutil" ) -var oneSecondDuration = internal.Duration{Duration: time.Second} +var oneSecondDuration = config.Duration(time.Second) // Key, value pair that represents a telegraf.Metric Field type field struct { @@ -122,7 +122,7 @@ func equalSets(l1 []telegraf.Metric, l2 []telegraf.Metric) bool { func runAndCompare(topk *TopK, metrics []telegraf.Metric, answer []telegraf.Metric, testID string, t *testing.T) { // Sleep for `period`, otherwise the processor will only // cache the metrics, but it will not process them - time.Sleep(topk.Period.Duration) + time.Sleep(time.Duration(topk.Period)) // Run the processor ret := topk.Apply(metrics...)