diff --git a/.golangci.yml b/.golangci.yml index 6adb916124d..b47b63dd45a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,6 +18,7 @@ linters: - revive - staticcheck - unused + - gosimple linters-settings: goheader: diff --git a/cmd/protoc-gen-go-tetragon/common/common.go b/cmd/protoc-gen-go-tetragon/common/common.go index 93938504767..7b377d54f5f 100644 --- a/cmd/protoc-gen-go-tetragon/common/common.go +++ b/cmd/protoc-gen-go-tetragon/common/common.go @@ -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 diff --git a/cmd/tetragon-vmtests-run/qemu.go b/cmd/tetragon-vmtests-run/qemu.go index a963361ef23..a38ceb93f7c 100644 --- a/cmd/tetragon-vmtests-run/qemu.go +++ b/cmd/tetragon-vmtests-run/qemu.go @@ -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, " "), ) } diff --git a/cmd/tetragon/main.go b/cmd/tetragon/main.go index 5c41a83876d..af05658ed33 100644 --- a/cmd/tetragon/main.go +++ b/cmd/tetragon/main.go @@ -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) @@ -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) } @@ -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 } diff --git a/pkg/btf/validation_test.go b/pkg/btf/validation_test.go index a394aad8dc2..fa785044665 100644 --- a/pkg/btf/validation_test.go +++ b/pkg/btf/validation_test.go @@ -5,7 +5,6 @@ package btf import ( "errors" - "fmt" "os" "path/filepath" "runtime" @@ -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 { diff --git a/pkg/cgroups/cgroups.go b/pkg/cgroups/cgroups.go index 4409eb21366..94a1db40c52 100644 --- a/pkg/cgroups/cgroups.go +++ b/pkg/cgroups/cgroups.go @@ -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, @@ -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 } @@ -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 } diff --git a/pkg/encoder/encoder.go b/pkg/encoder/encoder.go index 8c586419633..e01c0e2b56e 100644 --- a/pkg/encoder/encoder.go +++ b/pkg/encoder/encoder.go @@ -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 { diff --git a/pkg/eventcheckertests/yamlhelpers/yamlhelpers.go b/pkg/eventcheckertests/yamlhelpers/yamlhelpers.go index 023aa4cd2cb..07b2b9ddd90 100644 --- a/pkg/eventcheckertests/yamlhelpers/yamlhelpers.go +++ b/pkg/eventcheckertests/yamlhelpers/yamlhelpers.go @@ -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)) } diff --git a/pkg/fieldfilters/fields.go b/pkg/fieldfilters/fields.go index e1cfbe40563..84a9e45e358 100644 --- a/pkg/fieldfilters/fields.go +++ b/pkg/fieldfilters/fields.go @@ -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 { diff --git a/pkg/idtable/idtable.go b/pkg/idtable/idtable.go index 77ddfed08e7..e5e3ee37e3d 100644 --- a/pkg/idtable/idtable.go +++ b/pkg/idtable/idtable.go @@ -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) { diff --git a/pkg/kernels/kernels.go b/pkg/kernels/kernels.go index 0d058fbf3a7..ab0290f72ca 100644 --- a/pkg/kernels/kernels.go +++ b/pkg/kernels/kernels.go @@ -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 { diff --git a/pkg/observer/observer.go b/pkg/observer/observer.go index 3641f8c7c17..923fad084ab 100644 --- a/pkg/observer/observer.go +++ b/pkg/observer/observer.go @@ -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 diff --git a/pkg/option/config.go b/pkg/option/config.go index 83cc807e7c4..9b9c92728d7 100644 --- a/pkg/option/config.go +++ b/pkg/option/config.go @@ -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) } @@ -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) } diff --git a/pkg/pidfile/pidfile.go b/pkg/pidfile/pidfile.go index 5f8118a182d..494c175e7c6 100644 --- a/pkg/pidfile/pidfile.go +++ b/pkg/pidfile/pidfile.go @@ -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 } diff --git a/pkg/policyfilter/k8s_test.go b/pkg/policyfilter/k8s_test.go index f33ad0644e1..c10e575ff6e 100644 --- a/pkg/policyfilter/k8s_test.go +++ b/pkg/policyfilter/k8s_test.go @@ -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() diff --git a/pkg/policyfilter/state_test.go b/pkg/policyfilter/state_test.go index 687f421e64e..f89d75eb80c 100644 --- a/pkg/policyfilter/state_test.go +++ b/pkg/policyfilter/state_test.go @@ -4,7 +4,6 @@ package policyfilter import ( - "fmt" "testing" "github.com/google/uuid" @@ -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() diff --git a/pkg/process/args.go b/pkg/process/args.go index b5d3b38f66a..9950ea35f68 100644 --- a/pkg/process/args.go +++ b/pkg/process/args.go @@ -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) { diff --git a/pkg/process/process.go b/pkg/process/process.go index aa363318045..db9e82a9bbf 100644 --- a/pkg/process/process.go +++ b/pkg/process/process.go @@ -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 } diff --git a/pkg/reader/namespace/namespace.go b/pkg/reader/namespace/namespace.go index fc83b5f66b8..6db5add2d3c 100644 --- a/pkg/reader/namespace/namespace.go +++ b/pkg/reader/namespace/namespace.go @@ -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")) @@ -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} diff --git a/pkg/selectors/kernel.go b/pkg/selectors/kernel.go index 5218ab0f42d..ac339812513 100644 --- a/pkg/selectors/kernel.go +++ b/pkg/selectors/kernel.go @@ -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) @@ -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 } diff --git a/pkg/selectors/kernel_test.go b/pkg/selectors/kernel_test.go index 180d0e00635..75abc8b4c65 100644 --- a/pkg/selectors/kernel_test.go +++ b/pkg/selectors/kernel_test.go @@ -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)]) } } diff --git a/pkg/sensors/exec/exit_test.go b/pkg/sensors/exec/exit_test.go index 2fe083ac3d1..1f8044a6a4a 100644 --- a/pkg/sensors/exec/exit_test.go +++ b/pkg/sensors/exec/exit_test.go @@ -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) diff --git a/pkg/sensors/exec/procevents/proc.go b/pkg/sensors/exec/procevents/proc.go index 55a544e5fc3..0901c94c5e1 100644 --- a/pkg/sensors/exec/procevents/proc.go +++ b/pkg/sensors/exec/procevents/proc.go @@ -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 } @@ -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. diff --git a/pkg/sensors/exec/procevents/proc_reader.go b/pkg/sensors/exec/procevents/proc_reader.go index 7f772af0547..086aeb129db 100644 --- a/pkg/sensors/exec/procevents/proc_reader.go +++ b/pkg/sensors/exec/procevents/proc_reader.go @@ -346,7 +346,7 @@ func listRunningProcs(procPath string) ([]procs, error) { var pexecPath string var pnspid uint32 - if d.IsDir() == false { + if !d.IsDir() { continue } @@ -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") diff --git a/pkg/sensors/exec/threads_test.go b/pkg/sensors/exec/threads_test.go index 7b7067cc422..a2ed5cbc84b 100644 --- a/pkg/sensors/exec/threads_test.go +++ b/pkg/sensors/exec/threads_test.go @@ -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 } } } diff --git a/pkg/sensors/program/loader.go b/pkg/sensors/program/loader.go index 79ed0a78176..a054da29eb5 100644 --- a/pkg/sensors/program/loader.go +++ b/pkg/sensors/program/loader.go @@ -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) } } } diff --git a/pkg/sensors/tracing/generickprobe.go b/pkg/sensors/tracing/generickprobe.go index f16a2f2dfc8..9fea84066ef 100644 --- a/pkg/sensors/tracing/generickprobe.go +++ b/pkg/sensors/tracing/generickprobe.go @@ -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") } } @@ -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 diff --git a/pkg/sensors/tracing/killer.go b/pkg/sensors/tracing/killer.go index 6d73581238d..7cc191e0691 100644 --- a/pkg/sensors/tracing/killer.go +++ b/pkg/sensors/tracing/killer.go @@ -67,9 +67,7 @@ func loadSingleKillerSensor(bpfDir, mapDir string, load *program.Program, verbos func loadMultiKillerSensor(bpfDir, mapDir string, load *program.Program, verbose int) error { data := &program.MultiKprobeAttachData{} - for idx := range syscallsSyms { - data.Symbols = append(data.Symbols, syscallsSyms[idx]) - } + data.Symbols = append(data.Symbols, syscallsSyms...) load.SetAttachData(data) diff --git a/pkg/sensors/tracing/lists.go b/pkg/sensors/tracing/lists.go index b0bb9803ef1..0ed202e130c 100644 --- a/pkg/sensors/tracing/lists.go +++ b/pkg/sensors/tracing/lists.go @@ -138,9 +138,7 @@ func (lr *listReader) Read(name string) ([]uint32, error) { for idx := range list.Values { sc := arch.CutSyscallPrefix(list.Values[idx]) - if strings.HasPrefix(sc, "sys_") { - sc = sc[len("sys_"):] - } + sc = strings.TrimPrefix(sc, "sys_") id := syscallinfo.GetSyscallID(sc) if id == -1 { return []uint32{}, fmt.Errorf("failed list '%s' cannot translate syscall '%s'", name, sc) diff --git a/pkg/tracepoint/fieldtype.go b/pkg/tracepoint/fieldtype.go index 4ba9813d260..00245e2935f 100644 --- a/pkg/tracepoint/fieldtype.go +++ b/pkg/tracepoint/fieldtype.go @@ -118,7 +118,7 @@ func parseTy(tyFields []string) (interface{}, error) { } else { retTy = IntTy{Base: IntTyLong, Unsigned: unsigned} } - case unsigned == true: + case unsigned: // we are doing something wrong if we hit this because we are ignoring the unsigned qualifier return nil, &ParseError{r: "unexpected unsigned"} case ty == "u8": diff --git a/pkg/vtuplefilter/vtuplefilter.go b/pkg/vtuplefilter/vtuplefilter.go index 78750f8cf0d..665173b06da 100644 --- a/pkg/vtuplefilter/vtuplefilter.go +++ b/pkg/vtuplefilter/vtuplefilter.go @@ -107,7 +107,7 @@ type And struct { func (op *And) FilterFn(t vtuple.VTuple) bool { for _, f := range op.fs { - if f.FilterFn(t) == false { + if !f.FilterFn(t) { return false } } // NB: for 0 filters, AND returns true @@ -124,7 +124,7 @@ type Or struct { func (op *Or) FilterFn(t vtuple.VTuple) bool { for _, f := range op.fs { - if f.FilterFn(t) == true { + if f.FilterFn(t) { return true } }