Skip to content

Commit

Permalink
linters: add go-simple and fix corresponding alerts
Browse files Browse the repository at this point in the history
Gosimple is beneficial since it makes the code more readable and
proposes simplification of things which can make things more efficient
if not already optimized by the compiler.

Signed-off-by: Mahe Tardy <[email protected]>
  • Loading branch information
mtardy committed Dec 1, 2023
1 parent ef1278e commit c971f0c
Show file tree
Hide file tree
Showing 31 changed files with 47 additions and 75 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ linters:
- revive
- staticcheck
- unused
- gosimple

linters-settings:
goheader:
Expand Down
6 changes: 1 addition & 5 deletions cmd/protoc-gen-go-tetragon/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,7 @@ func FmtSprintf(g *protogen.GeneratedFile, fmt_ string, args ...string) string {

// EventFieldCheck returns true if the event has the field
func EventFieldCheck(msg *protogen.Message, field string) bool {
if msg.Desc.Fields().ByName(protoreflect.Name(field)) != nil {
return true
}

return false
return msg.Desc.Fields().ByName(protoreflect.Name(field)) != nil
}

// IsProcessEvent returns true if the message is an Tetragon event that has a process field
Expand Down
2 changes: 1 addition & 1 deletion cmd/tetragon-vmtests-run/qemu.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func buildQemuArgs(log *logrus.Logger, rcnf *RunConf) ([]string, error) {
}
qemuArgs = append(qemuArgs,
"-kernel", rcnf.kernelFname,
"-append", fmt.Sprintf("%s", strings.Join(appendArgs, " ")),
"-append", strings.Join(appendArgs, " "),
)
}

Expand Down
6 changes: 3 additions & 3 deletions cmd/tetragon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func tetragonExecute() error {
log.Fatal(err)
}

if filepath.IsAbs(option.Config.TracingPolicyDir) == false {
if !filepath.IsAbs(option.Config.TracingPolicyDir) {
log.Fatalf("Failed path specified by --tracing-policy-dir '%q' is not absolute", option.Config.TracingPolicyDir)
}
option.Config.TracingPolicyDir = filepath.Clean(option.Config.TracingPolicyDir)
Expand Down Expand Up @@ -488,7 +488,7 @@ func tetragonExecute() error {
}

// k8s should have metrics, so periodically log only in a non k8s
if option.Config.EnableK8s == false {
if !option.Config.EnableK8s {
go logStatus(ctx, obs)
}

Expand Down Expand Up @@ -526,7 +526,7 @@ func loadTpFromDir(ctx context.Context, dir string) error {
return err
}

if st.Mode().IsRegular() == false {
if !st.Mode().IsRegular() {
return nil
}

Expand Down
3 changes: 1 addition & 2 deletions pkg/btf/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package btf

import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
Expand Down Expand Up @@ -55,7 +54,7 @@ func TestSpecs(t *testing.T) {
// NB: for now we check against a single BTF file.
btfFname := filepath.Join(testdataPath, "btf", "vmlinux-5.4.104+")
if _, err := os.Stat(btfFname); err != nil {
t.Skip(fmt.Sprintf("%s not found", btfFname))
t.Skipf("%s not found", btfFname)
}
btf, err := btf.LoadSpec(btfFname)
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions pkg/cgroups/cgroups.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ func parseCgroupSubSysIds(filePath string) error {
}).Debugf("Cgroup available controllers")

// Could not find 'memory', 'pids' nor 'cpuset' controllers, are they compiled in?
if fixed == false {
if !fixed {
err = fmt.Errorf("detect cgroup controllers IDs from '%s' failed", filePath)
logger.GetLogger().WithFields(logrus.Fields{
"cgroup.fs": cgroupFSPath,
Expand Down Expand Up @@ -278,7 +278,7 @@ func setDeploymentMode(cgroupPath string) error {
return nil
}

if option.Config.EnableK8s == true {
if option.Config.EnableK8s {
deploymentMode = DEPLOY_K8S
return nil
}
Expand Down Expand Up @@ -354,7 +354,7 @@ func GetCgrpControllerName() string {
func getValidCgroupv1Path(cgroupPaths []string) (string, error) {
for _, controller := range CgroupControllers {
// First lets go again over list of active controllers
if controller.Active == false {
if !controller.Active {
logger.GetLogger().WithField("cgroup.fs", cgroupFSPath).Debugf("Cgroup controller '%s' is not active", controller.Name)
continue
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/encoder/encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ const (

func CapTrailorPrinter(str string, caps string) string {
if len(caps) == 0 {
return fmt.Sprintf("%s", str)
return str
}
padding := 0
if len(str) < capsPad {
Expand Down
10 changes: 2 additions & 8 deletions pkg/eventcheckertests/yamlhelpers/yamlhelpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,11 @@ func AssertUnmarshalRoundTrip(t *testing.T, b []byte, o interface{}) bool {
// AssertUnmarshal unmarshals an object and makes sure that it unmarshals
func AssertUnmarshal(t *testing.T, b []byte, o interface{}) bool {
err := yaml.Unmarshal(b, o)
if !assert.NoError(t, err, "`%v` should unmarshal", o) {
return false
}
return true
return assert.NoError(t, err, "`%v` should unmarshal", o)
}

// AssertMarshal unmarshals an object and makes sure that it unmarshals
func AssertMarshal(t *testing.T, b []byte, o interface{}) bool {
_, err := yaml.Marshal(o)
if !assert.NoError(t, err, "`%s` should marshal", string(b)) {
return false
}
return true
return assert.NoError(t, err, "`%s` should marshal", string(b))
}
2 changes: 1 addition & 1 deletion pkg/fieldfilters/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ func fixupFieldFilterString(s string) string {
dec := json.NewDecoder(strings.NewReader(s))
enc := json.NewEncoder(builder)

for true {
for {
var dat map[string]interface{}
err := dec.Decode(&dat)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion pkg/idtable/idtable.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,6 @@ func (t *Table) AddEntry(entry Entry) {
idx := t.findEmpty()
t.arr[idx] = entry
entry.SetID(EntryID{idx})
return
}

func (t *Table) getValidEntryIndex(id EntryID) (int, error) {
Expand Down
5 changes: 1 addition & 4 deletions pkg/kernels/kernels.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,7 @@ func MinKernelVersion(kernel string) bool {
runningVersion := int(KernelStringToNumeric(release))
minVersion := int(KernelStringToNumeric(kernel))

if minVersion <= runningVersion {
return true
}
return false
return minVersion <= runningVersion
}

func EnableV61Progs() bool {
Expand Down
2 changes: 1 addition & 1 deletion pkg/observer/observer.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ func (k *Observer) LogPinnedBpf(observerDir string) {
return
}

if finfo.IsDir() == false {
if !finfo.IsDir() {
err := fmt.Errorf("is not a directory")
k.log.WithField("bpf-dir", observerDir).WithError(err).Warn("BPF: checking BPF resources failed")
// Do not fail, let bpf part handle it
Expand Down
4 changes: 2 additions & 2 deletions pkg/option/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func ReadConfigFile(path string, file string) error {
if err != nil {
return err
}
if st.Mode().IsRegular() == false {
if !st.Mode().IsRegular() {
return fmt.Errorf("failed to read config file '%s' not a regular file", file)
}

Expand All @@ -179,7 +179,7 @@ func ReadConfigDir(path string) error {
if err != nil {
return err
}
if st.IsDir() == false {
if !st.IsDir() {
return fmt.Errorf("'%s' is not a directory", path)
}

Expand Down
4 changes: 1 addition & 3 deletions pkg/pidfile/pidfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ func Create() (uint64, error) {
return pid, ErrPidIsStillAlive
}

if err != nil &&
errors.Is(err, ErrPidFileAccess) == false &&
errors.Is(err, ErrPidIsNotAlive) == false {
if err != nil && !errors.Is(err, ErrPidFileAccess) && !errors.Is(err, ErrPidIsNotAlive) {
return 0, err
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/policyfilter/k8s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -565,7 +565,7 @@ func TestK8s(t *testing.T) {
ts := newTestState(client)
st, err := newState(log, ts)
if err != nil {
t.Skip(fmt.Sprintf("failed to initialize policy filter state: %s", err))
t.Skipf("failed to initialize policy filter state: %s", err)
}
defer st.Close()

Expand Down
3 changes: 1 addition & 2 deletions pkg/policyfilter/state_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
package policyfilter

import (
"fmt"
"testing"

"github.com/google/uuid"
Expand All @@ -14,7 +13,7 @@ import (
func TestState(t *testing.T) {
s, err := New()
if err != nil {
t.Skip(fmt.Sprintf("failed to inialize policy filter state: %s", err))
t.Skipf("failed to inialize policy filter state: %s", err)
}
defer s.Close()

Expand Down
5 changes: 1 addition & 4 deletions pkg/process/args.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,7 @@ import (
)

func argsDecoderTrim(r rune) bool {
if r == 0x00 {
return true
}
return false
return r == 0x00
}

func ArgsDecoder(s string, flags uint32) (string, string) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/process/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ func (pi *ProcessInternal) UpdateExecOutsideCache(cred bool) (*tetragon.Process,

// Take a copy of the process, add the necessary fields to the
// final ProcessExec event
if update == true {
if update {
process = pi.GetProcessCopy()
process.BinaryProperties = prop
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/reader/namespace/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func GetMyPidG() uint32 {
if procfs := os.Getenv("TETRAGON_PROCFS"); procfs != "" {
procFS, _ := os.ReadDir(procfs)
for _, d := range procFS {
if d.IsDir() == false {
if !d.IsDir() {
continue
}
cmdline, err := os.ReadFile(filepath.Join(procfs, d.Name(), "/cmdline"))
Expand Down Expand Up @@ -228,7 +228,7 @@ func initHostNamespace() (*tetragon.Namespaces, error) {
for _, n := range listNamespaces {
ino, err := GetPidNsInode(1, n)
if err != nil {
if (n == "time" || n == "time_for_children") && TimeNsSupport == false {
if (n == "time" || n == "time_for_children") && !TimeNsSupport {
// Explicitly initialize host time namespace to zero which indicates
// kernel does not support it.
knownNamespaces[n] = &tetragon.Namespace{Inum: 0, IsHost: false}
Expand Down
4 changes: 2 additions & 2 deletions pkg/selectors/kernel.go
Original file line number Diff line number Diff line change
Expand Up @@ -1100,7 +1100,7 @@ func ParseMatchNamespaceChanges(k *KernelSelectorState, actions []v1alpha1.Names
if len(actions) > 1 {
return fmt.Errorf("matchNamespaceChanges supports only a single filter (current number of filters is %d)", len(actions))
}
if (len(actions) == 1) && (kernels.EnableLargeProgs() == false) {
if (len(actions) == 1) && !kernels.EnableLargeProgs() {
return fmt.Errorf("matchNamespaceChanges is only supported in kernels >= 5.3")
}
loff := AdvanceSelectorLength(&k.data)
Expand Down Expand Up @@ -1333,7 +1333,7 @@ func InitKernelSelectorState(selectors []v1alpha1.KProbeSelector, args []v1alpha
func HasOverride(spec *v1alpha1.KProbeSpec) bool {
for _, s := range spec.Selectors {
for _, action := range s.MatchActions {
act, _ := actionTypeTable[strings.ToLower(action.Action)]
act := actionTypeTable[strings.ToLower(action.Action)]
if act == ActionTypeOverride {
return true
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/selectors/kernel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -819,7 +819,7 @@ func TestInitKernelSelectors(t *testing.T) {
var actionArgTable idtable.Table

b, _ := InitKernelSelectors(selectors, args, &actionArgTable)
if bytes.Equal(expected[0:len(expected)], b[0:len(expected)]) == false {
if bytes.Equal(expected[0:], b[0:len(expected)]) == false {
t.Errorf("InitKernelSelectors:\nexpected %v\nbytes %v\n", expected, b[0:len(expected)])
}
}
4 changes: 1 addition & 3 deletions pkg/sensors/exec/exit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ func TestExit(t *testing.T) {
execChecker := ec.NewProcessExecChecker("exec").WithProcess(procChecker)
exitChecker := ec.NewProcessExitChecker("exit").WithProcess(procChecker)

var checker *ec.UnorderedEventChecker

checker = ec.NewUnorderedEventChecker(execChecker, exitChecker)
checker := ec.NewUnorderedEventChecker(execChecker, exitChecker)

if err := exec.Command(testNop).Run(); err != nil {
t.Fatalf("Failed to execute test binary: %s\n", err)
Expand Down
4 changes: 2 additions & 2 deletions pkg/sensors/exec/procevents/proc.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func LookupContainerId(cgroup string, bpfSource bool, walkParent bool) (string,
// We trust BPF part that it will always return null terminated
// DOCKER_ID_LENGTH. For other cases where we read through /proc/
// strings are not truncated.
if bpfSource == true && len(subdir) >= processapi.DOCKER_ID_LENGTH-1 {
if bpfSource && len(subdir) >= processapi.DOCKER_ID_LENGTH-1 {
idTruncated = true
}

Expand All @@ -86,7 +86,7 @@ func LookupContainerId(cgroup string, bpfSource bool, walkParent bool) (string,
// walkParent argument set and get its parent cgroup
if !strings.HasSuffix(container, "service") &&
((len(container) >= ContainerIdLength) ||
(idTruncated == true && len(container) >= BpfContainerIdLength)) {
(idTruncated && len(container) >= BpfContainerIdLength)) {
// Return first 31 chars. If the string is less than 31 chars
// it's not a docker ID so skip it. For example docker.server
// will get here.
Expand Down
4 changes: 2 additions & 2 deletions pkg/sensors/exec/procevents/proc_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ func listRunningProcs(procPath string) ([]procs, error) {
var pexecPath string
var pnspid uint32

if d.IsDir() == false {
if !d.IsDir() {
continue
}

Expand Down Expand Up @@ -436,7 +436,7 @@ func listRunningProcs(procPath string) ([]procs, error) {
}
time_ns := uint32(0)
time_for_children_ns := uint32(0)
if namespace.TimeNsSupport == true {
if namespace.TimeNsSupport {
time_ns, err = namespace.GetPidNsInode(uint32(pid), "time")
if err != nil {
logger.GetLogger().WithError(err).Warnf("Reading time namespace failed")
Expand Down
14 changes: 6 additions & 8 deletions pkg/sensors/exec/threads_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,20 +127,18 @@ func TestMatchCloneThreadsIDs(t *testing.T) {
clonePID, cloneTID := uint32(0), uint32(0)
events := perfring.RunTestEvents(t, ctx, ops)
for _, ev := range events {
switch ev.(type) {
switch ev := ev.(type) {
case *grpcexec.MsgExecveEventUnix:
exec := ev.(*grpcexec.MsgExecveEventUnix)
if exec.Process.Filename == testBin {
execPID = exec.Process.PID
execTID = exec.Process.TID
if ev.Process.Filename == testBin {
execPID = ev.Process.PID
execTID = ev.Process.TID
}
case *grpcexec.MsgCloneEventUnix:
msg := ev.(*grpcexec.MsgCloneEventUnix)
// We found the exec parent then catch the single per thread
// clone event
if execPID != 0 && clonePID == 0 {
clonePID = msg.PID
cloneTID = msg.TID
clonePID = ev.PID
cloneTID = ev.TID
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/sensors/program/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ func doLoadProgram(
if verbose < 2 {
fmt.Println(slimVerifierError(fmt.Sprintf("%+v", ve)))
} else {
fmt.Println(fmt.Sprintf("%+v", ve))
fmt.Printf("%+v\n", ve)
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/sensors/tracing/generickprobe.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ func preValidateKprobes(name string, kprobes []v1alpha1.KProbeSpec, lists []v1al
}
if !f.Syscall {
for idx := range calls {
if strings.HasPrefix(calls[idx], "security_") == false {
if !strings.HasPrefix(calls[idx], "security_") {
return fmt.Errorf("Error override action can be used only with syscalls and security_ hooks")
}
}
Expand Down Expand Up @@ -756,7 +756,7 @@ func addKprobe(funcName string, f *v1alpha1.KProbeSpec, in *addKprobeIn) (id idt
// Mark remaining arguments as 'nops' the kernel side will skip
// copying 'nop' args.
for j, a := range argsBTFSet {
if a == false {
if !a {
if j != api.ReturnArgIndex {
config.Arg[j] = gt.GenericNopType
config.ArgM[j] = 0
Expand Down
Loading

0 comments on commit c971f0c

Please sign in to comment.