chore: Fix errcheck CI warnings outside of plugins directory (#15390)

This commit is contained in:
Dane Strandboge 2024-06-04 03:33:37 -05:00 committed by GitHub
parent ca525d69f8
commit 612b5ad8b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
18 changed files with 159 additions and 95 deletions

View File

@ -71,6 +71,7 @@ linters-settings:
- "(*hash/maphash.Hash).Write" - "(*hash/maphash.Hash).Write"
- "(*hash/maphash.Hash).WriteByte" - "(*hash/maphash.Hash).WriteByte"
- "(*hash/maphash.Hash).WriteString" - "(*hash/maphash.Hash).WriteString"
check-blank: true
gocritic: gocritic:
# Disable all checks. # Disable all checks.
# Default: false # Default: false
@ -325,6 +326,9 @@ issues:
- package comment should be of the form "(.+)... - package comment should be of the form "(.+)...
# EXC0015 revive: Annoying issue about not having a comment. The rare codebase has such comments # EXC0015 revive: Annoying issue about not having a comment. The rare codebase has such comments
- should have a package comment - should have a package comment
# nolintlint: directive `//nolint:errcheck` is unused for linter "errcheck"
# temporary while these are being fixed
- directive `//nolint:errcheck //.*` is unused for linter "errcheck"
# Excluding configuration per-path, per-linter, per-text and per-source # Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules: exclude-rules:
@ -335,6 +339,10 @@ issues:
- path: cmd/telegraf/(main|printer|cmd_plugins).go - path: cmd/telegraf/(main|printer|cmd_plugins).go
text: "Error return value of `outputBuffer.Write` is not checked" #errcheck text: "Error return value of `outputBuffer.Write` is not checked" #errcheck
- path: plugins/*
linters:
- errcheck # temporary as this linter is gradually being applied across the codebase
- path: _test\.go - path: _test\.go
text: "Potential hardcoded credentials" #gosec:G101 text: "Potential hardcoded credentials" #gosec:G101

View File

@ -406,7 +406,8 @@ func (t *Telegraf) runAgent(ctx context.Context, reloadConfig bool) error {
// SdNotify() only tries to notify if the NOTIFY_SOCKET environment is set, so it's safe to call when systemd isn't present. // SdNotify() only tries to notify if the NOTIFY_SOCKET environment is set, so it's safe to call when systemd isn't present.
// Ignore the return values here because they're not valid for platforms that don't use systemd. // Ignore the return values here because they're not valid for platforms that don't use systemd.
// For platforms that use systemd, telegraf doesn't log if the notification failed. // For platforms that use systemd, telegraf doesn't log if the notification failed.
_, _ = daemon.SdNotify(false, daemon.SdNotifyReady) //nolint:errcheck // see above
daemon.SdNotify(false, daemon.SdNotifyReady)
if t.once { if t.once {
wait := time.Duration(t.testWait) * time.Second wait := time.Duration(t.testWait) * time.Second

View File

@ -955,9 +955,9 @@ func (c *Config) probeParser(parentcategory string, parentname string, table *as
} }
// Try to parse the options to detect if any of them is misspelled // Try to parse the options to detect if any of them is misspelled
// We don't actually use the parser, so no need to check the error.
parser := creator("") parser := creator("")
_ = c.toml.UnmarshalTable(table, parser) //nolint:errcheck // We don't actually use the parser, so no need to check the error.
c.toml.UnmarshalTable(table, parser)
return true return true
} }

View File

@ -519,7 +519,8 @@ func TestConfig_AzureMonitorNamespacePrefix(t *testing.T) {
func TestGetDefaultConfigPathFromEnvURL(t *testing.T) { func TestGetDefaultConfigPathFromEnvURL(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("[agent]\ndebug = true")) _, err := w.Write([]byte("[agent]\ndebug = true"))
require.NoError(t, err)
})) }))
defer ts.Close() defer ts.Close()
@ -1193,7 +1194,8 @@ func TestPersisterInputStoreLoad(t *testing.T) {
p.state.Version++ p.state.Version++
p.state.Offset += uint64(i + 1) p.state.Offset += uint64(i + 1)
p.state.Bits = append(p.state.Bits, len(p.state.Bits)) p.state.Bits = append(p.state.Bits, len(p.state.Bits))
p.state.Modified, _ = time.Parse(time.RFC3339, "2022-11-03T16:49:00+02:00") p.state.Modified, err = time.Parse(time.RFC3339, "2022-11-03T16:49:00+02:00")
require.NoError(t, err)
// Store the state for later comparison // Store the state for later comparison
expected[plugin.ID()] = p.GetState() expected[plugin.ID()] = p.GetState()
@ -1542,7 +1544,10 @@ type MockupStatePlugin struct {
} }
func (m *MockupStatePlugin) Init() error { func (m *MockupStatePlugin) Init() error {
t0, _ := time.Parse(time.RFC3339, "2021-04-24T23:42:00+02:00") t0, err := time.Parse(time.RFC3339, "2021-04-24T23:42:00+02:00")
if err != nil {
return err
}
m.state = MockupState{ m.state = MockupState{
Name: "mockup", Name: "mockup",
Bits: []int{}, Bits: []int{},

View File

@ -39,17 +39,20 @@ func (t *trimmer) process() error {
// Switch states if we need to // Switch states if we need to
switch c { switch c {
case '\\': case '\\':
_ = t.input.UnreadByte() //nolint:errcheck // next byte is known
t.input.UnreadByte()
err = t.escape() err = t.escape()
case '\'': case '\'':
_ = t.input.UnreadByte() //nolint:errcheck // next byte is known
t.input.UnreadByte()
if t.hasNQuotes(c, 3) { if t.hasNQuotes(c, 3) {
err = t.tripleSingleQuote() err = t.tripleSingleQuote()
} else { } else {
err = t.singleQuote() err = t.singleQuote()
} }
case '"': case '"':
_ = t.input.UnreadByte() //nolint:errcheck // next byte is known
t.input.UnreadByte()
if t.hasNQuotes(c, 3) { if t.hasNQuotes(c, 3) {
err = t.tripleDoubleQuote() err = t.tripleDoubleQuote()
} else { } else {
@ -85,8 +88,8 @@ func (t *trimmer) hasNQuotes(ref byte, limit int64) bool {
if count < limit { if count < limit {
offset-- offset--
} }
// Unread the matched characters //nolint:errcheck // Unread the already matched characters
_, _ = t.input.Seek(offset, io.SeekCurrent) t.input.Seek(offset, io.SeekCurrent)
return count >= limit return count >= limit
} }
@ -99,8 +102,8 @@ func (t *trimmer) readWriteByte() (byte, error) {
} }
func (t *trimmer) escape() error { func (t *trimmer) escape() error {
// Consumer the known starting backslash and quote //nolint:errcheck // Consume the known starting backslash and quote
_, _ = t.readWriteByte() t.readWriteByte()
// Read the next character which is the escaped one and exit // Read the next character which is the escaped one and exit
_, err := t.readWriteByte() _, err := t.readWriteByte()
@ -108,8 +111,8 @@ func (t *trimmer) escape() error {
} }
func (t *trimmer) singleQuote() error { func (t *trimmer) singleQuote() error {
// Consumer the known starting quote //nolint:errcheck // Consume the known starting quote
_, _ = t.readWriteByte() t.readWriteByte()
// Read bytes until EOF, line end or another single quote // Read bytes until EOF, line end or another single quote
for { for {
@ -121,8 +124,8 @@ func (t *trimmer) singleQuote() error {
func (t *trimmer) tripleSingleQuote() error { func (t *trimmer) tripleSingleQuote() error {
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
// Consumer the known starting quotes //nolint:errcheck // Consume the known starting quotes
_, _ = t.readWriteByte() t.readWriteByte()
} }
// Read bytes until EOF or another set of triple single quotes // Read bytes until EOF or another set of triple single quotes
@ -133,17 +136,18 @@ func (t *trimmer) tripleSingleQuote() error {
} }
if c == '\'' && t.hasNQuotes('\'', 2) { if c == '\'' && t.hasNQuotes('\'', 2) {
// Consumer the two additional ending quotes //nolint:errcheck // Consume the two additional ending quotes
_, _ = t.readWriteByte() t.readWriteByte()
_, _ = t.readWriteByte() //nolint:errcheck // Consume the two additional ending quotes
t.readWriteByte()
return nil return nil
} }
} }
} }
func (t *trimmer) doubleQuote() error { func (t *trimmer) doubleQuote() error {
// Consumer the known starting quote //nolint:errcheck // Consume the known starting quote
_, _ = t.readWriteByte() t.readWriteByte()
// Read bytes until EOF, line end or another double quote // Read bytes until EOF, line end or another double quote
for { for {
@ -153,8 +157,8 @@ func (t *trimmer) doubleQuote() error {
} }
switch c { switch c {
case '\\': case '\\':
// Found escaped character //nolint:errcheck // Consume the found escaped character
_ = t.input.UnreadByte() t.input.UnreadByte()
if err := t.escape(); err != nil { if err := t.escape(); err != nil {
return err return err
} }
@ -169,8 +173,8 @@ func (t *trimmer) doubleQuote() error {
func (t *trimmer) tripleDoubleQuote() error { func (t *trimmer) tripleDoubleQuote() error {
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
// Consumer the known starting quotes //nolint:errcheck // Consume the known starting quotes
_, _ = t.readWriteByte() t.readWriteByte()
} }
// Read bytes until EOF or another set of triple double quotes // Read bytes until EOF or another set of triple double quotes
@ -181,8 +185,8 @@ func (t *trimmer) tripleDoubleQuote() error {
} }
switch c { switch c {
case '\\': case '\\':
// Found escaped character //nolint:errcheck // Consume the found escape character
_ = t.input.UnreadByte() t.input.UnreadByte()
if err := t.escape(); err != nil { if err := t.escape(); err != nil {
return err return err
} }
@ -190,9 +194,10 @@ func (t *trimmer) tripleDoubleQuote() error {
case '"': case '"':
t.output.WriteByte(c) t.output.WriteByte(c)
if t.hasNQuotes('"', 2) { if t.hasNQuotes('"', 2) {
// Consumer the two additional ending quotes //nolint:errcheck // Consume the two additional ending quotes
_, _ = t.readWriteByte() t.readWriteByte()
_, _ = t.readWriteByte() //nolint:errcheck // Consume the two additional ending quotes
t.readWriteByte()
return nil return nil
} }
continue continue

View File

@ -70,7 +70,8 @@ func TestIncludeExclude(t *testing.T) {
var benchbool bool var benchbool bool
func BenchmarkFilterSingleNoGlobFalse(b *testing.B) { func BenchmarkFilterSingleNoGlobFalse(b *testing.B) {
f, _ := Compile([]string{"cpu"}) f, err := Compile([]string{"cpu"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("network") tmp = f.Match("network")
@ -79,7 +80,8 @@ func BenchmarkFilterSingleNoGlobFalse(b *testing.B) {
} }
func BenchmarkFilterSingleNoGlobTrue(b *testing.B) { func BenchmarkFilterSingleNoGlobTrue(b *testing.B) {
f, _ := Compile([]string{"cpu"}) f, err := Compile([]string{"cpu"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("cpu") tmp = f.Match("cpu")
@ -88,7 +90,8 @@ func BenchmarkFilterSingleNoGlobTrue(b *testing.B) {
} }
func BenchmarkFilter(b *testing.B) { func BenchmarkFilter(b *testing.B) {
f, _ := Compile([]string{"cpu", "mem", "net*"}) f, err := Compile([]string{"cpu", "mem", "net*"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("network") tmp = f.Match("network")
@ -97,7 +100,8 @@ func BenchmarkFilter(b *testing.B) {
} }
func BenchmarkFilterNoGlob(b *testing.B) { func BenchmarkFilterNoGlob(b *testing.B) {
f, _ := Compile([]string{"cpu", "mem", "net"}) f, err := Compile([]string{"cpu", "mem", "net"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("net") tmp = f.Match("net")
@ -106,8 +110,9 @@ func BenchmarkFilterNoGlob(b *testing.B) {
} }
func BenchmarkFilter2(b *testing.B) { func BenchmarkFilter2(b *testing.B) {
f, _ := Compile([]string{"aa", "bb", "c", "ad", "ar", "at", "aq", f, err := Compile([]string{"aa", "bb", "c", "ad", "ar", "at", "aq",
"aw", "az", "axxx", "ab", "cpu", "mem", "net*"}) "aw", "az", "axxx", "ab", "cpu", "mem", "net*"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("network") tmp = f.Match("network")
@ -116,8 +121,9 @@ func BenchmarkFilter2(b *testing.B) {
} }
func BenchmarkFilter2NoGlob(b *testing.B) { func BenchmarkFilter2NoGlob(b *testing.B) {
f, _ := Compile([]string{"aa", "bb", "c", "ad", "ar", "at", "aq", f, err := Compile([]string{"aa", "bb", "c", "ad", "ar", "at", "aq",
"aw", "az", "axxx", "ab", "cpu", "mem", "net"}) "aw", "az", "axxx", "ab", "cpu", "mem", "net"})
require.NoError(b, err)
var tmp bool var tmp bool
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
tmp = f.Match("net") tmp = f.Match("net")

View File

@ -50,6 +50,7 @@ func (g *GlobPath) Match() []string {
g.path = strings.ReplaceAll(g.path, "**/**", "**") g.path = strings.ReplaceAll(g.path, "**/**", "**")
g.path = strings.ReplaceAll(g.path, "**", "**/**") g.path = strings.ReplaceAll(g.path, "**", "**/**")
//nolint:errcheck // pattern is known
files, _ := doublestar.Glob(g.path) files, _ := doublestar.Glob(g.path)
return files return files
} }
@ -58,6 +59,7 @@ func (g *GlobPath) Match() []string {
// the host platform separator. // the host platform separator.
func (g *GlobPath) MatchString(path string) bool { func (g *GlobPath) MatchString(path string) bool {
if !g.HasSuperMeta { if !g.HasSuperMeta {
//nolint:errcheck // pattern is known
res, _ := filepath.Match(g.path, path) res, _ := filepath.Match(g.path, path)
return res return res
} }
@ -75,9 +77,11 @@ func (g *GlobPath) GetRoots() []string {
return []string{g.path} return []string{g.path}
} }
if !g.HasSuperMeta { if !g.HasSuperMeta {
//nolint:errcheck // pattern is known
matches, _ := filepath.Glob(g.path) matches, _ := filepath.Glob(g.path)
return matches return matches
} }
//nolint:errcheck // pattern is known
roots, _ := filepath.Glob(g.rootGlob) roots, _ := filepath.Glob(g.rootGlob)
return roots return roots
} }

View File

@ -69,7 +69,8 @@ func TestRootGlob(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
actual, _ := Compile(test.input) actual, err := Compile(test.input)
require.NoError(t, err)
require.Equal(t, actual.rootGlob, test.output) require.Equal(t, actual.rootGlob, test.output)
} }
} }

View File

@ -44,21 +44,17 @@ func TestSnakeCase(t *testing.T) {
} }
} }
var (
sleepbin, _ = exec.LookPath("sleep")
echobin, _ = exec.LookPath("echo")
shell, _ = exec.LookPath("sh")
)
func TestRunTimeout(t *testing.T) { func TestRunTimeout(t *testing.T) {
t.Skip("Skipping test due to random failures & a data race when running test-all.") t.Skip("Skipping test due to random failures & a data race when running test-all.")
if sleepbin == "" { sleepbin, err := exec.LookPath("sleep")
if err != nil || sleepbin == "" {
t.Skip("'sleep' binary not available on OS, skipping.") t.Skip("'sleep' binary not available on OS, skipping.")
} }
cmd := exec.Command(sleepbin, "10") cmd := exec.Command(sleepbin, "10")
start := time.Now() start := time.Now()
err := RunTimeout(cmd, time.Millisecond*20) err = RunTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start) elapsed := time.Since(start)
require.Equal(t, ErrTimeout, err) require.Equal(t, ErrTimeout, err)
@ -71,12 +67,13 @@ func TestRunTimeoutFastExit(t *testing.T) {
if testing.Short() { if testing.Short() {
t.Skip("Skipping test due to random failures.") t.Skip("Skipping test due to random failures.")
} }
if echobin == "" { echobin, err := exec.LookPath("echo")
if err != nil || echobin == "" {
t.Skip("'echo' binary not available on OS, skipping.") t.Skip("'echo' binary not available on OS, skipping.")
} }
cmd := exec.Command(echobin) cmd := exec.Command(echobin)
start := time.Now() start := time.Now()
err := RunTimeout(cmd, time.Millisecond*20) err = RunTimeout(cmd, time.Millisecond*20)
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
log.SetOutput(buf) log.SetOutput(buf)
elapsed := time.Since(start) elapsed := time.Since(start)
@ -93,12 +90,13 @@ func TestRunTimeoutFastExit(t *testing.T) {
func TestCombinedOutputTimeout(t *testing.T) { func TestCombinedOutputTimeout(t *testing.T) {
// TODO: Fix this test // TODO: Fix this test
t.Skip("Test failing too often, skip for now and revisit later.") t.Skip("Test failing too often, skip for now and revisit later.")
if sleepbin == "" { sleepbin, err := exec.LookPath("sleep")
if err != nil || sleepbin == "" {
t.Skip("'sleep' binary not available on OS, skipping.") t.Skip("'sleep' binary not available on OS, skipping.")
} }
cmd := exec.Command(sleepbin, "10") cmd := exec.Command(sleepbin, "10")
start := time.Now() start := time.Now()
_, err := CombinedOutputTimeout(cmd, time.Millisecond*20) _, err = CombinedOutputTimeout(cmd, time.Millisecond*20)
elapsed := time.Since(start) elapsed := time.Since(start)
require.Equal(t, ErrTimeout, err) require.Equal(t, ErrTimeout, err)
@ -107,7 +105,8 @@ func TestCombinedOutputTimeout(t *testing.T) {
} }
func TestCombinedOutput(t *testing.T) { func TestCombinedOutput(t *testing.T) {
if echobin == "" { echobin, err := exec.LookPath("echo")
if err != nil || echobin == "" {
t.Skip("'echo' binary not available on OS, skipping.") t.Skip("'echo' binary not available on OS, skipping.")
} }
cmd := exec.Command(echobin, "foo") cmd := exec.Command(echobin, "foo")
@ -120,7 +119,8 @@ func TestCombinedOutput(t *testing.T) {
// test that CombinedOutputTimeout and exec.Cmd.CombinedOutput return // test that CombinedOutputTimeout and exec.Cmd.CombinedOutput return
// the same output from a failed command. // the same output from a failed command.
func TestCombinedOutputError(t *testing.T) { func TestCombinedOutputError(t *testing.T) {
if shell == "" { shell, err := exec.LookPath("sh")
if err != nil || shell == "" {
t.Skip("'sh' binary not available on OS, skipping.") t.Skip("'sh' binary not available on OS, skipping.")
} }
cmd := exec.Command(shell, "-c", "false") cmd := exec.Command(shell, "-c", "false")
@ -135,11 +135,12 @@ func TestCombinedOutputError(t *testing.T) {
} }
func TestRunError(t *testing.T) { func TestRunError(t *testing.T) {
if shell == "" { shell, err := exec.LookPath("sh")
if err != nil || shell == "" {
t.Skip("'sh' binary not available on OS, skipping.") t.Skip("'sh' binary not available on OS, skipping.")
} }
cmd := exec.Command(shell, "-c", "false") cmd := exec.Command(shell, "-c", "false")
err := RunTimeout(cmd, time.Second) err = RunTimeout(cmd, time.Second)
require.Error(t, err) require.Error(t, err)
} }
@ -306,8 +307,9 @@ func TestAlignDuration(t *testing.T) {
func TestAlignTime(t *testing.T) { func TestAlignTime(t *testing.T) {
rfc3339 := func(value string) time.Time { rfc3339 := func(value string) time.Time {
t, _ := time.Parse(time.RFC3339, value) tt, err := time.Parse(time.RFC3339, value)
return t require.NoError(t, err)
return tt
} }
tests := []struct { tests := []struct {

View File

@ -210,5 +210,6 @@ func isQuitting(ctx context.Context) bool {
} }
func defaultReadPipe(r io.Reader) { func defaultReadPipe(r io.Reader) {
_, _ = io.Copy(io.Discard, r) //nolint:errcheck // Discarding the data, no need to handle an error
io.Copy(io.Discard, r)
} }

View File

@ -19,13 +19,15 @@ func TestFileWriter_NoRotation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
_, err = writer.Write([]byte("Hello World 2")) _, err = writer.Write([]byte("Hello World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 1) require.Len(t, files, 1)
} }
func TestFileWriter_TimeRotation(t *testing.T) { func TestFileWriter_TimeRotation(t *testing.T) {
tempDir := t.TempDir() tempDir := t.TempDir()
interval, _ := time.ParseDuration("10ms") interval, err := time.ParseDuration("10ms")
require.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test"), interval, 0, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test"), interval, 0, -1)
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, writer.Close()) }) t.Cleanup(func() { require.NoError(t, writer.Close()) })
@ -35,22 +37,25 @@ func TestFileWriter_TimeRotation(t *testing.T) {
time.Sleep(interval) time.Sleep(interval)
_, err = writer.Write([]byte("Hello World 2")) _, err = writer.Write([]byte("Hello World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 2) require.Len(t, files, 2)
} }
func TestFileWriter_ReopenTimeRotation(t *testing.T) { func TestFileWriter_ReopenTimeRotation(t *testing.T) {
tempDir := t.TempDir() tempDir := t.TempDir()
interval, _ := time.ParseDuration("10ms") interval, err := time.ParseDuration("10ms")
require.NoError(t, err)
filePath := filepath.Join(tempDir, "test.log") filePath := filepath.Join(tempDir, "test.log")
err := os.WriteFile(filePath, []byte("Hello World"), 0640) err = os.WriteFile(filePath, []byte("Hello World"), 0640)
time.Sleep(interval) time.Sleep(interval)
require.NoError(t, err) require.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), interval, 0, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), interval, 0, -1)
require.NoError(t, err) require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, writer.Close()) }) t.Cleanup(func() { require.NoError(t, writer.Close()) })
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 2) require.Len(t, files, 2)
} }
@ -65,7 +70,8 @@ func TestFileWriter_SizeRotation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
_, err = writer.Write([]byte("World 2")) _, err = writer.Write([]byte("World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 2) require.Len(t, files, 2)
} }
@ -81,7 +87,8 @@ func TestFileWriter_ReopenSizeRotation(t *testing.T) {
_, err = writer.Write([]byte("Hello World Again")) _, err = writer.Write([]byte("Hello World Again"))
require.NoError(t, err) require.NoError(t, err)
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 2) require.Len(t, files, 2)
} }
@ -108,7 +115,8 @@ func TestFileWriter_DeleteArchives(t *testing.T) {
_, err = writer.Write([]byte("Third file")) _, err = writer.Write([]byte("Third file"))
require.NoError(t, err) require.NoError(t, err)
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 3) require.Len(t, files, 3)
for _, tempFile := range files { for _, tempFile := range files {
@ -135,7 +143,8 @@ func TestFileWriter_CloseDoesNotRotate(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, writer.Close()) require.NoError(t, writer.Close())
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 1) require.Len(t, files, 1)
require.Regexp(t, "^test.log$", files[0].Name()) require.Regexp(t, "^test.log$", files[0].Name())
} }

View File

@ -92,7 +92,7 @@ func (f *Field) Init(tr Translator) error {
} }
// fieldConvert converts from any type according to the conv specification // fieldConvert converts from any type according to the conv specification
func (f *Field) Convert(ent gosnmp.SnmpPDU) (v interface{}, err error) { func (f *Field) Convert(ent gosnmp.SnmpPDU) (interface{}, error) {
if f.Conversion == "" { if f.Conversion == "" {
if bs, ok := ent.Value.([]byte); ok { if bs, ok := ent.Value.([]byte); ok {
return string(bs), nil return string(bs), nil
@ -100,6 +100,7 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (v interface{}, err error) {
return ent.Value, nil return ent.Value, nil
} }
var v interface{}
var d int var d int
if _, err := fmt.Sscanf(f.Conversion, "float(%d)", &d); err == nil || f.Conversion == "float" { if _, err := fmt.Sscanf(f.Conversion, "float(%d)", &d); err == nil || f.Conversion == "float" {
v = ent.Value v = ent.Value
@ -129,10 +130,16 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (v interface{}, err error) {
case uint64: case uint64:
v = float64(vt) / math.Pow10(d) v = float64(vt) / math.Pow10(d)
case []byte: case []byte:
vf, _ := strconv.ParseFloat(string(vt), 64) vf, err := strconv.ParseFloat(string(vt), 64)
if err != nil {
return nil, fmt.Errorf("failed to convert field to float with value %s: %w", vt, err)
}
v = vf / math.Pow10(d) v = vf / math.Pow10(d)
case string: case string:
vf, _ := strconv.ParseFloat(vt, 64) vf, err := strconv.ParseFloat(vt, 64)
if err != nil {
return nil, fmt.Errorf("failed to convert field to float with value %s: %w", vt, err)
}
v = vf / math.Pow10(d) v = vf / math.Pow10(d)
} }
return v, nil return v, nil
@ -140,6 +147,7 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (v interface{}, err error) {
if f.Conversion == "int" { if f.Conversion == "int" {
v = ent.Value v = ent.Value
var err error
switch vt := v.(type) { switch vt := v.(type) {
case float32: case float32:
v = int64(vt) v = int64(vt)
@ -166,11 +174,11 @@ func (f *Field) Convert(ent gosnmp.SnmpPDU) (v interface{}, err error) {
case uint64: case uint64:
v = int64(vt) v = int64(vt)
case []byte: case []byte:
v, _ = strconv.ParseInt(string(vt), 10, 64) v, err = strconv.ParseInt(string(vt), 10, 64)
case string: case string:
v, _ = strconv.ParseInt(vt, 10, 64) v, err = strconv.ParseInt(vt, 10, 64)
} }
return v, nil return v, err
} }
if f.Conversion == "hwaddr" { if f.Conversion == "hwaddr" {

View File

@ -136,7 +136,10 @@ func snmpTranslateCall(oid string) (mibName string, oidNum string, oidText strin
} }
} }
oidNum = strings.Join(s, ".") oidNum = strings.Join(s, ".")
out, _ = gosmi.GetNodeByOID(types.OidMustFromString(oidNum)) out, err = gosmi.GetNodeByOID(types.OidMustFromString(oidNum))
if err != nil {
return oid, oid, oid, "", out, err
}
} else { } else {
out, err = gosmi.GetNodeByOID(types.OidMustFromString(oid)) out, err = gosmi.GetNodeByOID(types.OidMustFromString(oid))
oidNum = oid oidNum = oid

View File

@ -7,7 +7,8 @@ import (
) )
func TestEngineAlternateSeparator(t *testing.T) { func TestEngineAlternateSeparator(t *testing.T) {
defaultTemplate, _ := NewDefaultTemplateWithPattern("topic*") defaultTemplate, err := NewDefaultTemplateWithPattern("measurement*")
require.NoError(t, err)
engine, err := NewEngine("_", defaultTemplate, []string{ engine, err := NewEngine("_", defaultTemplate, []string{
"/ /*/*/* /measurement/origin/measurement*", "/ /*/*/* /measurement/origin/measurement*",
}) })

View File

@ -111,7 +111,8 @@ func TestWriteToFileInRotation(t *testing.T) {
log.Printf("I! TEST 1") // Writes 31 bytes, will rotate log.Printf("I! TEST 1") // Writes 31 bytes, will rotate
log.Printf("I! TEST") // Writes 29 byes, no rotation expected log.Printf("I! TEST") // Writes 29 byes, no rotation expected
files, _ := os.ReadDir(tempDir) files, err := os.ReadDir(tempDir)
require.NoError(t, err)
require.Len(t, files, 2) require.Len(t, files, 2)
} }

View File

@ -112,7 +112,8 @@ func TestParsing(t *testing.T) {
// Start the test-server // Start the test-server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/stats" { if r.URL.Path == "/stats" {
_, _ = w.Write(input) _, err = w.Write(input)
require.NoError(t, err)
} else { } else {
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }

View File

@ -1,7 +1,6 @@
package testutil package testutil
import ( import (
"encoding/json"
"fmt" "fmt"
"reflect" "reflect"
"sync" "sync"
@ -130,14 +129,6 @@ func (a *Accumulator) addMeasurement(
} }
} }
if a.debug {
pretty, _ := json.MarshalIndent(fields, "", " ")
prettyTags, _ := json.MarshalIndent(tags, "", " ")
msg := fmt.Sprintf("Adding Measurement [%s]\nFields:%s\nTags:%s\n",
measurement, string(pretty), string(prettyTags))
fmt.Print(msg)
}
m := &Metric{ m := &Metric{
Measurement: measurement, Measurement: measurement,
Fields: fieldsCopy, Fields: fieldsCopy,

View File

@ -68,8 +68,10 @@ func (c *Container) Create(image string) error {
// delete the container // delete the container
func (c *Container) Delete() { func (c *Container) Delete() {
_ = c.client.Stop(c.Name) //nolint:errcheck // cleaning up state so no need to check for error
_ = c.client.Delete(c.Name) c.client.Stop(c.Name)
//nolint:errcheck // cleaning up state so no need to check for error
c.client.Delete(c.Name)
} }
// installs the package from configured repos // installs the package from configured repos
@ -121,14 +123,17 @@ func (c *Container) CheckStatus(serviceName string) error {
err = c.client.Exec(c.Name, "systemctl", "start", serviceName) err = c.client.Exec(c.Name, "systemctl", "start", serviceName)
if err != nil { if err != nil {
_ = c.client.Exec(c.Name, "systemctl", "status", serviceName) //nolint:errcheck // cleaning up state so no need to check for error
_ = c.client.Exec(c.Name, "journalctl", "--no-pager", "--unit", serviceName) c.client.Exec(c.Name, "systemctl", "status", serviceName)
//nolint:errcheck // cleaning up state so no need to check for error
c.client.Exec(c.Name, "journalctl", "--no-pager", "--unit", serviceName)
return err return err
} }
err = c.client.Exec(c.Name, "systemctl", "status", serviceName) err = c.client.Exec(c.Name, "systemctl", "status", serviceName)
if err != nil { if err != nil {
_ = c.client.Exec(c.Name, "journalctl", "--no-pager", "--unit", serviceName) //nolint:errcheck // cleaning up state so no need to check for error
c.client.Exec(c.Name, "journalctl", "--no-pager", "--unit", serviceName)
return err return err
} }
@ -188,11 +193,14 @@ func (c *Container) configureApt() error {
return err return err
} }
_ = c.client.Exec( err = c.client.Exec(
c.Name, c.Name,
"bash", "-c", "--", "bash", "-c", "--",
"cat /etc/apt/sources.list.d/influxdata.list", "cat /etc/apt/sources.list.d/influxdata.list",
) )
if err != nil {
return err
}
err = c.client.Exec(c.Name, "apt-get", "update") err = c.client.Exec(c.Name, "apt-get", "update")
if err != nil { if err != nil {
@ -213,11 +221,14 @@ func (c *Container) configureYum() error {
return err return err
} }
_ = c.client.Exec( err = c.client.Exec(
c.Name, c.Name,
"bash", "-c", "--", "bash", "-c", "--",
"cat /etc/yum.repos.d/influxdata.repo", "cat /etc/yum.repos.d/influxdata.repo",
) )
if err != nil {
return err
}
// will return a non-zero return code if there are packages to update // will return a non-zero return code if there are packages to update
return c.client.Exec(c.Name, "bash", "-c", "yum check-update || true") return c.client.Exec(c.Name, "bash", "-c", "yum check-update || true")
@ -234,11 +245,14 @@ func (c *Container) configureDnf() error {
return err return err
} }
_ = c.client.Exec( err = c.client.Exec(
c.Name, c.Name,
"bash", "-c", "--", "bash", "-c", "--",
"cat /etc/yum.repos.d/influxdata.repo", "cat /etc/yum.repos.d/influxdata.repo",
) )
if err != nil {
return err
}
// will return a non-zero return code if there are packages to update // will return a non-zero return code if there are packages to update
return c.client.Exec(c.Name, "bash", "-c", "dnf check-update || true") return c.client.Exec(c.Name, "bash", "-c", "dnf check-update || true")
@ -255,11 +269,14 @@ func (c *Container) configureZypper() error {
return err return err
} }
_ = c.client.Exec( err = c.client.Exec(
c.Name, c.Name,
"bash", "-c", "--", "bash", "-c", "--",
"cat /etc/zypp/repos.d/influxdata.repo", "cat /etc/zypp/repos.d/influxdata.repo",
) )
if err != nil {
return err
}
return c.client.Exec(c.Name, "zypper", "--no-gpg-checks", "refresh") return c.client.Exec(c.Name, "zypper", "--no-gpg-checks", "refresh")
} }