Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[auditbeat] fix golangci lint errors (elastic#37063)
Browse files Browse the repository at this point in the history
* auditbeat: fix golangci lint errors

* golangci-lint: fix logp exclude rules

* golangci-lint: remove error checks from all instances of logp.TestingSetup()

* golangci-lint: remove error checks from all instances of logp.DevelopmentSetup()
mmat11 authored and Scholar-Li committed Feb 5, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
1 parent b491bdd commit 9862b1c
Showing 50 changed files with 104 additions and 127 deletions.
7 changes: 4 additions & 3 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -30,7 +30,7 @@ issues:
- text: "imported and not used"
linters:
- typecheck
# From mage we are priting to the console to ourselves
# From mage we are printing to the console to ourselves
- path: (.*magefile.go|.*dev-tools/mage/.*)
linters: forbidigo

@@ -43,7 +43,7 @@ linters:
enable:
- errcheck # checking for unchecked errors in go programs
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- forbidigo # forbids identifiers matched by reg exps
- forbidigo # forbids identifiers matched by reg exps
- gosimple # linter for Go source code that specializes in simplifying a code
- misspell # finds commonly misspelled English words in comments
- nakedret # finds naked returns in functions greater than a specified function length
@@ -79,7 +79,8 @@ linters-settings:
exclude-functions:
- (github.com/elastic/elastic-agent-libs/mapstr.M).Delete # Only returns ErrKeyNotFound, can safely be ignored.
- (github.com/elastic/elastic-agent-libs/mapstr.M).Put # Can only fail on type conversions, usually safe to ignore.
- (github.com/elastic/elastic-agent-libs/logp).TestingSetup # Cannot return a non-nil error using the provided API.
- github.com/elastic/elastic-agent-libs/logp.TestingSetup # Cannot return a non-nil error using the provided API.
- github.com/elastic/elastic-agent-libs/logp.DevelopmentSetup # Cannot return a non-nil error using the provided API.

errorlint:
# Check whether fmt.Errorf uses the %w verb for formatting errors. See the readme for caveats
2 changes: 1 addition & 1 deletion auditbeat/helper/hasher/hasher.go
Original file line number Diff line number Diff line change
@@ -199,7 +199,7 @@ func (hasher *FileHasher) HashFile(path string) (map[HashType]Digest, error) {
}
}

var hashes []hash.Hash
var hashes []hash.Hash //nolint:prealloc // Preallocating doesn't bring improvements.
for _, hashType := range hasher.config.HashTypes {
h, valid := validHashes[hashType]
if !valid {
12 changes: 6 additions & 6 deletions auditbeat/module/auditd/audit_linux_test.go
Original file line number Diff line number Diff line change
@@ -72,7 +72,7 @@ var (
)

func TestImmutable(t *testing.T) {
_ = logp.TestingSetup()
logp.TestingSetup()

// Create a mock netlink client that provides the expected responses.
mock := NewMock().
@@ -107,7 +107,7 @@ func TestImmutable(t *testing.T) {
}

func TestData(t *testing.T) {
_ = logp.TestingSetup()
logp.TestingSetup()

// Create a mock netlink client that provides the expected responses.
mock := NewMock().
@@ -140,7 +140,7 @@ func TestData(t *testing.T) {
}

func TestLoginType(t *testing.T) {
_ = logp.TestingSetup()
logp.TestingSetup()

// Create a mock netlink client that provides the expected responses.
mock := NewMock().
@@ -259,7 +259,7 @@ func TestUnicastClient(t *testing.T) {
t.Skip("-audit was not specified")
}

_ = logp.TestingSetup()
logp.TestingSetup()
FailIfAuditdIsRunning(t)

c := map[string]interface{}{
@@ -289,7 +289,7 @@ func TestMulticastClient(t *testing.T) {
t.Skip("no multicast support")
}

_ = logp.TestingSetup()
logp.TestingSetup()
FailIfAuditdIsRunning(t)

c := map[string]interface{}{
@@ -349,7 +349,7 @@ func TestBuildMetricbeatEvent(t *testing.T) {
}

func buildSampleEvent(t testing.TB, lines []string, filename string) {
var msgs []*auparse.AuditMessage
var msgs []*auparse.AuditMessage //nolint:prealloc // Preallocating doesn't bring improvements.
for _, txt := range lines {
m, err := auparse.ParseLogLine(txt)
if err != nil {
2 changes: 1 addition & 1 deletion auditbeat/module/auditd/config_test.go
Original file line number Diff line number Diff line change
@@ -265,7 +265,7 @@ func parseConfig(t testing.TB, yaml string) (Config, error) {
}

func commands(rules []auditRule) []string {
var cmds []string
var cmds []string //nolint:prealloc // Preallocating doesn't bring improvements.
for _, r := range rules {
cmds = append(cmds, r.flags)
}
18 changes: 11 additions & 7 deletions auditbeat/module/file_integrity/eventreader_test.go
Original file line number Diff line number Diff line change
@@ -18,6 +18,7 @@
package file_integrity

import (
"errors"
"fmt"
"os"
"path/filepath"
@@ -29,6 +30,7 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func init() {
@@ -133,8 +135,9 @@ func TestEventReader(t *testing.T) {
if err != nil {
t.Fatal(err)
}
f.WriteString(" world!")
f.Sync()
_, err = f.WriteString(" world!")
require.NoError(t, err)
require.NoError(t, f.Sync())
f.Close()

event := readTimeout(t, events)
@@ -186,8 +189,9 @@ func TestEventReader(t *testing.T) {
if err != nil {
t.Fatal(err)
}
f.WriteString("move-in")
f.Sync()
_, err = f.WriteString("move-in")
require.NoError(t, err)
require.NoError(t, f.Sync())
f.Close()
moveInOrig = f.Name()

@@ -261,7 +265,7 @@ func TestRaces(t *testing.T) {
for i := 0; i < 10; i++ {
for _, dir := range dirs {
fname := filepath.Join(dir, fmt.Sprintf("%d.dat", i))
os.WriteFile(fname, []byte("hello"), fileMode)
require.NoError(t, os.WriteFile(fname, []byte("hello"), fileMode))
}
}
}()
@@ -273,7 +277,7 @@ func TestRaces(t *testing.T) {
const marker = "test_file"
for _, dir := range dirs {
fname := filepath.Join(dir, marker)
os.WriteFile(fname, []byte("hello"), fileMode)
require.NoError(t, os.WriteFile(fname, []byte("hello"), fileMode))
}

got := 0
@@ -406,7 +410,7 @@ func rename(t *testing.T, oldPath, newPath string) {
return
}

if linkErr, ok := err.(*os.LinkError); ok && linkErr.Err == ErrorSharingViolation {
if errors.Is(err, ErrorSharingViolation) {
time.Sleep(time.Millisecond)
continue
}
5 changes: 3 additions & 2 deletions auditbeat/module/file_integrity/fileinfo_test.go
Original file line number Diff line number Diff line change
@@ -26,6 +26,7 @@ import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestNewMetadata(t *testing.T) {
@@ -38,7 +39,7 @@ func TestNewMetadata(t *testing.T) {
if err != nil {
t.Fatal(err)
}
f.Sync()
require.NoError(t, f.Sync())
f.Close()

info, err := os.Lstat(f.Name())
@@ -103,7 +104,7 @@ func TestSetUIDSetGIDBits(t *testing.T) {
if err != nil {
t.Fatal(err)
}
f.Sync()
require.NoError(t, f.Sync())
f.Close()

info, err := os.Lstat(f.Name())
2 changes: 1 addition & 1 deletion auditbeat/module/file_integrity/metricset.go
Original file line number Diff line number Diff line change
@@ -41,7 +41,7 @@ const (
namespace = "."
)

var underTest = false
var underTest bool //nolint:unused // Used in Darwin-only builds.

func init() {
mb.Registry.MustAddMetricSet(moduleName, metricsetName, New,
23 changes: 13 additions & 10 deletions auditbeat/module/file_integrity/metricset_test.go
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@ import (
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/elastic/beats/v7/auditbeat/core"
"github.com/elastic/beats/v7/auditbeat/datastore"
@@ -44,7 +45,7 @@ func TestData(t *testing.T) {
go func() {
time.Sleep(100 * time.Millisecond)
file := filepath.Join(dir, "file.data")
os.WriteFile(file, []byte("hello world"), 0o600)
require.NoError(t, os.WriteFile(file, []byte("hello world"), 0o600))
}()

ms := mbtest.NewPushMetricSetV2(t, getConfig(dir))
@@ -113,8 +114,8 @@ func TestActions(t *testing.T) {
}

// Create some files in first directory
os.WriteFile(createdFilepath, []byte("hello world"), 0o600)
os.WriteFile(updatedFilepath, []byte("hello world"), 0o600)
require.NoError(t, os.WriteFile(createdFilepath, []byte("hello world"), 0o600))
require.NoError(t, os.WriteFile(updatedFilepath, []byte("hello world"), 0o600))

ms := mbtest.NewPushMetricSetV2(t, getConfig(dir, newDir))
events := mbtest.RunPushMetricSetV2(10*time.Second, 5, ms)
@@ -169,7 +170,7 @@ func TestExcludedFiles(t *testing.T) {
go func() {
for _, f := range []string{"FILE.TXT", "FILE.TXT.SWP", "file.txt.swo", ".git/HEAD", ".gitignore"} {
file := filepath.Join(dir, f)
os.WriteFile(file, []byte("hello world"), 0o600)
_ = os.WriteFile(file, []byte("hello world"), 0o600)
}
}()

@@ -223,10 +224,7 @@ func TestIncludedExcludedFiles(t *testing.T) {

for _, f := range []string{"FILE.TXT", ".ssh/known_hosts", ".ssh/known_hosts.swp"} {
file := filepath.Join(dir, f)
err := os.WriteFile(file, []byte("hello world"), 0o600)
if err != nil {
t.Fatal(err)
}
require.NoError(t, os.WriteFile(file, []byte("hello world"), 0o600))
}

events := mbtest.RunPushMetricSetV2(10*time.Second, 3, ms)
@@ -287,12 +285,15 @@ func TestErrorReporting(t *testing.T) {
ms := mbtest.NewPushMetricSetV2(t, config)

done := make(chan struct{}, 1)
ready := make(chan struct{}, 1)
go func() {
for {
f.WriteString("can't read this\n")
f.Sync()
_, err := f.WriteString("can't read this\n")
require.NoError(t, err)
require.NoError(t, f.Sync())
select {
case <-done:
close(ready)
return
default:
time.Sleep(time.Second / 10)
@@ -302,6 +303,7 @@ func TestErrorReporting(t *testing.T) {

events := mbtest.RunPushMetricSetV2(10*time.Second, 10, ms)
close(done)
<-ready

getField := func(ev *mb.Event, field string) interface{} {
v, _ := ev.MetricSetFields.GetValue(field)
@@ -316,6 +318,7 @@ func TestErrorReporting(t *testing.T) {

var event *mb.Event
for idx, ev := range events {
ev := ev
t.Log("event[", idx, "] = ", ev)
if match(&ev) {
event = &ev
2 changes: 1 addition & 1 deletion auditbeat/module/file_integrity/monitor/monitor.go
Original file line number Diff line number Diff line change
@@ -45,7 +45,7 @@ func New(recursive bool, IsExcludedPath func(path string) bool) (Watcher, error)
// Use our simulated recursive watches unless the fsnotify implementation
// supports OS-provided recursive watches
if recursive && watcher.SetRecursive() != nil {
return newRecursiveWatcher(watcher, IsExcludedPath), nil
return newRecursiveWatcher(watcher, IsExcludedPath), nil //nolint:nilerr // Ignore SetRecursive() errors.
}
return (*nonRecursiveWatcher)(watcher), nil
}
7 changes: 3 additions & 4 deletions auditbeat/module/file_integrity/monitor/recursive.go
Original file line number Diff line number Diff line change
@@ -144,20 +144,19 @@ func (watcher *recursiveWatcher) deliver(ev fsnotify.Event) {
}
}

func (watcher *recursiveWatcher) forwardEvents() error {
func (watcher *recursiveWatcher) forwardEvents() {
defer watcher.close()

for {
select {
case <-watcher.done:
return nil

return
case path := <-watcher.addC:
watcher.addErrC <- watcher.addRecursive(path)

case event, ok := <-watcher.inner.Events:
if !ok {
return nil
return
}
if event.Name == "" {
continue
4 changes: 1 addition & 3 deletions filebeat/input/filestream/environment_test.go
Original file line number Diff line number Diff line change
@@ -66,9 +66,7 @@ type registryEntry struct {
}

func newInputTestingEnvironment(t *testing.T) *inputTestingEnvironment {
if err := logp.DevelopmentSetup(logp.ToObserverOutput()); err != nil {
t.Fatalf("error setting up dev logging: %s", err)
}
logp.DevelopmentSetup(logp.ToObserverOutput())

t.Cleanup(func() {
if t.Failed() {
8 changes: 3 additions & 5 deletions filebeat/input/filestream/fswatch_test.go
Original file line number Diff line number Diff line change
@@ -265,15 +265,14 @@ scanner:
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()

err := logp.DevelopmentSetup(logp.ToObserverOutput())
require.NoError(t, err)
logp.DevelopmentSetup(logp.ToObserverOutput())

fw := createWatcherWithConfig(t, paths, cfgStr)
go fw.Run(ctx)

basename := "created.log"
filename := filepath.Join(dir, basename)
err = os.WriteFile(filename, nil, 0777)
err := os.WriteFile(filename, nil, 0777)
require.NoError(t, err)

t.Run("issues a warning in logs", func(t *testing.T) {
@@ -373,8 +372,7 @@ scanner:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err = logp.DevelopmentSetup(logp.ToObserverOutput())
require.NoError(t, err)
logp.DevelopmentSetup(logp.ToObserverOutput())

fw := createWatcherWithConfig(t, paths, cfgStr)

4 changes: 1 addition & 3 deletions libbeat/autodiscover/autodiscover_test.go
Original file line number Diff line number Diff line change
@@ -733,9 +733,7 @@ func printDebugLogsOnFailure(t *testing.T) {
// Use the following line to have the logs being printed
// in real time.
// logp.DevelopmentSetup(logp.WithLevel(logp.DebugLevel), logp.WithSelectors("*"))
if err := logp.DevelopmentSetup(logp.ToObserverOutput()); err != nil {
t.Fatalf("error setting up dev logging: %s", err)
}
logp.DevelopmentSetup(logp.ToObserverOutput())

t.Cleanup(func() {
if t.Failed() {
7 changes: 2 additions & 5 deletions libbeat/cmd/instance/locks/lock_test.go
Original file line number Diff line number Diff line change
@@ -30,11 +30,8 @@ import (
)

func TestMain(m *testing.M) {
err := logp.DevelopmentSetup()
if err != nil {
fmt.Fprintf(os.Stderr, "error creating logger: %s\n", err)
os.Exit(1)
}
logp.DevelopmentSetup()

tmp, err := os.MkdirTemp("", "pidfile_test")
defer os.RemoveAll(tmp)
if err != nil {
Loading

0 comments on commit 9862b1c

Please sign in to comment.