Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master' into enable_revive_enf…
Browse files Browse the repository at this point in the history
…orce-repeated-arg-type-style

# Conflicts:
#	.golangci.yml
  • Loading branch information
zak-pawel committed Nov 13, 2024
2 parents 42a2df3 + cf2a820 commit 62110e0
Show file tree
Hide file tree
Showing 60 changed files with 1,838 additions and 598 deletions.
3 changes: 3 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ linters-settings:
exclude: [ "TEST" ]
- name: enforce-repeated-arg-type-style
arguments: ["short"]
- name: enforce-slice-style
arguments: ["make"]
- name: error-naming
- name: error-return
- name: error-strings
Expand Down Expand Up @@ -340,6 +342,7 @@ linters-settings:
- expected-actual
- float-compare
- formatter
- go-require
- len
- negative-positive
- nil-compare
Expand Down
2 changes: 1 addition & 1 deletion agent/accumulator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func TestSetPrecision(t *testing.T) {

func TestAddTrackingMetricGroupEmpty(t *testing.T) {
ch := make(chan telegraf.Metric, 10)
metrics := []telegraf.Metric{}
metrics := make([]telegraf.Metric, 0)
acc := NewAccumulator(&TestMetricMaker{}, ch).WithTracking(1)

id := acc.AddTrackingMetricGroup(metrics)
Expand Down
10 changes: 5 additions & 5 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ func (a *Agent) Run(ctx context.Context) error {
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")
if err := a.InitPlugins(); err != nil {
return err
}

if a.Config.Persister != nil {
log.Printf("D! [agent] Initializing plugin states")
if err := a.initPersister(); err != nil {
Expand All @@ -119,11 +124,6 @@ func (a *Agent) Run(ctx context.Context) error {
}
}

log.Printf("D! [agent] Initializing plugins")
if err := a.InitPlugins(); err != nil {
return err
}

startTime := time.Now()

log.Printf("D! [agent] Connecting outputs")
Expand Down
1 change: 0 additions & 1 deletion agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ func TestAgent_LoadOutput(t *testing.T) {
require.Len(t, a.Config.Outputs, 1)

c = config.NewConfig()
c.OutputFilters = []string{}
err = c.LoadConfig("../config/testdata/telegraf-agent.toml")
require.NoError(t, err)
a = NewAgent(c)
Expand Down
10 changes: 4 additions & 6 deletions agent/tick_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@ func TestAlignedTicker(t *testing.T) {
time.Unix(60, 0).UTC(),
}

actual := []time.Time{}

actual := make([]time.Time, 0)
clk.Add(10 * time.Second)
for !clk.Now().After(until) {
tm := <-ticker.Elapsed()
Expand Down Expand Up @@ -109,8 +108,7 @@ func TestAlignedTickerOffset(t *testing.T) {
time.Unix(53, 0).UTC(),
}

actual := []time.Time{}

actual := make([]time.Time, 0)
clk.Add(10*time.Second + offset)
for !clk.Now().After(until) {
tm := <-ticker.Elapsed()
Expand Down Expand Up @@ -174,7 +172,7 @@ func TestUnalignedTicker(t *testing.T) {
time.Unix(61, 0).UTC(),
}

actual := []time.Time{}
actual := make([]time.Time, 0)
for !clk.Now().After(until) {
select {
case tm := <-ticker.Elapsed():
Expand Down Expand Up @@ -215,7 +213,7 @@ func TestRollingTicker(t *testing.T) {
time.Unix(61, 0).UTC(),
}

actual := []time.Time{}
actual := make([]time.Time, 0)
for !clk.Now().After(until) {
select {
case tm := <-ticker.Elapsed():
Expand Down
2 changes: 1 addition & 1 deletion cmd/telegraf/cmd_win_service_notwindows.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

func cliFlags() []cli.Flag {
return []cli.Flag{}
return make([]cli.Flag, 0)
}

func getServiceCommands(io.Writer) []*cli.Command {
Expand Down
10 changes: 5 additions & 5 deletions cmd/telegraf/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ var (
inputDefaults = []string{"cpu", "mem", "swap", "system", "kernel", "processes", "disk", "diskio"}

// Default output plugins
outputDefaults = []string{}
outputDefaults = make([]string, 0)
)

var header = `# Telegraf Configuration
Expand Down Expand Up @@ -126,7 +126,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) {
printFilteredSecretstores(secretstoreFilters, false, outputBuffer)
} else {
fmt.Print(secretstoreHeader)
snames := []string{}
snames := make([]string, 0, len(secretstores.SecretStores))
for sname := range secretstores.SecretStores {
snames = append(snames, sname)
}
Expand Down Expand Up @@ -165,7 +165,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) {
printFilteredProcessors(processorFilters, false, outputBuffer)
} else {
outputBuffer.Write([]byte(processorHeader))
pnames := []string{}
pnames := make([]string, 0, len(processors.Processors))
for pname := range processors.Processors {
pnames = append(pnames, pname)
}
Expand All @@ -182,7 +182,7 @@ func printSampleConfig(outputBuffer io.Writer, filters Filters) {
printFilteredAggregators(aggregatorFilters, false, outputBuffer)
} else {
outputBuffer.Write([]byte(aggregatorHeader))
pnames := []string{}
pnames := make([]string, 0, len(aggregators.Aggregators))
for pname := range aggregators.Aggregators {
pnames = append(pnames, pname)
}
Expand Down Expand Up @@ -261,7 +261,7 @@ func printFilteredInputs(inputFilters []string, commented bool, outputBuffer io.
// cache service inputs to print them at the end
servInputs := make(map[string]telegraf.ServiceInput)
// for alphabetical looping:
servInputNames := []string{}
servInputNames := make([]string, 0, len(pnames))

// Print Inputs
for _, pname := range pnames {
Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ func GetDefaultConfigPath() ([]string, error) {

// At this point we need to check if the files under /etc/telegraf are
// populated and return them all.
confFiles := []string{}
confFiles := make([]string, 0)
if _, err := os.Stat(etcfile); err == nil {
confFiles = append(confFiles, etcfile)
}
Expand Down Expand Up @@ -1805,7 +1805,7 @@ func (c *Config) getFieldTagFilter(tbl *ast.Table, fieldName string) []models.Ta
}

func keys(m map[string]bool) []string {
result := []string{}
result := make([]string, 0, len(m))
for k := range m {
result = append(result, k)
}
Expand Down
10 changes: 5 additions & 5 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,6 @@ func TestConfig_InlineTables(t *testing.T) {
}

func TestConfig_SliceComment(t *testing.T) {
t.Skipf("Skipping until #3642 is resolved")

c := config.NewConfig()
require.NoError(t, c.LoadConfig("./testdata/slice_comment.toml"))
require.Len(t, c.Outputs, 1)
Expand Down Expand Up @@ -520,8 +518,11 @@ func TestConfig_AzureMonitorNamespacePrefix(t *testing.T) {
func TestGetDefaultConfigPathFromEnvURL(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("[agent]\ndebug = true"))
require.NoError(t, err)
if _, err := w.Write([]byte("[agent]\ndebug = true")); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
}))
defer ts.Close()

Expand Down Expand Up @@ -1575,7 +1576,6 @@ func (m *MockupStatePlugin) Init() error {
}
m.state = MockupState{
Name: "mockup",
Bits: []int{},
Modified: t0,
}

Expand Down
6 changes: 3 additions & 3 deletions config/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func TestGettingMissingResolver(t *testing.T) {
mysecret := "a @{referenced:secret}"
s := NewSecret([]byte(mysecret))
defer s.Destroy()
s.unlinked = []string{}
s.unlinked = make([]string, 0)
s.resolvers = map[string]telegraf.ResolveFunc{
"@{a:dummy}": func() ([]byte, bool, error) {
return nil, false, nil
Expand All @@ -82,7 +82,7 @@ func TestGettingResolverError(t *testing.T) {
mysecret := "a @{referenced:secret}"
s := NewSecret([]byte(mysecret))
defer s.Destroy()
s.unlinked = []string{}
s.unlinked = make([]string, 0)
s.resolvers = map[string]telegraf.ResolveFunc{
"@{referenced:secret}": func() ([]byte, bool, error) {
return nil, false, errors.New("broken")
Expand Down Expand Up @@ -111,7 +111,7 @@ func TestEnclaveOpenError(t *testing.T) {
err := s.Link(map[string]telegraf.ResolveFunc{})
require.ErrorContains(t, err, "opening enclave failed")

s.unlinked = []string{}
s.unlinked = make([]string, 0)
_, err = s.Get()
require.ErrorContains(t, err, "opening enclave failed")
}
Expand Down
10 changes: 6 additions & 4 deletions docs/specs/tsd-003-state-persistence.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,17 @@ It is intended to

The persistence will use the following steps:

- Compute an unique ID for each of the plugin _instances_
- Startup Telegraf plugins calling `Init()`, etc.
- Initialize persistence framework with the user specified `statefile` location
and load the state if present
- Determine all stateful plugin instances by fulfilling the `StatefulPlugin`
interface
- Compute an unique ID for each of the plugin _instances_
- Restore plugin states (if any) for each plugin ID present in the state-file
- Startup Telegraf plugins calling `Init()`, etc.
- Run data-collection etc...
- On shutdown, query the state of all registered stateful plugins state
- On shutdown, stopping all Telegraf plugins calling `Stop()` or `Close()`
depending on the plugin type
- Query the state of all registered stateful plugins state
- Create an overall state-map with the plugin instance ID as a key and the
serialized plugin state as value.
- Marshal the overall state-map and store to disk
Expand Down Expand Up @@ -85,7 +87,7 @@ for the overall state. On-disk, the overall state of Telegraf is stored as JSON.
To restore the state of a plugin, the overall Telegraf state is first
deserialized from the on-disk JSON data and a lookup for the plugin ID is
performed in the resulting map. The value, if found, is then deserialized to the
plugin's state data-structure and provided to the plugin before calling `Init()`.
plugin's state data-structure and provided to the plugin after calling `Init()`.

## Is / Is-not

Expand Down
6 changes: 3 additions & 3 deletions filter/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
)

func TestCompile(t *testing.T) {
f, err := Compile([]string{})
f, err := Compile(nil)
require.NoError(t, err)
require.Nil(t, f)

Expand Down Expand Up @@ -50,10 +50,10 @@ func TestCompile(t *testing.T) {
}

func TestIncludeExclude(t *testing.T) {
tags := []string{}
labels := []string{"best", "com_influxdata", "timeseries", "com_influxdata_telegraf", "ever"}
tags := make([]string, 0, len(labels))

filter, err := NewIncludeExcludeFilter([]string{}, []string{"com_influx*"})
filter, err := NewIncludeExcludeFilter(nil, []string{"com_influx*"})
if err != nil {
t.Fatalf("Failed to create include/exclude filter - %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion internal/process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func New(command, envs []string) (*Process, error) {
p := &Process{
RestartDelay: 5 * time.Second,
name: command[0],
args: []string{},
args: make([]string, 0),
envs: envs,
}

Expand Down
6 changes: 3 additions & 3 deletions internal/snmp/field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func TestConvertHextoint(t *testing.T) {
{
name: "big endian invalid",
conversion: "hextoint:BigEndian:invalid",
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []uint8{}},
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]uint8, 0)},
errmsg: "invalid bit value",
},
{
Expand Down Expand Up @@ -223,13 +223,13 @@ func TestConvertHextoint(t *testing.T) {
{
name: "little endian invalid",
conversion: "hextoint:LittleEndian:invalid",
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []byte{}},
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]byte, 0)},
errmsg: "invalid bit value",
},
{
name: "invalid",
conversion: "hextoint:invalid:uint64",
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: []byte{}},
ent: gosnmp.SnmpPDU{Type: gosnmp.OctetString, Value: make([]byte, 0)},
errmsg: "invalid Endian value",
},
}
Expand Down
2 changes: 1 addition & 1 deletion internal/snmp/mib_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ func LoadMibsFromPath(paths []string, log telegraf.Logger, loader MibLoader) err
// should walk the paths given and find all folders
func walkPaths(paths []string, log telegraf.Logger) ([]string, error) {
once.Do(gosmi.Init)
folders := []string{}

folders := make([]string, 0)
for _, mibPath := range paths {
// Check if we loaded that path already and skip it if so
m.Lock()
Expand Down
2 changes: 1 addition & 1 deletion internal/snmp/translator_netsnmp_mocks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestMockExecCommand(_ *testing.T) {
var cmd []string //nolint:prealloc // Pre-allocated this slice would break the algorithm
for _, arg := range os.Args {
if arg == "--" {
cmd = []string{}
cmd = make([]string, 0)
continue
}
if cmd == nil {
Expand Down
2 changes: 1 addition & 1 deletion metric/series_grouper.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (
func NewSeriesGrouper() *SeriesGrouper {
return &SeriesGrouper{
metrics: make(map[uint64]telegraf.Metric),
ordered: []telegraf.Metric{},
ordered: make([]telegraf.Metric, 0),
hashSeed: maphash.MakeSeed(),
}
}
Expand Down
7 changes: 5 additions & 2 deletions migrations/inputs_httpjson/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,11 @@ func TestParsing(t *testing.T) {
// Start the test-server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/stats" {
_, err = w.Write(input)
require.NoError(t, err)
if _, err = w.Write(input); err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Error(err)
return
}
} else {
w.WriteHeader(http.StatusNotFound)
}
Expand Down
2 changes: 1 addition & 1 deletion models/buffer_disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (b *DiskBuffer) Batch(batchSize int) []telegraf.Metric {

if b.length() == 0 {
// no metrics in the wal file, so return an empty array
return []telegraf.Metric{}
return make([]telegraf.Metric, 0)
}
b.batchFirst = b.readIndex()
var metrics []telegraf.Metric
Expand Down
4 changes: 2 additions & 2 deletions models/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ func (f *Filter) shouldTagsPass(tags []*telegraf.Tag) bool {

// filterFields removes fields according to fieldinclude/fieldexclude.
func (f *Filter) filterFields(metric telegraf.Metric) {
filterKeys := []string{}
filterKeys := make([]string, 0, len(metric.FieldList()))
for _, field := range metric.FieldList() {
if !ShouldPassFilters(f.fieldIncludeFilter, f.fieldExcludeFilter, field.Key) {
filterKeys = append(filterKeys, field.Key)
Expand All @@ -220,7 +220,7 @@ func (f *Filter) filterFields(metric telegraf.Metric) {

// filterTags removes tags according to taginclude/tagexclude.
func (f *Filter) filterTags(metric telegraf.Metric) {
filterKeys := []string{}
filterKeys := make([]string, 0, len(metric.TagList()))
for _, tag := range metric.TagList() {
if !ShouldPassFilters(f.tagIncludeFilter, f.tagExcludeFilter, tag.Key) {
filterKeys = append(filterKeys, tag.Key)
Expand Down
4 changes: 0 additions & 4 deletions models/running_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -777,10 +777,6 @@ func (m *mockOutput) Write(metrics []telegraf.Metric) error {
return errors.New("failed write")
}

if m.metrics == nil {
m.metrics = []telegraf.Metric{}
}

m.metrics = append(m.metrics, metrics...)
return nil
}
Expand Down
Loading

0 comments on commit 62110e0

Please sign in to comment.