diff --git a/dev-tools/cmd/module_fields/module_fields.go b/dev-tools/cmd/module_fields/module_fields.go index 203cc298028..3ba2d97f12a 100644 --- a/dev-tools/cmd/module_fields/module_fields.go +++ b/dev-tools/cmd/module_fields/module_fields.go @@ -20,7 +20,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -104,7 +103,7 @@ func main() { log.Fatalf("Error creating golang file from template: %v", err) } - err = ioutil.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644) + err = os.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644) if err != nil { log.Fatalf("Error writing fields.go: %v", err) } @@ -112,6 +111,6 @@ func main() { } func usageFlag() { - fmt.Fprintf(os.Stderr, usageText) + fmt.Fprint(os.Stderr, usageText) flag.PrintDefaults() } diff --git a/dev-tools/cmd/module_include_list/module_include_list.go b/dev-tools/cmd/module_include_list/module_include_list.go index 4d222d2e707..8bc58537b81 100644 --- a/dev-tools/cmd/module_include_list/module_include_list.go +++ b/dev-tools/cmd/module_include_list/module_include_list.go @@ -22,7 +22,6 @@ import ( "bytes" "flag" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -164,13 +163,13 @@ func main() { } // Write the output file. - if err = ioutil.WriteFile(outFile, buf.Bytes(), 0644); err != nil { + if err = os.WriteFile(outFile, buf.Bytes(), 0644); err != nil { log.Fatalf("Failed writing output file: %v", err) } } func usageFlag() { - fmt.Fprintf(os.Stderr, usageText) + fmt.Fprint(os.Stderr, usageText) flag.PrintDefaults() } diff --git a/dev-tools/mage/common.go b/dev-tools/mage/common.go index 1c1ca25d95b..01c683c11e7 100644 --- a/dev-tools/mage/common.go +++ b/dev-tools/mage/common.go @@ -32,7 +32,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -125,7 +124,7 @@ func joinMaps(args ...map[string]interface{}) map[string]interface{} { } func expandFile(src, dst string, args ...map[string]interface{}) error { - tmplData, err := ioutil.ReadFile(src) + tmplData, err := os.ReadFile(src) if err != nil { return fmt.Errorf("failed reading from template %v: %w", src, err) } @@ -140,7 +139,7 @@ func expandFile(src, dst string, args ...map[string]interface{}) error { return err } - if err = ioutil.WriteFile(createDir(dst), []byte(output), 0644); err != nil { + if err = os.WriteFile(createDir(dst), []byte(output), 0644); err != nil { return fmt.Errorf("failed to write rendered template: %w", err) } @@ -262,13 +261,13 @@ func FindReplace(file string, re *regexp.Regexp, repl string) error { return err } - contents, err := ioutil.ReadFile(file) + contents, err := os.ReadFile(file) if err != nil { return err } out := re.ReplaceAllString(string(contents), repl) - return ioutil.WriteFile(file, []byte(out), info.Mode().Perm()) + return os.WriteFile(file, []byte(out), info.Mode().Perm()) } // MustFindReplace invokes FindReplace and panics if an error occurs. @@ -283,9 +282,14 @@ func MustFindReplace(file string, re *regexp.Regexp, repl string) { func DownloadFile(url, destinationDir string) (string, error) { log.Println("Downloading", url) - resp, err := http.Get(url) + req, err := http.NewRequestWithContext(context.TODO(), http.MethodGet, url, nil) if err != nil { - return "", fmt.Errorf("http get failed: %w", err) + return "", fmt.Errorf("failed to create http request: %w", err) + } + + resp, err := http.DefaultClient.Do(req) + if err != nil { + return "", fmt.Errorf("failed to download file: %w", err) } defer resp.Body.Close() @@ -338,9 +342,9 @@ func unzip(sourceFile, destinationDir string) error { } defer innerFile.Close() - path := filepath.Join(destinationDir, f.Name) - if !strings.HasPrefix(path, destinationDir) { - return fmt.Errorf("illegal file path in zip: %v", f.Name) + path, err := sanitizeFilePath(f.Name, destinationDir) + if err != nil { + return err } if f.FileInfo().IsDir() { @@ -357,7 +361,7 @@ func unzip(sourceFile, destinationDir string) error { } defer out.Close() - if _, err = io.Copy(out, innerFile); err != nil { + if _, err = io.Copy(out, innerFile); err != nil { //nolint:gosec // this is only used for dev tools return err } @@ -374,6 +378,16 @@ func unzip(sourceFile, destinationDir string) error { return nil } +// sanitizeExtractPath sanitizes against path traversal attacks. +// See https://security.snyk.io/research/zip-slip-vulnerability. +func sanitizeFilePath(filePath string, workdir string) (string, error) { + destPath := filepath.Join(workdir, filePath) + if !strings.HasPrefix(destPath, filepath.Clean(workdir)+string(os.PathSeparator)) { + return filePath, fmt.Errorf("failed to extract illegal file path: %s", filePath) + } + return destPath, nil +} + // Tar compress a directory using tar + gzip algorithms but without adding // the directory func TarWithOptions(src string, targetFile string, trimSource bool) error { @@ -390,7 +404,7 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error { tw := tar.NewWriter(zr) // walk through every file in the folder - filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error { + err = filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error { if errFn != nil { return fmt.Errorf("error traversing the file system: %w", errFn) } @@ -438,6 +452,9 @@ func TarWithOptions(src string, targetFile string, trimSource bool) error { } return nil }) + if err != nil { + return fmt.Errorf("error walking dir: %w", err) + } // produce tar if err := tw.Close(); err != nil { @@ -477,15 +494,15 @@ func untar(sourceFile, destinationDir string) error { for { header, err := tarReader.Next() if err != nil { - if err == io.EOF { + if errors.Is(err, io.EOF) { break } return err } - path := filepath.Join(destinationDir, header.Name) - if !strings.HasPrefix(path, destinationDir) { - return fmt.Errorf("illegal file path in tar: %v", header.Name) + path, err := sanitizeFilePath(header.Name, destinationDir) + if err != nil { + return err } switch header.Typeflag { @@ -499,7 +516,7 @@ func untar(sourceFile, destinationDir string) error { return err } - if _, err = io.Copy(writer, tarReader); err != nil { + if _, err = io.Copy(writer, tarReader); err != nil { //nolint:gosec // this is only used for dev tools return err } @@ -613,7 +630,7 @@ func ParallelCtx(ctx context.Context, fns ...interface{}) { wg.Wait() if len(errs) > 0 { - panic(fmt.Errorf(strings.Join(errs, "\n"))) + panic(errors.New(strings.Join(errs, "\n"))) } } @@ -773,7 +790,7 @@ func CreateSHA512File(file string) error { computedHash := hex.EncodeToString(sum.Sum(nil)) out := fmt.Sprintf("%v %v", computedHash, filepath.Base(file)) - return ioutil.WriteFile(file+".sha512", []byte(out), 0644) + return os.WriteFile(file+".sha512", []byte(out), 0644) } // Mage executes mage targets in the specified directory. @@ -800,7 +817,7 @@ func IsUpToDate(dst string, sources ...string) bool { var files []string for _, s := range sources { - filepath.Walk(s, func(path string, info os.FileInfo, err error) error { + err := filepath.Walk(s, func(path string, info os.FileInfo, err error) error { if err != nil { if os.IsNotExist(err) { return nil @@ -814,6 +831,9 @@ func IsUpToDate(dst string, sources ...string) bool { return nil }) + if err != nil { + panic(fmt.Errorf("failed to walk source %v: %w", s, err)) + } } execute, err := target.Path(dst, files...) @@ -896,7 +916,7 @@ func ParseVersion(version string) (major, minor, patch int, err error) { matches := parseVersionRegex.FindStringSubmatch(version) if len(matches) == 0 { err = fmt.Errorf("failed to parse version '%v'", version) - return + return major, minor, patch, err } data := map[string]string{} @@ -906,7 +926,7 @@ func ParseVersion(version string) (major, minor, patch int, err error) { major, _ = strconv.Atoi(data["major"]) minor, _ = strconv.Atoi(data["minor"]) patch, _ = strconv.Atoi(data["patch"]) - return + return major, minor, patch, nil } // ListMatchingEnvVars returns all of the environment variables names that begin diff --git a/heartbeat/hbtestllext/isdefs.go b/heartbeat/hbtestllext/isdefs.go index e20f2cb18a1..eeb56e16631 100644 --- a/heartbeat/hbtestllext/isdefs.go +++ b/heartbeat/hbtestllext/isdefs.go @@ -74,7 +74,7 @@ var IsMonitorStateInLocation = func(locName string) isdef.IsDef { } if !stateIdMatch.MatchString(s.ID) { - return llresult.SimpleResult(path, false, fmt.Sprintf("ID %s does not match regexp pattern /%s/", s.ID, locPattern)) + return llresult.SimpleResult(path, false, "ID %s does not match regexp pattern /%s/", s.ID, locPattern) } return llresult.ValidResult(path) }) diff --git a/heartbeat/look/look_test.go b/heartbeat/look/look_test.go index ff3f9bdcc54..77f5377b235 100644 --- a/heartbeat/look/look_test.go +++ b/heartbeat/look/look_test.go @@ -18,6 +18,7 @@ package look import ( + "errors" "testing" "time" @@ -57,7 +58,7 @@ func TestReason(t *testing.T) { func TestReasonGenericError(t *testing.T) { msg := "An error" - res := Reason(fmt.Errorf(msg)) + res := Reason(errors.New(msg)) assert.Equal(t, mapstr.M{ "type": "io", "message": msg, diff --git a/heartbeat/monitors/active/icmp/stdloop.go b/heartbeat/monitors/active/icmp/stdloop.go index f67ae402bc7..8fa0816bb5b 100644 --- a/heartbeat/monitors/active/icmp/stdloop.go +++ b/heartbeat/monitors/active/icmp/stdloop.go @@ -110,7 +110,7 @@ func getStdLoop() (*stdICMPLoop, error) { } func noPingCapabilityError(message string) error { - return fmt.Errorf(fmt.Sprintf("Insufficient privileges to perform ICMP ping. %s", message)) + return fmt.Errorf("Insufficient privileges to perform ICMP ping. %s", message) } func newICMPLoop() (*stdICMPLoop, error) { diff --git a/heartbeat/monitors/wrappers/summarizer/summarizertesthelper/testhelper.go b/heartbeat/monitors/wrappers/summarizer/summarizertesthelper/testhelper.go index bcea2bd803e..7c8d5de23bc 100644 --- a/heartbeat/monitors/wrappers/summarizer/summarizertesthelper/testhelper.go +++ b/heartbeat/monitors/wrappers/summarizer/summarizertesthelper/testhelper.go @@ -22,8 +22,6 @@ package summarizertesthelper // prevent import cycles. import ( - "fmt" - "github.com/elastic/beats/v7/heartbeat/hbtestllext" "github.com/elastic/beats/v7/heartbeat/monitors/wrappers/summarizer/jobsummary" "github.com/elastic/go-lookslike" @@ -46,11 +44,11 @@ func summaryIsdef(up uint16, down uint16) isdef.IsDef { return isdef.Is("summary", func(path llpath.Path, v interface{}) *llresult.Results { js, ok := v.(jobsummary.JobSummary) if !ok { - return llresult.SimpleResult(path, false, fmt.Sprintf("expected a *jobsummary.JobSummary, got %v", v)) + return llresult.SimpleResult(path, false, "expected a *jobsummary.JobSummary, got %v", v) } if js.Up != up || js.Down != down { - return llresult.SimpleResult(path, false, fmt.Sprintf("expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down)) + return llresult.SimpleResult(path, false, "expected up/down to be %d/%d, got %d/%d", up, down, js.Up, js.Down) } return llresult.ValidResult(path) diff --git a/libbeat/cmd/instance/beat.go b/libbeat/cmd/instance/beat.go index df3a71416b6..1a6250fad4d 100644 --- a/libbeat/cmd/instance/beat.go +++ b/libbeat/cmd/instance/beat.go @@ -388,7 +388,7 @@ func NewBeatReceiver(settings Settings, receiverConfig map[string]interface{}, c } // log paths values to help with troubleshooting - logp.Info(paths.Paths.String()) + logp.Info("%s", paths.Paths.String()) metaPath := paths.Resolve(paths.Data, "meta.json") err = b.loadMeta(metaPath) @@ -603,7 +603,7 @@ func (b *Beat) createBeater(bt beat.Creator) (beat.Beater, error) { logp.Info("Output is configured through Central Management") } else { msg := "no outputs are defined, please define one under the output section" - logp.Info(msg) + logp.Info("%s", msg) return nil, errors.New(msg) } } @@ -1055,7 +1055,7 @@ func (b *Beat) configure(settings Settings) error { } // log paths values to help with troubleshooting - logp.Info(paths.Paths.String()) + logp.Info("%s", paths.Paths.String()) metaPath := paths.Resolve(paths.Data, "meta.json") err = b.loadMeta(metaPath) diff --git a/libbeat/common/cli/confirm.go b/libbeat/common/cli/confirm.go index 7028561abe2..439174768ff 100644 --- a/libbeat/common/cli/confirm.go +++ b/libbeat/common/cli/confirm.go @@ -35,14 +35,14 @@ func Confirm(prompt string, def bool) (bool, error) { } func confirm(r io.Reader, out io.Writer, prompt string, def bool) (bool, error) { - options := " [Y/n]" + options := "[Y/n]" if !def { - options = " [y/N]" + options = "[y/N]" } reader := bufio.NewScanner(r) for { - fmt.Fprintf(out, prompt+options+":") + fmt.Fprintf(out, "%s %s:", prompt, options) if !reader.Scan() { break diff --git a/libbeat/common/cli/input.go b/libbeat/common/cli/input.go index 0d5163e4ec1..9584a525c45 100644 --- a/libbeat/common/cli/input.go +++ b/libbeat/common/cli/input.go @@ -34,7 +34,7 @@ func ReadInput(prompt string) (string, error) { func input(r io.Reader, out io.Writer, prompt string) (string, error) { reader := bufio.NewScanner(r) - fmt.Fprintf(out, prompt+" ") + fmt.Fprintf(out, "%s ", prompt) if !reader.Scan() { return "", errors.New("error reading user input") diff --git a/libbeat/common/schema/mapstriface/mapstriface.go b/libbeat/common/schema/mapstriface/mapstriface.go index 209ac0e03ce..d06119a5bf0 100644 --- a/libbeat/common/schema/mapstriface/mapstriface.go +++ b/libbeat/common/schema/mapstriface/mapstriface.go @@ -72,6 +72,7 @@ package mapstriface import ( "encoding/json" + "errors" "fmt" "time" @@ -102,18 +103,19 @@ func (convMap ConvMap) Map(key string, event mapstr.M, data map[string]interface switch subData := d.(type) { case map[string]interface{}, mapstr.M: subEvent := mapstr.M{} - _, errors := convMap.Schema.ApplyTo(subEvent, subData.(map[string]interface{})) - for _, err := range errors { - if err, ok := err.(schema.KeyError); ok { - err.SetKey(convMap.Key + "." + err.Key()) + _, errs := convMap.Schema.ApplyTo(subEvent, subData.(map[string]interface{})) + for _, err := range errs { + var keyErr schema.KeyError + if errors.As(err, &keyErr) { + keyErr.SetKey(convMap.Key + "." + keyErr.Key()) } } event[key] = subEvent - return errors + return errs default: msg := fmt.Sprintf("expected dictionary, found %T", subData) err := schema.NewWrongFormatError(convMap.Key, msg) - logp.Err(err.Error()) + logp.Err("%s", err.Error()) return multierror.Errors{err} } } @@ -135,11 +137,11 @@ func toStrFromNum(key string, data map[string]interface{}) (interface{}, error) if err != nil { return "", schema.NewKeyNotFoundError(key) } - switch emptyIface.(type) { + switch val := emptyIface.(type) { case int, int32, int64, uint, uint32, uint64, float32, float64: return fmt.Sprintf("%v", emptyIface), nil case json.Number: - return string(emptyIface.(json.Number)), nil + return string(val), nil default: msg := fmt.Sprintf("expected number, found %T", emptyIface) return "", schema.NewWrongFormatError(key, msg) @@ -207,24 +209,23 @@ func toInteger(key string, data map[string]interface{}) (interface{}, error) { if err != nil { return 0, schema.NewKeyNotFoundError(key) } - switch emptyIface.(type) { + switch val := emptyIface.(type) { case int64: - return emptyIface.(int64), nil + return val, nil case int: - return int64(emptyIface.(int)), nil + return int64(val), nil case float64: - return int64(emptyIface.(float64)), nil + return int64(val), nil case json.Number: - num := emptyIface.(json.Number) - i64, err := num.Int64() + i64, err := val.Int64() if err == nil { return i64, nil } - f64, err := num.Float64() + f64, err := val.Float64() if err == nil { return int64(f64), nil } - msg := fmt.Sprintf("expected integer, found json.Number (%v) that cannot be converted", num) + msg := fmt.Sprintf("expected integer, found json.Number (%v) that cannot be converted", val) return 0, schema.NewWrongFormatError(key, msg) default: msg := fmt.Sprintf("expected integer, found %T", emptyIface) @@ -243,24 +244,23 @@ func toFloat(key string, data map[string]interface{}) (interface{}, error) { if err != nil { return 0.0, schema.NewKeyNotFoundError(key) } - switch emptyIface.(type) { + switch val := emptyIface.(type) { case float64: - return emptyIface.(float64), nil + return val, nil case int: - return float64(emptyIface.(int)), nil + return float64(val), nil case int64: - return float64(emptyIface.(int64)), nil + return float64(val), nil case json.Number: - num := emptyIface.(json.Number) - i64, err := num.Float64() + i64, err := val.Float64() if err == nil { return i64, nil } - f64, err := num.Float64() + f64, err := val.Float64() if err == nil { return f64, nil } - msg := fmt.Sprintf("expected float, found json.Number (%v) that cannot be converted", num) + msg := fmt.Sprintf("expected float, found json.Number (%v) that cannot be converted", val) return 0.0, schema.NewWrongFormatError(key, msg) default: msg := fmt.Sprintf("expected float, found %T", emptyIface) @@ -280,17 +280,11 @@ func toTime(key string, data map[string]interface{}) (interface{}, error) { return common.Time(time.Unix(0, 0)), schema.NewKeyNotFoundError(key) } - switch emptyIface.(type) { + switch val := emptyIface.(type) { case time.Time: - ts, ok := emptyIface.(time.Time) - if ok { - return common.Time(ts), nil - } + return common.Time(val), nil case common.Time: - ts, ok := emptyIface.(common.Time) - if ok { - return ts, nil - } + return val, nil } msg := fmt.Sprintf("expected date, found %T", emptyIface) diff --git a/libbeat/dashboards/get.go b/libbeat/dashboards/get.go index 2da82ef4444..7b983c29090 100644 --- a/libbeat/dashboards/get.go +++ b/libbeat/dashboards/get.go @@ -35,7 +35,7 @@ var ( // GetDashboard returns the dashboard with the given id with the index pattern removed func Get(client *kibana.Client, id string) ([]byte, error) { if client.Version.LessThan(MinimumRequiredVersionSavedObjects) { - return nil, fmt.Errorf("Kibana version must be at least " + MinimumRequiredVersionSavedObjects.String()) + return nil, fmt.Errorf("Kibana version must be at least %s", MinimumRequiredVersionSavedObjects.String()) } // add a special header for serverless, where saved_objects is "hidden" diff --git a/libbeat/dashboards/kibana_loader.go b/libbeat/dashboards/kibana_loader.go index 55d195c4f8e..3320f996a2a 100644 --- a/libbeat/dashboards/kibana_loader.go +++ b/libbeat/dashboards/kibana_loader.go @@ -21,8 +21,8 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "net/url" + "os" "path/filepath" "time" @@ -104,13 +104,13 @@ func getKibanaClient(ctx context.Context, cfg *config.C, retryCfg *Retry, retryA // ImportIndexFile imports an index pattern from a file func (loader KibanaLoader) ImportIndexFile(file string) error { if loader.version.LessThan(minimumRequiredVersionSavedObjects) { - return fmt.Errorf("Kibana version must be at least " + minimumRequiredVersionSavedObjects.String()) + return fmt.Errorf("Kibana version must be at least %s", minimumRequiredVersionSavedObjects.String()) } loader.statusMsg("Importing index file from %s", file) // read json file - reader, err := ioutil.ReadFile(file) + reader, err := os.ReadFile(file) if err != nil { return fmt.Errorf("fail to read index-pattern from file %s: %w", file, err) } @@ -127,7 +127,7 @@ func (loader KibanaLoader) ImportIndexFile(file string) error { // ImportIndex imports the passed index pattern to Kibana func (loader KibanaLoader) ImportIndex(pattern mapstr.M) error { if loader.version.LessThan(minimumRequiredVersionSavedObjects) { - return fmt.Errorf("kibana version must be at least " + minimumRequiredVersionSavedObjects.String()) + return fmt.Errorf("kibana version must be at least %s", minimumRequiredVersionSavedObjects.String()) } var errs multierror.Errors @@ -149,7 +149,7 @@ func (loader KibanaLoader) ImportIndex(pattern mapstr.M) error { // ImportDashboard imports the dashboard file func (loader KibanaLoader) ImportDashboard(file string) error { if loader.version.LessThan(minimumRequiredVersionSavedObjects) { - return fmt.Errorf("Kibana version must be at least " + minimumRequiredVersionSavedObjects.String()) + return fmt.Errorf("Kibana version must be at least %s", minimumRequiredVersionSavedObjects.String()) } loader.statusMsg("Importing dashboard from %s", file) @@ -158,7 +158,7 @@ func (loader KibanaLoader) ImportDashboard(file string) error { params.Set("overwrite", "true") // read json file - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) if err != nil { return fmt.Errorf("fail to read dashboard from file %s: %w", file, err) } @@ -203,7 +203,7 @@ func (loader KibanaLoader) addReferences(path string, dashboard []byte) (string, if _, ok := loader.loadedAssets[referencePath]; ok { continue } - refContents, err := ioutil.ReadFile(referencePath) + refContents, err := os.ReadFile(referencePath) if err != nil { return "", fmt.Errorf("fail to read referenced asset from file %s: %w", referencePath, err) } diff --git a/libbeat/processors/actions/decode_json_fields.go b/libbeat/processors/actions/decode_json_fields.go index b47ebd646d9..ad8ffb6ade7 100644 --- a/libbeat/processors/actions/decode_json_fields.go +++ b/libbeat/processors/actions/decode_json_fields.go @@ -177,7 +177,7 @@ func (f *decodeJSONFields) Run(event *beat.Event) (*beat.Event, error) { } if len(errs) > 0 { - return event, fmt.Errorf(strings.Join(errs, ", ")) + return event, errors.New(strings.Join(errs, ", ")) } return event, nil } diff --git a/libbeat/processors/actions/include_fields.go b/libbeat/processors/actions/include_fields.go index 08419e7c2ec..718da6c456c 100644 --- a/libbeat/processors/actions/include_fields.go +++ b/libbeat/processors/actions/include_fields.go @@ -84,7 +84,7 @@ func (f *includeFields) Run(event *beat.Event) (*beat.Event, error) { event.Fields = filtered if len(errs) > 0 { - return event, fmt.Errorf(strings.Join(errs, ", ")) + return event, errors.New(strings.Join(errs, ", ")) } return event, nil } diff --git a/metricbeat/helper/kubernetes/ktest/ktest.go b/metricbeat/helper/kubernetes/ktest/ktest.go index 2e811069b79..5b1a73f7dbb 100644 --- a/metricbeat/helper/kubernetes/ktest/ktest.go +++ b/metricbeat/helper/kubernetes/ktest/ktest.go @@ -103,7 +103,7 @@ func TestMetricsFamilyFromFiles(t *testing.T, files []string, mapping *p.Metrics func TestMetricsFamilyFromFolder(t *testing.T, folder string, mapping *p.MetricsMapping) { files, err := getFiles(folder) if err != nil { - t.Fatalf(err.Error()) + t.Fatal(err.Error()) } TestMetricsFamilyFromFiles(t, files, mapping) } diff --git a/metricbeat/module/elasticsearch/elasticsearch.go b/metricbeat/module/elasticsearch/elasticsearch.go index 41f498a9de4..446a2d128bb 100644 --- a/metricbeat/module/elasticsearch/elasticsearch.go +++ b/metricbeat/module/elasticsearch/elasticsearch.go @@ -558,7 +558,7 @@ func (l *License) ToMapStr() mapstr.M { func getSettingGroup(allSettings mapstr.M, groupKey string) (mapstr.M, error) { hasSettingGroup, err := allSettings.HasKey(groupKey) if err != nil { - return nil, fmt.Errorf("failure to determine if "+groupKey+" settings exist: %w", err) + return nil, fmt.Errorf("failure to determine if %s settings exist: %w", groupKey, err) } if !hasSettingGroup { @@ -567,12 +567,12 @@ func getSettingGroup(allSettings mapstr.M, groupKey string) (mapstr.M, error) { settings, err := allSettings.GetValue(groupKey) if err != nil { - return nil, fmt.Errorf("failure to extract "+groupKey+" settings: %w", err) + return nil, fmt.Errorf("failure to extract %s settings: %w", groupKey, err) } v, ok := settings.(map[string]interface{}) if !ok { - return nil, fmt.Errorf(groupKey + " settings are not a map") + return nil, fmt.Errorf("%s settings are not a map", groupKey) } return mapstr.M(v), nil diff --git a/metricbeat/module/prometheus/query/data.go b/metricbeat/module/prometheus/query/data.go index 298f1efd22d..fbd535df137 100644 --- a/metricbeat/module/prometheus/query/data.go +++ b/metricbeat/module/prometheus/query/data.go @@ -19,6 +19,7 @@ package query import ( "encoding/json" + "errors" "fmt" "math" "strconv" @@ -120,8 +121,7 @@ func parseResponse(body []byte, pathConfig QueryConfig) ([]mb.Event, error) { } events = append(events, evnts...) default: - msg := fmt.Sprintf("Unknown resultType '%v'", resultType) - return events, fmt.Errorf(msg) + return events, fmt.Errorf("Unknown resultType '%v'", resultType) } return events, nil } @@ -223,8 +223,7 @@ func getEventFromScalarOrString(body []byte, resultType string, queryName string } else if resultType == "string" { value, ok := convertedArray.Data.Results[1].(string) if !ok { - msg := fmt.Sprintf("Could not parse value of result: %v", convertedArray.Data.Results) - return mb.Event{}, fmt.Errorf(msg) + return mb.Event{}, fmt.Errorf("Could not parse value of result: %v", convertedArray.Data.Results) } return mb.Event{ Timestamp: getTimestamp(timestamp), @@ -249,8 +248,7 @@ func getTimestampFromVector(vector []interface{}) (float64, error) { } timestamp, ok := vector[0].(float64) if !ok { - msg := fmt.Sprintf("Could not parse timestamp of result: %v", vector) - return 0, fmt.Errorf(msg) + return 0, fmt.Errorf("Could not parse timestamp of result: %v", vector) } return timestamp, nil } @@ -258,17 +256,15 @@ func getTimestampFromVector(vector []interface{}) (float64, error) { func getValueFromVector(vector []interface{}) (float64, error) { // Example input: [ , "" ] if len(vector) != 2 { - return 0, fmt.Errorf("could not parse results") + return 0, errors.New("could not parse results") } value, ok := vector[1].(string) if !ok { - msg := fmt.Sprintf("Could not parse value of result: %v", vector) - return 0, fmt.Errorf(msg) + return 0, fmt.Errorf("Could not parse value of result: %v", vector) } val, err := strconv.ParseFloat(value, 64) if err != nil { - msg := fmt.Sprintf("Could not parse value of result: %v", vector) - return 0, fmt.Errorf(msg) + return 0, fmt.Errorf("Could not parse value of result: %v", vector) } return val, nil } diff --git a/packetbeat/beater/processor.go b/packetbeat/beater/processor.go index 135f0c18ac7..0e32723c6ee 100644 --- a/packetbeat/beater/processor.go +++ b/packetbeat/beater/processor.go @@ -158,7 +158,7 @@ func (p *processorFactory) Create(pipeline beat.PipelineConnector, cfg *conf.C) if config.Interfaces[0].File == "" { err = watch.Init(config.Procs) if err != nil { - logp.Critical(err.Error()) + logp.Critical("%s", err.Error()) return nil, err } } else { diff --git a/packetbeat/config/agent.go b/packetbeat/config/agent.go index c5ccd589c07..ba86116f166 100644 --- a/packetbeat/config/agent.go +++ b/packetbeat/config/agent.go @@ -122,7 +122,7 @@ func NewAgentConfig(cfg *conf.C) (Config, error) { return config, err } - logp.Debug("agent", fmt.Sprintf("Found %d inputs", len(input.Streams))) + logp.Debug("agent", "Found %d inputs", len(input.Streams)) for _, stream := range input.Streams { if interfaceOverride, ok := stream["interface"]; ok { cfg, err := conf.NewConfigFrom(interfaceOverride) @@ -153,7 +153,7 @@ func NewAgentConfig(cfg *conf.C) (Config, error) { if !ok { return config, fmt.Errorf("invalid input type of: '%T'", rawStreamType) } - logp.Debug("agent", fmt.Sprintf("Found agent configuration for %v", streamType)) + logp.Debug("agent", "Found agent configuration for %v", streamType) cfg, err := conf.NewConfigFrom(stream) if err != nil { return config, err diff --git a/packetbeat/procs/procs_linux.go b/packetbeat/procs/procs_linux.go index cabddde3be8..8ad952a1e26 100644 --- a/packetbeat/procs/procs_linux.go +++ b/packetbeat/procs/procs_linux.go @@ -136,14 +136,14 @@ func findSocketsOfPid(prefix string, pid int) (inodes []uint64, err error) { for _, name := range names { link, err := os.Readlink(filepath.Join(dirname, name)) if err != nil { - logp.Debug("procs", err.Error()) + logp.Debug("procs", "%s", err.Error()) continue } if strings.HasPrefix(link, "socket:[") { inode, err := strconv.ParseInt(link[8:len(link)-1], 10, 64) if err != nil { - logp.Debug("procs", err.Error()) + logp.Debug("procs", "%s", err.Error()) continue } diff --git a/packetbeat/protos/http/http_test.go b/packetbeat/protos/http/http_test.go index c8c7a9c7344..50bf9e0874a 100644 --- a/packetbeat/protos/http/http_test.go +++ b/packetbeat/protos/http/http_test.go @@ -986,7 +986,7 @@ func TestHttpParser_RedactAuthorization_raw(t *testing.T) { rawMessageObscured := bytes.Index(msg, []byte("uthorization:*")) if rawMessageObscured < 0 { - t.Errorf("Obscured authorization string not found: " + string(msg[:])) + t.Error("Obscured authorization string not found: " + string(msg[:])) } } @@ -1021,7 +1021,7 @@ func TestHttpParser_RedactAuthorization_Proxy_raw(t *testing.T) { rawMessageObscured := bytes.Index(msg, []byte("uthorization:*")) if rawMessageObscured < 0 { - t.Errorf("Failed to redact proxy-authorization header: " + string(msg[:])) + t.Error("Failed to redact proxy-authorization header: " + string(msg[:])) } }