Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[metricbeat] replace depricated io/ioutil #36963

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions metricbeat/autodiscover/appender/kubernetes/token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import (
"fmt"
"io/ioutil"
"os"

"github.com/elastic/beats/v7/libbeat/autodiscover"
"github.com/elastic/beats/v7/libbeat/common/cfgwarn"
Expand All @@ -31,7 +31,7 @@
)

func init() {
autodiscover.Registry.AddAppender("kubernetes.token", NewTokenAppender)

Check failure on line 34 in metricbeat/autodiscover/appender/kubernetes/token/token.go

View workflow job for this annotation

GitHub Actions / lint (linux)

Error return value of `autodiscover.Registry.AddAppender` is not checked (errcheck)
}

type tokenAppender struct {
Expand All @@ -47,7 +47,7 @@

err := cfg.Unpack(&conf)
if err != nil {
return nil, fmt.Errorf("unable to unpack config due to error: %v", err)

Check failure on line 50 in metricbeat/autodiscover/appender/kubernetes/token/token.go

View workflow job for this annotation

GitHub Actions / lint (linux)

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}

var cond conditions.Condition
Expand All @@ -55,7 +55,7 @@
// Attempt to create a condition. If fails then report error
cond, err = conditions.NewCondition(conf.ConditionConfig)
if err != nil {
return nil, fmt.Errorf("unable to create condition due to error: %v", err)

Check failure on line 58 in metricbeat/autodiscover/appender/kubernetes/token/token.go

View workflow job for this annotation

GitHub Actions / lint (linux)

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}
}
appender := tokenAppender{
Expand All @@ -81,7 +81,7 @@
}

// Check if the condition is met. Attempt to append only if that is the case.
if t.Condition == nil || t.Condition.Check(mapstr.M(event)) == true {

Check failure on line 84 in metricbeat/autodiscover/appender/kubernetes/token/token.go

View workflow job for this annotation

GitHub Actions / lint (linux)

S1002: should omit comparison to bool constant, can be simplified to `t.Condition.Check(mapstr.M(event))` (gosimple)
tok := t.getAuthHeaderFromToken()
// If token is empty then just return
if tok == "" {
Expand Down Expand Up @@ -127,7 +127,7 @@
var token string

if t.TokenPath != "" {
b, err := ioutil.ReadFile(t.TokenPath)
b, err := os.ReadFile(t.TokenPath)
if err != nil {
logp.Err("Reading token file failed with err: %v", err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
package token

import (
"io/ioutil"
"os"
"testing"

Expand Down Expand Up @@ -93,7 +92,7 @@
assert.Equal(t, len(cfgs), 1)

out := mapstr.M{}
cfgs[0].Unpack(&out)

Check failure on line 95 in metricbeat/autodiscover/appender/kubernetes/token/token_test.go

View workflow job for this annotation

GitHub Actions / lint (linux)

Error return value of `(*github.com/elastic/elastic-agent-libs/config.C).Unpack` is not checked (errcheck)

assert.Equal(t, out, test.result)
deleteFile("test")
Expand All @@ -101,7 +100,7 @@
}

func writeFile(name, message string) {
ioutil.WriteFile(name, []byte(message), os.ModePerm)
os.WriteFile(name, []byte(message), os.ModePerm)

Check failure on line 103 in metricbeat/autodiscover/appender/kubernetes/token/token_test.go

View workflow job for this annotation

GitHub Actions / lint (linux)

Error return value of `os.WriteFile` is not checked (errcheck)
}

func deleteFile(name string) {
Expand Down
6 changes: 3 additions & 3 deletions metricbeat/helper/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"

"github.com/elastic/beats/v7/libbeat/version"
"github.com/elastic/beats/v7/metricbeat/helper/dialer"
Expand Down Expand Up @@ -115,7 +115,7 @@
reader = bytes.NewReader(h.body)
}

req, err := http.NewRequest(h.method, h.uri, reader)

Check failure on line 118 in metricbeat/helper/http.go

View workflow job for this annotation

GitHub Actions / lint (linux)

should rewrite http.NewRequestWithContext or add (*Request).WithContext (noctx)
if err != nil {
return nil, fmt.Errorf("failed to create HTTP request: %w", err)
}
Expand All @@ -126,7 +126,7 @@

resp, err := h.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error making http request: %v", err)

Check failure on line 129 in metricbeat/helper/http.go

View workflow job for this annotation

GitHub Actions / lint (linux)

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)
}

return resp, nil
Expand Down Expand Up @@ -179,7 +179,7 @@
return nil, fmt.Errorf("HTTP error %d in %s: %s", resp.StatusCode, h.name, resp.Status)
}

return ioutil.ReadAll(resp.Body)
return io.ReadAll(resp.Body)
}

// FetchScanner returns a Scanner for the content.
Expand Down Expand Up @@ -214,7 +214,7 @@
func getAuthHeaderFromToken(path string) (string, error) {
var token string

b, err := ioutil.ReadFile(path)
b, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("reading bearer token file: %w", err)
}
Expand Down
8 changes: 4 additions & 4 deletions metricbeat/helper/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import (
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -55,7 +55,7 @@
for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
content := []byte(test.Content)
tmpfile, err := ioutil.TempFile("", "token")
tmpfile, err := os.CreateTemp("", "token")
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -236,14 +236,14 @@
fmt.Fprintf(w, "ehlo!")
})

go http.Serve(l, mux)

Check failure on line 239 in metricbeat/helper/http_test.go

View workflow job for this annotation

GitHub Actions / lint (linux)

Error return value of `http.Serve` is not checked (errcheck)

return l
}

for title, c := range cases {
t.Run(title, func(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "testsocket")
tmpDir, err := os.MkdirTemp("", "testsocket")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)

Expand All @@ -262,7 +262,7 @@
r, err := h.FetchResponse()
require.NoError(t, err)
defer r.Body.Close()
content, err := ioutil.ReadAll(r.Body)
content, err := io.ReadAll(r.Body)
require.NoError(t, err)
assert.Equal(t, []byte("ehlo!"), content)
})
Expand Down
4 changes: 2 additions & 2 deletions metricbeat/helper/kubernetes/ktest/ktest.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
package ktest

import (
"io/ioutil"
"os"
"strings"
"testing"

Expand Down Expand Up @@ -57,7 +57,7 @@ func GetTestCases(files []string) ptest.TestCases {
func TestMetricsFamily(t *testing.T, files []string, mapping *p.MetricsMapping) {
metricsFiles := map[string][]string{}
for i := 0; i < len(files); i++ {
content, err := ioutil.ReadFile(files[i])
content, err := os.ReadFile(files[i])
if err != nil {
t.Fatalf("Unknown file %s.", files[i])
}
Expand Down
4 changes: 2 additions & 2 deletions metricbeat/helper/server/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

import (
"context"
"io/ioutil"
"io"
"net"
"net/http"
"strconv"
Expand Down Expand Up @@ -72,7 +72,7 @@
stop: cancel,
}

httpServer := &http.Server{

Check failure on line 75 in metricbeat/helper/server/http/http.go

View workflow job for this annotation

GitHub Actions / lint (linux)

G112: Potential Slowloris Attack because ReadHeaderTimeout is not configured in the http.Server (gosec)
Addr: net.JoinHostPort(config.Host, strconv.Itoa(int(config.Port))),
}
if tlsConfig != nil {
Expand Down Expand Up @@ -147,7 +147,7 @@
meta["Content-Type"] = contentType
}

body, err := ioutil.ReadAll(req.Body)
body, err := io.ReadAll(req.Body)
if err != nil {
logp.Err("Error reading body: %v", err)
http.Error(writer, "Unexpected error reading request payload", http.StatusBadRequest)
Expand Down
8 changes: 6 additions & 2 deletions metricbeat/helper/server/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"io"
"net"
"net/http"
"strconv"
Expand Down Expand Up @@ -212,6 +212,10 @@ func writeToServer(t *testing.T, message, host string, port int, connectionMetho
url := fmt.Sprintf("%s://%s:%d/", strings.ToLower(connectionType), host, port)
var str = []byte(message)
req, err := http.NewRequest(connectionMethod, url, bytes.NewBuffer(str))
if err != nil {
t.Error(err)
t.FailNow()
Comment on lines +216 to +217
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That can be replaced by a single t.Fatal()

Suggested change
t.Error(err)
t.FailNow()
t.Fatal(err)

}
req.Header.Set("Content-Type", "text/plain")
client := &http.Client{}
if connectionType == "HTTPS" {
Expand All @@ -230,7 +234,7 @@ func writeToServer(t *testing.T, message, host string, port int, connectionMetho

if connectionMethod == "GET" {
if resp.StatusCode == http.StatusOK {
bodyBytes, err2 := ioutil.ReadAll(resp.Body)
bodyBytes, err2 := io.ReadAll(resp.Body)
if err2 != nil {
t.Error(err)
t.FailNow()
Expand Down
3 changes: 1 addition & 2 deletions metricbeat/mb/lightmodules.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package mb

import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -260,7 +259,7 @@ func (s *LightModulesSource) moduleNames() ([]string, error) {
s.log.Debugf("Light modules directory '%d' doesn't exist", dir)
continue
}
files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("listing modules on path '%s': %w", dir, err)
}
Expand Down
3 changes: 1 addition & 2 deletions metricbeat/mb/testing/data_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ package testing
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"testing"
Expand Down Expand Up @@ -184,7 +183,7 @@ func WriteEventToDataJSON(t testing.TB, fullEvent beat.Event, postfixPath string
t.Fatal(err)
}

if err = ioutil.WriteFile(p, output, 0644); err != nil {
if err = os.WriteFile(p, output, 0644); err != nil {
t.Fatal(err)
}
}
Expand Down
5 changes: 2 additions & 3 deletions metricbeat/mb/testing/lightmodules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ package testing
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
Expand Down Expand Up @@ -103,7 +102,7 @@ func TestDataLightModuleWithProcessors(t *testing.T) {
assert.Empty(t, errs)
assert.NotEmpty(t, events)

dir, err := ioutil.TempDir("", "_meta-*")
dir, err := os.MkdirTemp("", "_meta-*")
require.NoError(t, err)
defer os.RemoveAll(dir)

Expand All @@ -127,7 +126,7 @@ func TestDataLightModuleWithProcessors(t *testing.T) {
}
}

d, err := ioutil.ReadFile(dataPath)
d, err := os.ReadFile(dataPath)
require.NoError(t, err)

err = json.Unmarshal(d, &event)
Expand Down
16 changes: 10 additions & 6 deletions metricbeat/mb/testing/testdata.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ package testing
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sort"
"strings"
Expand Down Expand Up @@ -131,7 +131,7 @@ func ReadDataConfig(t *testing.T, f string) DataConfig {
t.Helper()
config := defaultDataConfig()

configFile, err := ioutil.ReadFile(f)
configFile, err := os.ReadFile(f)
if err != nil {
t.Fatalf("failed to read '%s': %v", f, err)
}
Expand Down Expand Up @@ -294,13 +294,13 @@ func runTest(t *testing.T, file string, module, metricSetName string, config Dat
if err != nil {
t.Fatal(err)
}
if err = ioutil.WriteFile(expectedFile, outputIndented, 0644); err != nil {
if err = os.WriteFile(expectedFile, outputIndented, 0644); err != nil {
t.Fatal(err)
}
}

// Read expected file
expected, err := ioutil.ReadFile(expectedFile)
expected, err := os.ReadFile(expectedFile)
if err != nil {
t.Fatalf("could not read file: %s", err)
}
Expand Down Expand Up @@ -362,7 +362,11 @@ func writeDataJSON(t *testing.T, data mapstr.M, path string) {
// Add hardcoded timestamp
data.Put("@timestamp", "2019-03-01T08:05:34.853Z")
output, err := json.MarshalIndent(&data, "", " ")
if err = ioutil.WriteFile(path, output, 0644); err != nil {
if err != nil {
t.Error(err)
t.FailNow()
Comment on lines +366 to +367
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here

Suggested change
t.Error(err)
t.FailNow()
t.Fatal(err)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at existing code, t.Error(err) followed by t.FailNow() is the most common pattern. So far, no one cared that the error was ignored so far. And the change was added, just to make linter happy.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at existing code, t.Error(err) followed by t.FailNow() is the most common pattern.

The bits of the codebase I mostly work with follow a different pattern 😅 , anyway this one is not a blocker.

}
if err = os.WriteFile(path, output, 0644); err != nil {
t.Fatal(err)
}
}
Expand Down Expand Up @@ -494,7 +498,7 @@ func getConfig(module, metricSet, url string, config DataConfig) map[string]inte
// server starts a server with a mock output
func server(t *testing.T, path string, url string, contentType string) *httptest.Server {

body, err := ioutil.ReadFile(path)
body, err := os.ReadFile(path)
if err != nil {
t.Fatalf("could not read file: %s", err)
}
Expand Down
4 changes: 2 additions & 2 deletions metricbeat/module/beat/state/data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
package state

import (
"io/ioutil"
"os"
"path/filepath"
"testing"

Expand All @@ -42,7 +42,7 @@ func TestEventMapping(t *testing.T) {
}

for _, f := range files {
input, err := ioutil.ReadFile(f)
input, err := os.ReadFile(f)
require.NoError(t, err)

reporter := &mbtest.CapturingReporterV2{}
Expand Down
4 changes: 2 additions & 2 deletions metricbeat/module/beat/stats/data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
package stats

import (
"io/ioutil"
"os"
"path/filepath"
"testing"

Expand All @@ -44,7 +44,7 @@ func TestEventMapping(t *testing.T) {
clusterUUID := "foo"

for _, f := range files {
input, err := ioutil.ReadFile(f)
input, err := os.ReadFile(f)
require.NoError(t, err)

reporter := &mbtest.CapturingReporterV2{}
Expand Down
4 changes: 2 additions & 2 deletions metricbeat/module/ceph/cluster_disk/cluster_disk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
package cluster_disk

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"

Expand All @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) {
absPath, err := filepath.Abs("../_meta/testdata/")
assert.NoError(t, err)

response, err := ioutil.ReadFile(absPath + "/df_sample_response.json")
response, err := os.ReadFile(absPath + "/df_sample_response.json")
assert.NoError(t, err)

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
package cluster_health

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"

Expand All @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) {
absPath, err := filepath.Abs("../_meta/testdata/")
assert.NoError(t, err)

response, err := ioutil.ReadFile(absPath + "/sample_response.json")
response, err := os.ReadFile(absPath + "/sample_response.json")
assert.NoError(t, err)

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
package cluster_status

import (
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"

Expand All @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) {
absPath, err := filepath.Abs("../_meta/testdata/")
assert.NoError(t, err)

response, err := ioutil.ReadFile(absPath + "/status_sample_response.json")
response, err := os.ReadFile(absPath + "/status_sample_response.json")
assert.NoError(t, err)

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
Loading
Loading