diff --git a/.golangci.yml b/.golangci.yml index 400924ab9a..81790e6e3a 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,6 +16,7 @@ linters: - misspell issues: + max-same-issues: 0 exclude-rules: - path: _test.go linters: @@ -29,6 +30,7 @@ linters-settings: - sync/atomic: "Use go.uber.org/atomic instead of sync/atomic" - github.com/stretchr/testify/assert: "Use github.com/stretchr/testify/require instead of github.com/stretchr/testify/assert" - github.com/go-kit/kit/log: "Use github.com/go-kit/log instead of github.com/go-kit/kit/log" + - io/ioutil: "Use corresponding 'os' or 'io' functions instead." - regexp: "Use github.com/grafana/regexp instead of regexp" errcheck: exclude: scripts/errcheck_excludes.txt diff --git a/cmd/prometheus/main_test.go b/cmd/prometheus/main_test.go index 1f161d26be..cfdb5abdf0 100644 --- a/cmd/prometheus/main_test.go +++ b/cmd/prometheus/main_test.go @@ -17,7 +17,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "math" "os" "os/exec" @@ -211,7 +211,7 @@ func TestWALSegmentSizeBounds(t *testing.T) { stderr, err := prom.StderrPipe() require.NoError(t, err) go func() { - slurp, _ := ioutil.ReadAll(stderr) + slurp, _ := io.ReadAll(stderr) t.Log(string(slurp)) }() @@ -256,7 +256,7 @@ func TestMaxBlockChunkSegmentSizeBounds(t *testing.T) { stderr, err := prom.StderrPipe() require.NoError(t, err) go func() { - slurp, _ := ioutil.ReadAll(stderr) + slurp, _ := io.ReadAll(stderr) t.Log(string(slurp)) }() @@ -445,7 +445,7 @@ func TestModeSpecificFlags(t *testing.T) { stderr, err := prom.StderrPipe() require.NoError(t, err) go func() { - slurp, _ := ioutil.ReadAll(stderr) + slurp, _ := io.ReadAll(stderr) t.Log(string(slurp)) }() diff --git a/cmd/prometheus/query_log_test.go b/cmd/prometheus/query_log_test.go index 844bde1c96..d5dfbea509 100644 --- a/cmd/prometheus/query_log_test.go +++ b/cmd/prometheus/query_log_test.go @@ -17,7 +17,7 @@ import ( "bufio" "encoding/json" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/url" @@ -235,10 +235,10 @@ func (p *queryLogTest) run(t *testing.T) { p.skip(t) // Setup temporary files for this test. - queryLogFile, err := ioutil.TempFile("", "query") + queryLogFile, err := os.CreateTemp("", "query") require.NoError(t, err) defer os.Remove(queryLogFile.Name()) - p.configFile, err = ioutil.TempFile("", "config") + p.configFile, err = os.CreateTemp("", "config") require.NoError(t, err) defer os.Remove(p.configFile.Name()) @@ -269,7 +269,7 @@ func (p *queryLogTest) run(t *testing.T) { wg.Add(1) defer wg.Wait() go func() { - slurp, _ := ioutil.ReadAll(stderr) + slurp, _ := io.ReadAll(stderr) t.Log(string(slurp)) wg.Done() }() @@ -333,7 +333,7 @@ func (p *queryLogTest) run(t *testing.T) { return } // Move the file, Prometheus should still write to the old file. - newFile, err := ioutil.TempFile("", "newLoc") + newFile, err := os.CreateTemp("", "newLoc") require.NoError(t, err) require.NoError(t, newFile.Close()) defer os.Remove(newFile.Name()) diff --git a/cmd/promtool/debug.go b/cmd/promtool/debug.go index 23d613bb06..310004480a 100644 --- a/cmd/promtool/debug.go +++ b/cmd/promtool/debug.go @@ -15,7 +15,7 @@ package main import ( "fmt" - "io/ioutil" + "io" "net/http" "github.com/pkg/errors" @@ -41,7 +41,7 @@ func debugWrite(cfg debugWriterConfig) error { if err != nil { return errors.Wrap(err, "error executing HTTP request") } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { return errors.Wrap(err, "error reading the response body") diff --git a/cmd/promtool/main.go b/cmd/promtool/main.go index bf85786aec..0381a3dc22 100644 --- a/cmd/promtool/main.go +++ b/cmd/promtool/main.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math" "net/http" "net/url" @@ -541,7 +540,7 @@ func checkSDFile(filename string) ([]*targetgroup.Group, error) { } defer fd.Close() - content, err := ioutil.ReadAll(fd) + content, err := io.ReadAll(fd) if err != nil { return nil, err } diff --git a/cmd/promtool/rules_test.go b/cmd/promtool/rules_test.go index decda0fe38..aa66d08ded 100644 --- a/cmd/promtool/rules_test.go +++ b/cmd/promtool/rules_test.go @@ -15,8 +15,8 @@ package main import ( "context" - "io/ioutil" "math" + "os" "path/filepath" "testing" "time" @@ -188,7 +188,7 @@ func createSingleRuleTestFiles(path string) error { labels: testlabel11: testlabelvalue11 ` - return ioutil.WriteFile(path, []byte(recordingRules), 0o777) + return os.WriteFile(path, []byte(recordingRules), 0o777) } func createMultiRuleTestFiles(path string) error { @@ -208,7 +208,7 @@ func createMultiRuleTestFiles(path string) error { labels: testlabel11: testlabelvalue13 ` - return ioutil.WriteFile(path, []byte(recordingRules), 0o777) + return os.WriteFile(path, []byte(recordingRules), 0o777) } // TestBackfillLabels confirms that the labels in the rule file override the labels from the metrics @@ -236,7 +236,7 @@ func TestBackfillLabels(t *testing.T) { labels: name1: value-from-rule ` - require.NoError(t, ioutil.WriteFile(path, []byte(recordingRules), 0o777)) + require.NoError(t, os.WriteFile(path, []byte(recordingRules), 0o777)) errs := ruleImporter.loadGroups(ctx, []string{path}) for _, err := range errs { require.NoError(t, err) diff --git a/cmd/promtool/unittest.go b/cmd/promtool/unittest.go index 57b6103b0b..fd06f0e2d7 100644 --- a/cmd/promtool/unittest.go +++ b/cmd/promtool/unittest.go @@ -16,7 +16,6 @@ package main import ( "context" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -64,7 +63,7 @@ func RulesUnitTest(queryOpts promql.LazyLoaderOpts, files ...string) int { func ruleUnitTest(filename string, queryOpts promql.LazyLoaderOpts) []error { fmt.Println("Unit Testing: ", filename) - b, err := ioutil.ReadFile(filename) + b, err := os.ReadFile(filename) if err != nil { return []error{err} } diff --git a/config/config.go b/config/config.go index 2c5fc447a1..6ab790f610 100644 --- a/config/config.go +++ b/config/config.go @@ -15,7 +15,6 @@ package config import ( "fmt" - "io/ioutil" "net/url" "os" "path/filepath" @@ -103,7 +102,7 @@ func Load(s string, expandExternalLabels bool, logger log.Logger) (*Config, erro // LoadFile parses the given YAML file into a Config. func LoadFile(filename string, agentMode, expandExternalLabels bool, logger log.Logger) (*Config, error) { - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/config/config_test.go b/config/config_test.go index 65a8110007..e0f7621949 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -16,7 +16,6 @@ package config import ( "crypto/tls" "encoding/json" - "io/ioutil" "net/url" "os" "path/filepath" @@ -1510,7 +1509,7 @@ func TestBadConfigs(t *testing.T) { } func TestBadStaticConfigsJSON(t *testing.T) { - content, err := ioutil.ReadFile("testdata/static_config.bad.json") + content, err := os.ReadFile("testdata/static_config.bad.json") require.NoError(t, err) var tg targetgroup.Group err = json.Unmarshal(content, &tg) @@ -1518,7 +1517,7 @@ func TestBadStaticConfigsJSON(t *testing.T) { } func TestBadStaticConfigsYML(t *testing.T) { - content, err := ioutil.ReadFile("testdata/static_config.bad.yml") + content, err := os.ReadFile("testdata/static_config.bad.yml") require.NoError(t, err) var tg targetgroup.Group err = yaml.UnmarshalStrict(content, &tg) diff --git a/discovery/eureka/client.go b/discovery/eureka/client.go index 65c5b67bfe..071743d797 100644 --- a/discovery/eureka/client.go +++ b/discovery/eureka/client.go @@ -18,7 +18,6 @@ import ( "encoding/xml" "fmt" "io" - "io/ioutil" "net/http" "github.com/pkg/errors" @@ -95,7 +94,7 @@ func fetchApps(ctx context.Context, server string, client *http.Client) (*Applic return nil, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() diff --git a/discovery/file/file.go b/discovery/file/file.go index 6d645e90d4..0e8e7fd475 100644 --- a/discovery/file/file.go +++ b/discovery/file/file.go @@ -17,7 +17,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -376,7 +376,7 @@ func (d *Discovery) readFile(filename string) ([]*targetgroup.Group, error) { } defer fd.Close() - content, err := ioutil.ReadAll(fd) + content, err := io.ReadAll(fd) if err != nil { return nil, err } diff --git a/discovery/file/file_test.go b/discovery/file/file_test.go index 6c4e022d25..e3b59b4743 100644 --- a/discovery/file/file_test.go +++ b/discovery/file/file_test.go @@ -17,7 +17,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -73,7 +72,7 @@ func (t *testRunner) copyFile(src string) string { func (t *testRunner) copyFileTo(src, name string) string { t.Helper() - newf, err := ioutil.TempFile(t.dir, "") + newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) f, err := os.Open(src) @@ -95,7 +94,7 @@ func (t *testRunner) copyFileTo(src, name string) string { func (t *testRunner) writeString(file, data string) { t.Helper() - newf, err := ioutil.TempFile(t.dir, "") + newf, err := os.CreateTemp(t.dir, "") require.NoError(t, err) _, err = newf.WriteString(data) diff --git a/discovery/hetzner/robot.go b/discovery/hetzner/robot.go index d0f3e4d948..73d896450d 100644 --- a/discovery/hetzner/robot.go +++ b/discovery/hetzner/robot.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "strconv" @@ -85,7 +84,7 @@ func (d *robotDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -93,7 +92,7 @@ func (d *robotDiscovery) refresh(ctx context.Context) ([]*targetgroup.Group, err return nil, errors.Errorf("non 2xx status '%d' response during hetzner service discovery with role robot", resp.StatusCode) } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/discovery/http/http.go b/discovery/http/http.go index 09a100c6b2..f9380ddba5 100644 --- a/discovery/http/http.go +++ b/discovery/http/http.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -157,7 +156,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { return nil, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -171,7 +170,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { return nil, errors.Errorf("unsupported content type %q", resp.Header.Get("Content-Type")) } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { failuresCount.Inc() return nil, err diff --git a/discovery/kubernetes/kubernetes.go b/discovery/kubernetes/kubernetes.go index 4fa561b6eb..b90e6a74ef 100644 --- a/discovery/kubernetes/kubernetes.go +++ b/discovery/kubernetes/kubernetes.go @@ -16,7 +16,7 @@ package kubernetes import ( "context" "fmt" - "io/ioutil" + "os" "reflect" "strings" "sync" @@ -312,7 +312,7 @@ func New(l log.Logger, conf *SDConfig) (*Discovery, error) { } if conf.NamespaceDiscovery.IncludeOwnNamespace { - ownNamespaceContents, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") + ownNamespaceContents, err := os.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/namespace") if err != nil { return nil, fmt.Errorf("could not determine the pod's namespace: %w", err) } diff --git a/discovery/marathon/marathon.go b/discovery/marathon/marathon.go index 5688efedd5..a84313c388 100644 --- a/discovery/marathon/marathon.go +++ b/discovery/marathon/marathon.go @@ -18,10 +18,10 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math/rand" "net" "net/http" + "os" "strconv" "strings" "time" @@ -186,7 +186,7 @@ type authTokenFileRoundTripper struct { // newAuthTokenFileRoundTripper adds the auth token read from the file to a request. func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.RoundTripper, error) { // fail-fast if we can't read the file. - _, err := ioutil.ReadFile(tokenFile) + _, err := os.ReadFile(tokenFile) if err != nil { return nil, errors.Wrapf(err, "unable to read auth token file %s", tokenFile) } @@ -194,7 +194,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http. } func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { - b, err := ioutil.ReadFile(rt.authTokenFile) + b, err := os.ReadFile(rt.authTokenFile) if err != nil { return nil, errors.Wrapf(err, "unable to read auth token file %s", rt.authTokenFile) } @@ -331,7 +331,7 @@ func fetchApps(ctx context.Context, client *http.Client, url string) (*appList, return nil, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -339,7 +339,7 @@ func fetchApps(ctx context.Context, client *http.Client, url string) (*appList, return nil, errors.Errorf("non 2xx status '%v' response during marathon service discovery", resp.StatusCode) } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/discovery/moby/mock_test.go b/discovery/moby/mock_test.go index 3006ca5c28..f6511ed26f 100644 --- a/discovery/moby/mock_test.go +++ b/discovery/moby/mock_test.go @@ -16,9 +16,9 @@ package moby import ( "crypto/sha1" "encoding/base64" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "strings" "testing" @@ -63,7 +63,7 @@ func (m *SDMock) Setup() { // HandleNodesList mocks nodes list. func (m *SDMock) SetupHandlers() { headers := make(map[string]string) - rawHeaders, err := ioutil.ReadFile(filepath.Join("testdata", m.directory, "headers.yml")) + rawHeaders, err := os.ReadFile(filepath.Join("testdata", m.directory, "headers.yml")) require.NoError(m.t, err) yaml.Unmarshal(rawHeaders, &headers) @@ -102,13 +102,13 @@ func (m *SDMock) SetupHandlers() { f += "__" + base64.URLEncoding.EncodeToString(h.Sum(nil))[:10] } } - if response, err := ioutil.ReadFile(filepath.Join("testdata", m.directory, f+".json")); err == nil { + if response, err := os.ReadFile(filepath.Join("testdata", m.directory, f+".json")); err == nil { w.Header().Add("content-type", "application/json") w.WriteHeader(http.StatusOK) w.Write(response) return } - if response, err := ioutil.ReadFile(filepath.Join("testdata", m.directory, f)); err == nil { + if response, err := os.ReadFile(filepath.Join("testdata", m.directory, f)); err == nil { w.WriteHeader(http.StatusOK) w.Write(response) return diff --git a/discovery/puppetdb/puppetdb.go b/discovery/puppetdb/puppetdb.go index c2fbba0231..19ee7a205c 100644 --- a/discovery/puppetdb/puppetdb.go +++ b/discovery/puppetdb/puppetdb.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -187,7 +186,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { return nil, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -199,7 +198,7 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { return nil, errors.Errorf("unsupported content type %s", resp.Header.Get("Content-Type")) } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/discovery/scaleway/instance_test.go b/discovery/scaleway/instance_test.go index f1778d9909..e7a32dd924 100644 --- a/discovery/scaleway/instance_test.go +++ b/discovery/scaleway/instance_test.go @@ -16,9 +16,9 @@ package scaleway import ( "context" "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/prometheus/common/model" @@ -127,7 +127,7 @@ func mockScalewayInstance(w http.ResponseWriter, r *http.Request) { return } w.Header().Set("Content-Type", "application/json") - instance, err := ioutil.ReadFile("testdata/instance.json") + instance, err := os.ReadFile("testdata/instance.json") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/discovery/scaleway/scaleway.go b/discovery/scaleway/scaleway.go index ed3d7f3917..d4ed8a69d3 100644 --- a/discovery/scaleway/scaleway.go +++ b/discovery/scaleway/scaleway.go @@ -15,8 +15,8 @@ package scaleway import ( "context" - "io/ioutil" "net/http" + "os" "strings" "time" @@ -226,7 +226,7 @@ type authTokenFileRoundTripper struct { // newAuthTokenFileRoundTripper adds the auth token read from the file to a request. func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http.RoundTripper, error) { // fail-fast if we can't read the file. - _, err := ioutil.ReadFile(tokenFile) + _, err := os.ReadFile(tokenFile) if err != nil { return nil, errors.Wrapf(err, "unable to read auth token file %s", tokenFile) } @@ -234,7 +234,7 @@ func newAuthTokenFileRoundTripper(tokenFile string, rt http.RoundTripper) (http. } func (rt *authTokenFileRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { - b, err := ioutil.ReadFile(rt.authTokenFile) + b, err := os.ReadFile(rt.authTokenFile) if err != nil { return nil, errors.Wrapf(err, "unable to read auth token file %s", rt.authTokenFile) } diff --git a/discovery/triton/triton.go b/discovery/triton/triton.go index 66efd9bbc1..ef3bcca636 100644 --- a/discovery/triton/triton.go +++ b/discovery/triton/triton.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strings" @@ -207,11 +206,11 @@ func (d *Discovery) refresh(ctx context.Context) ([]*targetgroup.Group, error) { } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrap(err, "an error occurred when reading the response body") } diff --git a/discovery/xds/client.go b/discovery/xds/client.go index 05d1ca40cd..9844c6d7ed 100644 --- a/discovery/xds/client.go +++ b/discovery/xds/client.go @@ -19,7 +19,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "path" @@ -195,7 +194,7 @@ func (rc *HTTPResourceClient) Fetch(ctx context.Context) (*v3.DiscoveryResponse, return nil, err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -208,7 +207,7 @@ func (rc *HTTPResourceClient) Fetch(ctx context.Context) (*v3.DiscoveryResponse, return nil, fmt.Errorf("non 200 status '%d' response during xDS fetch", resp.StatusCode) } - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/discovery/xds/xds_test.go b/discovery/xds/xds_test.go index c0cdd3e7b4..b6c141e283 100644 --- a/discovery/xds/xds_test.go +++ b/discovery/xds/xds_test.go @@ -16,7 +16,6 @@ package xds import ( "context" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" @@ -60,9 +59,9 @@ func createTestHTTPServer(t *testing.T, responder discoveryResponder) *httptest. require.Equal(t, "application/json", r.Header.Get("Content-Type")) require.Equal(t, "application/json", r.Header.Get("Accept")) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) defer func() { - _, _ = io.Copy(ioutil.Discard, r.Body) + _, _ = io.Copy(io.Discard, r.Body) _ = r.Body.Close() }() require.NotEmpty(t, body) diff --git a/documentation/examples/custom-sd/adapter-usage/main.go b/documentation/examples/custom-sd/adapter-usage/main.go index 80a8f1b5ed..a3136f08e8 100644 --- a/documentation/examples/custom-sd/adapter-usage/main.go +++ b/documentation/examples/custom-sd/adapter-usage/main.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "os" @@ -101,11 +100,11 @@ func (d *discovery) parseServiceNodes(resp *http.Response, name string) (*target } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -168,8 +167,8 @@ func (d *discovery) Run(ctx context.Context, ch chan<- []*targetgroup.Group) { continue } - b, err := ioutil.ReadAll(resp.Body) - io.Copy(ioutil.Discard, resp.Body) + b, err := io.ReadAll(resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() if err != nil { level.Error(d.logger).Log("msg", "Error reading services list", "err", err) diff --git a/documentation/examples/custom-sd/adapter/adapter.go b/documentation/examples/custom-sd/adapter/adapter.go index abaad7dc70..b0ed5ab9aa 100644 --- a/documentation/examples/custom-sd/adapter/adapter.go +++ b/documentation/examples/custom-sd/adapter/adapter.go @@ -18,7 +18,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -117,7 +116,7 @@ func (a *Adapter) writeOutput() error { b, _ := json.MarshalIndent(arr, "", " ") dir, _ := filepath.Split(a.output) - tmpfile, err := ioutil.TempFile(dir, "sd-adapter") + tmpfile, err := os.CreateTemp(dir, "sd-adapter") if err != nil { return err } diff --git a/documentation/examples/custom-sd/adapter/adapter_test.go b/documentation/examples/custom-sd/adapter/adapter_test.go index e1223537c0..eaf34c6673 100644 --- a/documentation/examples/custom-sd/adapter/adapter_test.go +++ b/documentation/examples/custom-sd/adapter/adapter_test.go @@ -15,7 +15,6 @@ package adapter import ( "context" - "io/ioutil" "os" "testing" @@ -223,7 +222,7 @@ func TestGenerateTargetGroups(t *testing.T) { // TestWriteOutput checks the adapter can write a file to disk. func TestWriteOutput(t *testing.T) { ctx := context.Background() - tmpfile, err := ioutil.TempFile("", "sd_adapter_test") + tmpfile, err := os.CreateTemp("", "sd_adapter_test") require.NoError(t, err) defer os.Remove(tmpfile.Name()) tmpfile.Close() diff --git a/documentation/examples/remote_storage/remote_storage_adapter/influxdb/client_test.go b/documentation/examples/remote_storage/remote_storage_adapter/influxdb/client_test.go index b657abddea..cb56514e4b 100644 --- a/documentation/examples/remote_storage/remote_storage_adapter/influxdb/client_test.go +++ b/documentation/examples/remote_storage/remote_storage_adapter/influxdb/client_test.go @@ -14,7 +14,7 @@ package influxdb import ( - "io/ioutil" + "io" "math" "net/http" "net/http/httptest" @@ -76,7 +76,7 @@ testmetric,test_label=test_label_value2 value=5.1234 123456789123 func(w http.ResponseWriter, r *http.Request) { require.Equal(t, "POST", r.Method, "Unexpected method.") require.Equal(t, "/write", r.URL.Path, "Unexpected path.") - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) require.NoError(t, err, "Error reading body.") require.Equal(t, expectedBody, string(b), "Unexpected request body.") }, diff --git a/documentation/examples/remote_storage/remote_storage_adapter/main.go b/documentation/examples/remote_storage/remote_storage_adapter/main.go index 6a993a6098..548d0c5d9b 100644 --- a/documentation/examples/remote_storage/remote_storage_adapter/main.go +++ b/documentation/examples/remote_storage/remote_storage_adapter/main.go @@ -16,7 +16,7 @@ package main import ( "fmt" - "io/ioutil" + "io" "net/http" _ "net/http/pprof" "net/url" @@ -234,7 +234,7 @@ func serve(logger log.Logger, addr string, writers []writer, readers []reader) e }) http.HandleFunc("/read", func(w http.ResponseWriter, r *http.Request) { - compressed, err := ioutil.ReadAll(r.Body) + compressed, err := io.ReadAll(r.Body) if err != nil { level.Error(logger).Log("msg", "Read error", "err", err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) diff --git a/documentation/examples/remote_storage/remote_storage_adapter/opentsdb/client.go b/documentation/examples/remote_storage/remote_storage_adapter/opentsdb/client.go index d90ce48095..4942e65dd7 100644 --- a/documentation/examples/remote_storage/remote_storage_adapter/opentsdb/client.go +++ b/documentation/examples/remote_storage/remote_storage_adapter/opentsdb/client.go @@ -18,7 +18,6 @@ import ( "context" "encoding/json" "io" - "io/ioutil" "math" "net/http" "net/url" @@ -116,7 +115,7 @@ func (c *Client) Write(samples model.Samples) error { return err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() @@ -128,7 +127,7 @@ func (c *Client) Write(samples model.Samples) error { // API returns status code 400 on error, encoding error details in the // response content in JSON. - buf, err = ioutil.ReadAll(resp.Body) + buf, err = io.ReadAll(resp.Body) if err != nil { return err } diff --git a/model/rulefmt/rulefmt.go b/model/rulefmt/rulefmt.go index 5332514ed5..46e0080074 100644 --- a/model/rulefmt/rulefmt.go +++ b/model/rulefmt/rulefmt.go @@ -17,7 +17,7 @@ import ( "bytes" "context" "io" - "io/ioutil" + "os" "strings" "time" @@ -304,7 +304,7 @@ func Parse(content []byte) (*RuleGroups, []error) { // ParseFile reads and parses rules from a file. func ParseFile(file string) (*RuleGroups, []error) { - b, err := ioutil.ReadFile(file) + b, err := os.ReadFile(file) if err != nil { return nil, []error{errors.Wrap(err, file)} } diff --git a/model/textparse/promparse_test.go b/model/textparse/promparse_test.go index b9a037de1b..c6762b545d 100644 --- a/model/textparse/promparse_test.go +++ b/model/textparse/promparse_test.go @@ -17,7 +17,6 @@ import ( "bytes" "compress/gzip" "io" - "io/ioutil" "os" "testing" @@ -361,7 +360,7 @@ func BenchmarkParse(b *testing.B) { require.NoError(b, err) defer f.Close() - buf, err := ioutil.ReadAll(f) + buf, err := io.ReadAll(f) require.NoError(b, err) b.Run(parserName+"/no-decode-metric/"+fn, func(b *testing.B) { @@ -501,7 +500,7 @@ func BenchmarkGzip(b *testing.B) { require.NoError(b, err) require.NoError(b, gw.Close()) - gbuf, err := ioutil.ReadAll(&buf) + gbuf, err := io.ReadAll(&buf) require.NoError(b, err) k := b.N / promtestdataSampleCount @@ -516,7 +515,7 @@ func BenchmarkGzip(b *testing.B) { gr, err := gzip.NewReader(bytes.NewReader(gbuf)) require.NoError(b, err) - d, err := ioutil.ReadAll(gr) + d, err := io.ReadAll(gr) require.NoError(b, err) require.NoError(b, gr.Close()) diff --git a/notifier/notifier.go b/notifier/notifier.go index 0fca28c339..88cbbe0aeb 100644 --- a/notifier/notifier.go +++ b/notifier/notifier.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -583,7 +582,7 @@ func (n *Manager) sendOne(ctx context.Context, c *http.Client, url string, b []b return err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() diff --git a/notifier/notifier_test.go b/notifier/notifier_test.go index 4a2747efd3..e28a2609c9 100644 --- a/notifier/notifier_test.go +++ b/notifier/notifier_test.go @@ -18,7 +18,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -126,7 +126,7 @@ func TestHandlerSendAll(t *testing.T) { return } - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) if err != nil { err = errors.Errorf("error reading body: %v", err) w.WriteHeader(http.StatusInternalServerError) @@ -221,7 +221,7 @@ func TestCustomDo(t *testing.T) { h := NewManager(&Options{ Do: func(_ context.Context, client *http.Client, req *http.Request) (*http.Response, error) { received = true - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) require.NoError(t, err) @@ -230,7 +230,7 @@ func TestCustomDo(t *testing.T) { require.Equal(t, testURL, req.URL.String()) return &http.Response{ - Body: ioutil.NopCloser(bytes.NewBuffer(nil)), + Body: io.NopCloser(bytes.NewBuffer(nil)), }, nil }, }, nil) @@ -331,7 +331,7 @@ func TestHandlerQueuing(t *testing.T) { case expected := <-expectedc: var alerts []*Alert - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) if err != nil { panic(err) } diff --git a/plugins/generate.go b/plugins/generate.go index 7054b109b8..32a32d890b 100644 --- a/plugins/generate.go +++ b/plugins/generate.go @@ -18,7 +18,6 @@ package main import ( "fmt" - "io/ioutil" "log" "os" "path" @@ -30,7 +29,7 @@ import ( //go:generate go run generate.go func main() { - data, err := ioutil.ReadFile(filepath.Join("..", "plugins.yml")) + data, err := os.ReadFile(filepath.Join("..", "plugins.yml")) if err != nil { log.Fatal(err) } diff --git a/promql/engine_test.go b/promql/engine_test.go index 6c32b901d7..c34caa4bcf 100644 --- a/promql/engine_test.go +++ b/promql/engine_test.go @@ -16,7 +16,6 @@ package promql import ( "context" "errors" - "io/ioutil" "os" "sort" "testing" @@ -42,7 +41,7 @@ func TestMain(m *testing.M) { func TestQueryConcurrency(t *testing.T) { maxConcurrency := 10 - dir, err := ioutil.TempDir("", "test_concurrency") + dir, err := os.MkdirTemp("", "test_concurrency") require.NoError(t, err) defer os.RemoveAll(dir) queryTracker := NewActiveQueryTracker(dir, maxConcurrency, nil) diff --git a/promql/query_logger_test.go b/promql/query_logger_test.go index 033e012d8c..ad76fb9929 100644 --- a/promql/query_logger_test.go +++ b/promql/query_logger_test.go @@ -15,7 +15,6 @@ package promql import ( "context" - "io/ioutil" "os" "testing" @@ -105,7 +104,7 @@ func TestIndexReuse(t *testing.T) { } func TestMMapFile(t *testing.T) { - file, err := ioutil.TempFile("", "mmapedFile") + file, err := os.CreateTemp("", "mmapedFile") require.NoError(t, err) filename := file.Name() diff --git a/promql/test.go b/promql/test.go index a9408bc4c5..28bdd05886 100644 --- a/promql/test.go +++ b/promql/test.go @@ -16,8 +16,8 @@ package promql import ( "context" "fmt" - "io/ioutil" "math" + "os" "strconv" "strings" "time" @@ -78,7 +78,7 @@ func NewTest(t testutil.T, input string) (*Test, error) { } func newTestFromFile(t testutil.T, filename string) (*Test, error) { - content, err := ioutil.ReadFile(filename) + content, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/rules/manager_test.go b/rules/manager_test.go index 121fee3935..f69bf109a4 100644 --- a/rules/manager_test.go +++ b/rules/manager_test.go @@ -16,7 +16,6 @@ package rules import ( "context" "fmt" - "io/ioutil" "math" "os" "sort" @@ -752,7 +751,7 @@ func TestUpdate(t *testing.T) { rgs, errs := rulefmt.ParseFile("fixtures/rules.yaml") require.Equal(t, 0, len(errs), "file parsing failures") - tmpFile, err := ioutil.TempFile("", "rules.test.*.yaml") + tmpFile, err := os.CreateTemp("", "rules.test.*.yaml") require.NoError(t, err) defer os.Remove(tmpFile.Name()) defer tmpFile.Close() diff --git a/scrape/scrape.go b/scrape/scrape.go index 4b045faca9..20633a1c51 100644 --- a/scrape/scrape.go +++ b/scrape/scrape.go @@ -20,7 +20,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "math" "net/http" "reflect" @@ -773,7 +772,7 @@ func (s *targetScraper) scrape(ctx context.Context, w io.Writer) (string, error) return "", err } defer func() { - io.Copy(ioutil.Discard, resp.Body) + io.Copy(io.Discard, resp.Body) resp.Body.Close() }() diff --git a/scrape/scrape_test.go b/scrape/scrape_test.go index 80cbf344a4..c771ee1c84 100644 --- a/scrape/scrape_test.go +++ b/scrape/scrape_test.go @@ -19,7 +19,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "math" "net/http" "net/http/httptest" @@ -2129,7 +2128,7 @@ func TestTargetScrapeScrapeCancel(t *testing.T) { }() go func() { - _, err := ts.scrape(ctx, ioutil.Discard) + _, err := ts.scrape(ctx, io.Discard) if err == nil { errc <- errors.New("Expected error but got nil") } else if ctx.Err() != context.Canceled { @@ -2173,7 +2172,7 @@ func TestTargetScrapeScrapeNotFound(t *testing.T) { client: http.DefaultClient, } - _, err = ts.scrape(context.Background(), ioutil.Discard) + _, err = ts.scrape(context.Background(), io.Discard) require.Contains(t, err.Error(), "404", "Expected \"404 NotFound\" error but got: %s", err) } diff --git a/scrape/target_test.go b/scrape/target_test.go index 0e02dd8f97..f7733a5986 100644 --- a/scrape/target_test.go +++ b/scrape/target_test.go @@ -17,10 +17,10 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" "time" @@ -337,7 +337,7 @@ func TestNewHTTPWithBadServerName(t *testing.T) { func newTLSConfig(certName string, t *testing.T) *tls.Config { tlsConfig := &tls.Config{} caCertPool := x509.NewCertPool() - caCert, err := ioutil.ReadFile(caCertPath) + caCert, err := os.ReadFile(caCertPath) if err != nil { t.Fatalf("Couldn't set up TLS server: %v", err) } diff --git a/scripts/errcheck_excludes.txt b/scripts/errcheck_excludes.txt index 92974d7a5f..8c77ca148d 100644 --- a/scripts/errcheck_excludes.txt +++ b/scripts/errcheck_excludes.txt @@ -1,4 +1,4 @@ -// Don't flag lines such as "io.Copy(ioutil.Discard, resp.Body)". +// Don't flag lines such as "io.Copy(io.Discard, resp.Body)". io.Copy // The next two are used in HTTP handlers, any error is handled by the server itself. io.WriteString diff --git a/storage/remote/client.go b/storage/remote/client.go index 622d5e91a6..7120822d95 100644 --- a/storage/remote/client.go +++ b/storage/remote/client.go @@ -19,7 +19,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "strconv" "strings" @@ -213,7 +212,7 @@ func (c *Client) Store(ctx context.Context, req []byte) error { return RecoverableError{err, defaultBackoff} } defer func() { - io.Copy(ioutil.Discard, httpResp.Body) + io.Copy(io.Discard, httpResp.Body) httpResp.Body.Close() }() @@ -300,13 +299,13 @@ func (c *Client) Read(ctx context.Context, query *prompb.Query) (*prompb.QueryRe return nil, errors.Wrap(err, "error sending request") } defer func() { - io.Copy(ioutil.Discard, httpResp.Body) + io.Copy(io.Discard, httpResp.Body) httpResp.Body.Close() }() c.readQueriesDuration.Observe(time.Since(start).Seconds()) c.readQueriesTotal.WithLabelValues(strconv.Itoa(httpResp.StatusCode)).Inc() - compressed, err = ioutil.ReadAll(httpResp.Body) + compressed, err = io.ReadAll(httpResp.Body) if err != nil { return nil, errors.Wrap(err, fmt.Sprintf("error reading response. HTTP status code: %s", httpResp.Status)) } diff --git a/storage/remote/codec.go b/storage/remote/codec.go index fb4d777a34..f56fc6760f 100644 --- a/storage/remote/codec.go +++ b/storage/remote/codec.go @@ -16,7 +16,6 @@ package remote import ( "fmt" "io" - "io/ioutil" "net/http" "sort" "strings" @@ -52,7 +51,7 @@ func (e HTTPError) Status() int { // DecodeReadRequest reads a remote.Request from a http.Request. func DecodeReadRequest(r *http.Request) (*prompb.ReadRequest, error) { - compressed, err := ioutil.ReadAll(io.LimitReader(r.Body, decodeReadLimit)) + compressed, err := io.ReadAll(io.LimitReader(r.Body, decodeReadLimit)) if err != nil { return nil, err } @@ -524,7 +523,7 @@ func metricTypeToMetricTypeProto(t textparse.MetricType) prompb.MetricMetadata_M // DecodeWriteRequest from an io.Reader into a prompb.WriteRequest, handling // snappy decompression. func DecodeWriteRequest(r io.Reader) (*prompb.WriteRequest, error) { - compressed, err := ioutil.ReadAll(r) + compressed, err := io.ReadAll(r) if err != nil { return nil, err } diff --git a/storage/remote/queue_manager_test.go b/storage/remote/queue_manager_test.go index ff3f1aaf20..cb5cee9a44 100644 --- a/storage/remote/queue_manager_test.go +++ b/storage/remote/queue_manager_test.go @@ -16,7 +16,6 @@ package remote import ( "context" "fmt" - "io/ioutil" "math" "net/url" "os" @@ -824,7 +823,7 @@ func BenchmarkStartup(b *testing.B) { // Find the second largest segment; we will replay up to this. // (Second largest as WALWatcher will start tailing the largest). - dirents, err := ioutil.ReadDir(dir) + dirents, err := os.ReadDir(dir) require.NoError(b, err) var segments []int diff --git a/storage/remote/read_handler_test.go b/storage/remote/read_handler_test.go index 86edbe0b97..550ac6f6b2 100644 --- a/storage/remote/read_handler_test.go +++ b/storage/remote/read_handler_test.go @@ -16,7 +16,6 @@ package remote import ( "bytes" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" @@ -84,7 +83,7 @@ func TestSampledReadEndpoint(t *testing.T) { require.Equal(t, "snappy", recorder.Result().Header.Get("Content-Encoding")) // Decode the response. - compressed, err = ioutil.ReadAll(recorder.Result().Body) + compressed, err = io.ReadAll(recorder.Result().Body) require.NoError(t, err) uncompressed, err := snappy.Decode(nil, compressed) diff --git a/storage/remote/write_handler_test.go b/storage/remote/write_handler_test.go index 5eb17d3b87..459910992f 100644 --- a/storage/remote/write_handler_test.go +++ b/storage/remote/write_handler_test.go @@ -17,7 +17,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -128,7 +128,7 @@ func TestCommitErr(t *testing.T) { handler.ServeHTTP(recorder, req) resp := recorder.Result() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusInternalServerError, resp.StatusCode) require.Equal(t, "commit error\n", string(body)) diff --git a/tsdb/block.go b/tsdb/block.go index e4db21f85e..38ed063536 100644 --- a/tsdb/block.go +++ b/tsdb/block.go @@ -17,7 +17,6 @@ package tsdb import ( "encoding/json" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -201,7 +200,7 @@ const ( func chunkDir(dir string) string { return filepath.Join(dir, "chunks") } func readMetaFile(dir string) (*BlockMeta, int64, error) { - b, err := ioutil.ReadFile(filepath.Join(dir, metaFilename)) + b, err := os.ReadFile(filepath.Join(dir, metaFilename)) if err != nil { return nil, 0, err } @@ -636,7 +635,7 @@ func (pb *Block) Snapshot(dir string) error { // Hardlink the chunks curChunkDir := chunkDir(pb.dir) - files, err := ioutil.ReadDir(curChunkDir) + files, err := os.ReadDir(curChunkDir) if err != nil { return errors.Wrap(err, "ReadDir the current chunk dir") } diff --git a/tsdb/blockwriter.go b/tsdb/blockwriter.go index 064cd01c7e..09b355368d 100644 --- a/tsdb/blockwriter.go +++ b/tsdb/blockwriter.go @@ -15,7 +15,6 @@ package tsdb import ( "context" - "io/ioutil" "math" "os" @@ -64,7 +63,7 @@ func NewBlockWriter(logger log.Logger, dir string, blockSize int64) (*BlockWrite // initHead creates and initialises a new TSDB head. func (w *BlockWriter) initHead() error { - chunkDir, err := ioutil.TempDir(os.TempDir(), "head") + chunkDir, err := os.MkdirTemp(os.TempDir(), "head") if err != nil { return errors.Wrap(err, "create temp dir") } diff --git a/tsdb/chunks/chunks.go b/tsdb/chunks/chunks.go index 2f565fcb17..4f8f405876 100644 --- a/tsdb/chunks/chunks.go +++ b/tsdb/chunks/chunks.go @@ -21,7 +21,6 @@ import ( "hash" "hash/crc32" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -591,7 +590,7 @@ func (s *Reader) Chunk(ref ChunkRef) (chunkenc.Chunk, error) { } func nextSequenceFile(dir string) (string, int, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return "", 0, err } @@ -617,7 +616,7 @@ func segmentFile(baseDir string, index int) string { } func sequenceFiles(dir string) ([]string, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } diff --git a/tsdb/chunks/head_chunks.go b/tsdb/chunks/head_chunks.go index 307ecfc96d..c4b784bea4 100644 --- a/tsdb/chunks/head_chunks.go +++ b/tsdb/chunks/head_chunks.go @@ -19,7 +19,6 @@ import ( "encoding/binary" "hash" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -330,7 +329,7 @@ func (cdm *ChunkDiskMapper) openMMapFiles() (returnErr error) { } func listChunkFiles(dir string) (map[int]string, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } diff --git a/tsdb/chunks/head_chunks_test.go b/tsdb/chunks/head_chunks_test.go index 57c9c34017..cc4fc2c09f 100644 --- a/tsdb/chunks/head_chunks_test.go +++ b/tsdb/chunks/head_chunks_test.go @@ -16,7 +16,6 @@ package chunks import ( "encoding/binary" "errors" - "io/ioutil" "math/rand" "os" "strconv" @@ -124,7 +123,7 @@ func TestChunkDiskMapper_WriteChunk_Chunk_IterateChunks(t *testing.T) { require.Equal(t, 3, len(hrw.mmappedChunkFiles), "expected 3 mmapped files, got %d", len(hrw.mmappedChunkFiles)) require.Equal(t, len(hrw.mmappedChunkFiles), len(hrw.closers)) - actualBytes, err := ioutil.ReadFile(firstFileName) + actualBytes, err := os.ReadFile(firstFileName) require.NoError(t, err) // Check header of the segment file. @@ -202,7 +201,7 @@ func TestChunkDiskMapper_Truncate(t *testing.T) { verifyFiles := func(remainingFiles []int) { t.Helper() - files, err := ioutil.ReadDir(hrw.dir.Name()) + files, err := os.ReadDir(hrw.dir.Name()) require.NoError(t, err) require.Equal(t, len(remainingFiles), len(files), "files on disk") require.Equal(t, len(remainingFiles), len(hrw.mmappedChunkFiles), "hrw.mmappedChunkFiles") @@ -320,7 +319,7 @@ func TestChunkDiskMapper_Truncate_PreservesFileSequence(t *testing.T) { verifyFiles := func(remainingFiles []int) { t.Helper() - files, err := ioutil.ReadDir(hrw.dir.Name()) + files, err := os.ReadDir(hrw.dir.Name()) require.NoError(t, err) require.Equal(t, len(remainingFiles), len(files), "files on disk") require.Equal(t, len(remainingFiles), len(hrw.mmappedChunkFiles), "hrw.mmappedChunkFiles") @@ -454,7 +453,7 @@ func TestHeadReadWriter_ReadRepairOnEmptyLastFile(t *testing.T) { } // Removed even from disk. - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) require.Equal(t, 3, len(files)) for _, fi := range files { diff --git a/tsdb/db.go b/tsdb/db.go index d65c0246bf..ab0822d73b 100644 --- a/tsdb/db.go +++ b/tsdb/db.go @@ -18,7 +18,7 @@ import ( "context" "fmt" "io" - "io/ioutil" + "io/fs" "math" "os" "path/filepath" @@ -761,20 +761,20 @@ func open(dir string, l log.Logger, r prometheus.Registerer, opts *Options, rngs } func removeBestEffortTmpDirs(l log.Logger, dir string) error { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if os.IsNotExist(err) { return nil } if err != nil { return err } - for _, fi := range files { - if isTmpDir(fi) { - if err := os.RemoveAll(filepath.Join(dir, fi.Name())); err != nil { - level.Error(l).Log("msg", "failed to delete tmp block dir", "dir", filepath.Join(dir, fi.Name()), "err", err) + for _, f := range files { + if isTmpDir(f) { + if err := os.RemoveAll(filepath.Join(dir, f.Name())); err != nil { + level.Error(l).Log("msg", "failed to delete tmp block dir", "dir", filepath.Join(dir, f.Name()), "err", err) continue } - level.Info(l).Log("msg", "Found and deleted tmp block dir", "dir", filepath.Join(dir, fi.Name())) + level.Info(l).Log("msg", "Found and deleted tmp block dir", "dir", filepath.Join(dir, f.Name())) } } return nil @@ -1717,7 +1717,7 @@ func (db *DB) CleanTombstones() (err error) { return nil } -func isBlockDir(fi os.FileInfo) bool { +func isBlockDir(fi fs.DirEntry) bool { if !fi.IsDir() { return false } @@ -1726,7 +1726,7 @@ func isBlockDir(fi os.FileInfo) bool { } // isTmpDir returns true if the given file-info contains a block ULID or checkpoint prefix and a tmp extension. -func isTmpDir(fi os.FileInfo) bool { +func isTmpDir(fi fs.DirEntry) bool { if !fi.IsDir() { return false } @@ -1745,22 +1745,22 @@ func isTmpDir(fi os.FileInfo) bool { } func blockDirs(dir string) ([]string, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } var dirs []string - for _, fi := range files { - if isBlockDir(fi) { - dirs = append(dirs, filepath.Join(dir, fi.Name())) + for _, f := range files { + if isBlockDir(f) { + dirs = append(dirs, filepath.Join(dir, f.Name())) } } return dirs, nil } func sequenceFiles(dir string) ([]string, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } @@ -1776,7 +1776,7 @@ func sequenceFiles(dir string) ([]string, error) { } func nextSequenceFile(dir string) (string, int, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return "", 0, err } diff --git a/tsdb/db_test.go b/tsdb/db_test.go index ea3ae4d678..655cf9dacd 100644 --- a/tsdb/db_test.go +++ b/tsdb/db_test.go @@ -20,7 +20,6 @@ import ( "flag" "fmt" "hash/crc32" - "io/ioutil" "math" "math/rand" "os" @@ -225,7 +224,7 @@ func TestNoPanicAfterWALCorruption(t *testing.T) { // it is not garbage collected. // The repair deletes all WAL records after the corrupted record and these are read from the mmaped chunk. { - walFiles, err := ioutil.ReadDir(path.Join(db.Dir(), "wal")) + walFiles, err := os.ReadDir(path.Join(db.Dir(), "wal")) require.NoError(t, err) f, err := os.OpenFile(path.Join(db.Dir(), "wal", walFiles[0].Name()), os.O_RDWR, 0o666) require.NoError(t, err) @@ -926,12 +925,14 @@ func TestWALSegmentSizeOptions(t *testing.T) { tests := map[int]func(dbdir string, segmentSize int){ // Default Wal Size. 0: func(dbDir string, segmentSize int) { - filesAndDir, err := ioutil.ReadDir(filepath.Join(dbDir, "wal")) + filesAndDir, err := os.ReadDir(filepath.Join(dbDir, "wal")) require.NoError(t, err) files := []os.FileInfo{} for _, f := range filesAndDir { if !f.IsDir() { - files = append(files, f) + fi, err := f.Info() + require.NoError(t, err) + files = append(files, fi) } } // All the full segment files (all but the last) should match the segment size option. @@ -943,12 +944,14 @@ func TestWALSegmentSizeOptions(t *testing.T) { }, // Custom Wal Size. 2 * 32 * 1024: func(dbDir string, segmentSize int) { - filesAndDir, err := ioutil.ReadDir(filepath.Join(dbDir, "wal")) + filesAndDir, err := os.ReadDir(filepath.Join(dbDir, "wal")) require.NoError(t, err) files := []os.FileInfo{} for _, f := range filesAndDir { if !f.IsDir() { - files = append(files, f) + fi, err := f.Info() + require.NoError(t, err) + files = append(files, fi) } } require.Greater(t, len(files), 1, "current WALSegmentSize should result in more than a single WAL file.") @@ -2706,7 +2709,7 @@ func TestChunkWriter_ReadAfterWrite(t *testing.T) { } require.NoError(t, chunkw.Close()) - files, err := ioutil.ReadDir(tempDir) + files, err := os.ReadDir(tempDir) require.NoError(t, err) require.Equal(t, test.expSegmentsCount, len(files), "expected segments count mismatch") @@ -2726,7 +2729,9 @@ func TestChunkWriter_ReadAfterWrite(t *testing.T) { sizeExp += test.expSegmentsCount * chunks.SegmentHeaderSize // The segment header bytes. for i, f := range files { - size := int(f.Size()) + fi, err := f.Info() + require.NoError(t, err) + size := int(fi.Size()) // Verify that the segment is the same or smaller than the expected size. require.GreaterOrEqual(t, chunks.SegmentHeaderSize+test.expSegmentSizes[i], size, "Segment:%v should NOT be bigger than:%v actual:%v", i, chunks.SegmentHeaderSize+test.expSegmentSizes[i], size) @@ -2877,7 +2882,7 @@ func TestCompactHead(t *testing.T) { } func deleteNonBlocks(dbDir string) error { - dirs, err := ioutil.ReadDir(dbDir) + dirs, err := os.ReadDir(dbDir) if err != nil { return err } @@ -2888,7 +2893,7 @@ func deleteNonBlocks(dbDir string) error { } } } - dirs, err = ioutil.ReadDir(dbDir) + dirs, err = os.ReadDir(dbDir) if err != nil { return err } @@ -2995,7 +3000,7 @@ func TestOpen_VariousBlockStates(t *testing.T) { require.Equal(t, len(expectedLoadedDirs), loaded) require.NoError(t, db.Close()) - files, err := ioutil.ReadDir(tmpDir) + files, err := os.ReadDir(tmpDir) require.NoError(t, err) var ignored int diff --git a/tsdb/example_test.go b/tsdb/example_test.go index 1947a48a55..edb0e3c392 100644 --- a/tsdb/example_test.go +++ b/tsdb/example_test.go @@ -16,7 +16,6 @@ package tsdb import ( "context" "fmt" - "io/ioutil" "math" "os" "time" @@ -27,7 +26,7 @@ import ( func Example() { // Create a random dir to work in. Open() doesn't require a pre-existing dir, but // we want to make sure not to make a mess where we shouldn't. - dir, err := ioutil.TempDir("", "tsdb-test") + dir, err := os.MkdirTemp("", "tsdb-test") noErr(err) // Open a TSDB for reading and/or writing. diff --git a/tsdb/fileutil/fileutil.go b/tsdb/fileutil/fileutil.go index 8ab8ce3dd1..5e479f48b9 100644 --- a/tsdb/fileutil/fileutil.go +++ b/tsdb/fileutil/fileutil.go @@ -18,7 +18,6 @@ package fileutil import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -60,12 +59,12 @@ func CopyDirs(src, dest string) error { } func copyFile(src, dest string) error { - data, err := ioutil.ReadFile(src) + data, err := os.ReadFile(src) if err != nil { return err } - err = ioutil.WriteFile(dest, data, 0o666) + err = os.WriteFile(dest, data, 0o666) if err != nil { return err } diff --git a/tsdb/head_test.go b/tsdb/head_test.go index 7cd072a192..7a2c439994 100644 --- a/tsdb/head_test.go +++ b/tsdb/head_test.go @@ -17,7 +17,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "math" "math/rand" "os" @@ -1679,7 +1678,7 @@ func TestHeadReadWriterRepair(t *testing.T) { // Verify that there are 6 segment files. // It should only be 6 because the last call to .CutNewFile() won't // take effect without another chunk being written. - files, err := ioutil.ReadDir(mmappedChunksDir(dir)) + files, err := os.ReadDir(mmappedChunksDir(dir)) require.NoError(t, err) require.Equal(t, 6, len(files)) @@ -1705,7 +1704,7 @@ func TestHeadReadWriterRepair(t *testing.T) { // Verify that there are 3 segment files after the repair. // The segments from the corrupt segment should be removed. { - files, err := ioutil.ReadDir(mmappedChunksDir(dir)) + files, err := os.ReadDir(mmappedChunksDir(dir)) require.NoError(t, err) require.Equal(t, 3, len(files)) } @@ -2965,7 +2964,7 @@ func TestChunkSnapshot(t *testing.T) { closeHeadAndCheckSnapshot() // Verify that there is only 1 snapshot. - files, err := ioutil.ReadDir(head.opts.ChunkDirRoot) + files, err := os.ReadDir(head.opts.ChunkDirRoot) require.NoError(t, err) snapshots := 0 for i := len(files) - 1; i >= 0; i-- { @@ -3028,7 +3027,7 @@ func TestSnapshotError(t *testing.T) { // Corrupt the snapshot. snapDir, _, _, err := LastChunkSnapshot(head.opts.ChunkDirRoot) require.NoError(t, err) - files, err := ioutil.ReadDir(snapDir) + files, err := os.ReadDir(snapDir) require.NoError(t, err) f, err := os.OpenFile(path.Join(snapDir, files[0].Name()), os.O_RDWR, 0) require.NoError(t, err) @@ -3093,7 +3092,7 @@ func TestChunkSnapshotReplayBug(t *testing.T) { cpdir := filepath.Join(dir, snapshotName) require.NoError(t, os.MkdirAll(cpdir, 0o777)) - err = ioutil.WriteFile(filepath.Join(cpdir, "00000000"), []byte{1, 5, 3, 5, 6, 7, 4, 2, 2}, 0o777) + err = os.WriteFile(filepath.Join(cpdir, "00000000"), []byte{1, 5, 3, 5, 6, 7, 4, 2, 2}, 0o777) require.NoError(t, err) opts := DefaultHeadOptions() @@ -3264,7 +3263,7 @@ func TestReplayAfterMmapReplayError(t *testing.T) { } } - files, err := ioutil.ReadDir(filepath.Join(dir, "chunks_head")) + files, err := os.ReadDir(filepath.Join(dir, "chunks_head")) require.Equal(t, 5, len(files)) // Corrupt a m-map file. @@ -3278,7 +3277,7 @@ func TestReplayAfterMmapReplayError(t *testing.T) { openHead() // There should be less m-map files due to corruption. - files, err = ioutil.ReadDir(filepath.Join(dir, "chunks_head")) + files, err = os.ReadDir(filepath.Join(dir, "chunks_head")) require.Equal(t, 2, len(files)) // Querying should not panic. diff --git a/tsdb/head_wal.go b/tsdb/head_wal.go index 02f4aeadb0..6f2fd6eaa4 100644 --- a/tsdb/head_wal.go +++ b/tsdb/head_wal.go @@ -15,7 +15,6 @@ package tsdb import ( "fmt" - "io/ioutil" "math" "os" "path/filepath" @@ -760,7 +759,7 @@ type ChunkSnapshotStats struct { // LastChunkSnapshot returns the directory name and index of the most recent chunk snapshot. // If dir does not contain any chunk snapshots, ErrNotFound is returned. func LastChunkSnapshot(dir string) (string, int, int, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return "", 0, 0, err } @@ -805,7 +804,7 @@ func LastChunkSnapshot(dir string) (string, int, int, error) { // DeleteChunkSnapshots deletes all chunk snapshots in a directory below a given index. func DeleteChunkSnapshots(dir string, maxIndex, maxOffset int) error { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return err } diff --git a/tsdb/index/index.go b/tsdb/index/index.go index 0d2981385d..fc1faf5eef 100644 --- a/tsdb/index/index.go +++ b/tsdb/index/index.go @@ -22,7 +22,6 @@ import ( "hash" "hash/crc32" "io" - "io/ioutil" "math" "os" "path/filepath" @@ -1109,7 +1108,7 @@ func (b realByteSlice) Sub(start, end int) ByteSlice { // NewReader returns a new index reader on the given byte slice. It automatically // handles different format versions. func NewReader(b ByteSlice) (*Reader, error) { - return newReader(b, ioutil.NopCloser(nil)) + return newReader(b, io.NopCloser(nil)) } // NewFileReader returns a new index reader against the given index file. diff --git a/tsdb/index/index_test.go b/tsdb/index/index_test.go index 811d859bfd..7d0f49010c 100644 --- a/tsdb/index/index_test.go +++ b/tsdb/index/index_test.go @@ -17,7 +17,6 @@ import ( "context" "fmt" "hash/crc32" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -488,7 +487,7 @@ func TestNewFileReaderErrorNoOpenFiles(t *testing.T) { dir := testutil.NewTemporaryDirectory("block", t) idxName := filepath.Join(dir.Path(), "index") - err := ioutil.WriteFile(idxName, []byte("corrupted contents"), 0o666) + err := os.WriteFile(idxName, []byte("corrupted contents"), 0o666) require.NoError(t, err) _, err = NewFileReader(idxName) diff --git a/tsdb/repair.go b/tsdb/repair.go index 8d60cb3817..0c2e08791c 100644 --- a/tsdb/repair.go +++ b/tsdb/repair.go @@ -16,7 +16,6 @@ package tsdb import ( "encoding/json" "io" - "io/ioutil" "os" "path/filepath" @@ -115,7 +114,7 @@ func repairBadIndexVersion(logger log.Logger, dir string) error { } func readBogusMetaFile(dir string) (*BlockMeta, error) { - b, err := ioutil.ReadFile(filepath.Join(dir, metaFilename)) + b, err := os.ReadFile(filepath.Join(dir, metaFilename)) if err != nil { return nil, err } diff --git a/tsdb/tombstones/tombstones.go b/tsdb/tombstones/tombstones.go index 621e104714..f7e2a2a1e7 100644 --- a/tsdb/tombstones/tombstones.go +++ b/tsdb/tombstones/tombstones.go @@ -18,7 +18,6 @@ import ( "fmt" "hash" "hash/crc32" - "io/ioutil" "os" "path/filepath" "sort" @@ -190,7 +189,7 @@ type Stone struct { } func ReadTombstones(dir string) (Reader, int64, error) { - b, err := ioutil.ReadFile(filepath.Join(dir, TombstonesFilename)) + b, err := os.ReadFile(filepath.Join(dir, TombstonesFilename)) if os.IsNotExist(err) { return NewMemTombstones(), 0, nil } else if err != nil { diff --git a/tsdb/tsdbutil/dir_locker_testutil.go b/tsdb/tsdbutil/dir_locker_testutil.go index cbb21e254f..a4cf5abd68 100644 --- a/tsdb/tsdbutil/dir_locker_testutil.go +++ b/tsdb/tsdbutil/dir_locker_testutil.go @@ -15,7 +15,6 @@ package tsdbutil import ( "fmt" - "io/ioutil" "os" "testing" @@ -61,7 +60,7 @@ func TestDirLockerUsage(t *testing.T, open func(t *testing.T, data string, creat for _, c := range cases { t.Run(fmt.Sprintf("%+v", c), func(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "test") + tmpdir, err := os.MkdirTemp("", "test") require.NoError(t, err) t.Cleanup(func() { require.NoError(t, os.RemoveAll(tmpdir)) @@ -71,7 +70,7 @@ func TestDirLockerUsage(t *testing.T, open func(t *testing.T, data string, creat if c.fileAlreadyExists { tmpLocker, err := NewDirLocker(tmpdir, "tsdb", log.NewNopLogger(), nil) require.NoError(t, err) - err = ioutil.WriteFile(tmpLocker.path, []byte{}, 0o644) + err = os.WriteFile(tmpLocker.path, []byte{}, 0o644) require.NoError(t, err) } diff --git a/tsdb/wal/checkpoint.go b/tsdb/wal/checkpoint.go index 9064beed06..af4bd940c7 100644 --- a/tsdb/wal/checkpoint.go +++ b/tsdb/wal/checkpoint.go @@ -17,7 +17,6 @@ package wal import ( "fmt" "io" - "io/ioutil" "math" "os" "path/filepath" @@ -300,7 +299,7 @@ type checkpointRef struct { } func listCheckpoints(dir string) (refs []checkpointRef, err error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } diff --git a/tsdb/wal/checkpoint_test.go b/tsdb/wal/checkpoint_test.go index 3f8ca25e0f..63f3558afa 100644 --- a/tsdb/wal/checkpoint_test.go +++ b/tsdb/wal/checkpoint_test.go @@ -16,7 +16,6 @@ package wal import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -86,7 +85,7 @@ func TestDeleteCheckpoints(t *testing.T) { require.NoError(t, DeleteCheckpoints(dir, 2)) - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) fns := []string{} for _, f := range files { @@ -100,7 +99,7 @@ func TestDeleteCheckpoints(t *testing.T) { require.NoError(t, DeleteCheckpoints(dir, 100000000)) - files, err = ioutil.ReadDir(dir) + files, err = os.ReadDir(dir) require.NoError(t, err) fns = []string{} for _, f := range files { @@ -183,7 +182,7 @@ func TestCheckpoint(t *testing.T) { require.NoError(t, DeleteCheckpoints(w.Dir(), 106)) // Only the new checkpoint should be left. - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) require.Equal(t, 1, len(files)) require.Equal(t, "checkpoint.00000106", files[0].Name()) diff --git a/tsdb/wal/reader_test.go b/tsdb/wal/reader_test.go index a6516367d7..191e54636b 100644 --- a/tsdb/wal/reader_test.go +++ b/tsdb/wal/reader_test.go @@ -20,7 +20,6 @@ import ( "fmt" "hash/crc32" "io" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -203,7 +202,7 @@ func TestReader_Live(t *testing.T) { for i := range testReaderCases { t.Run(strconv.Itoa(i), func(t *testing.T) { - writeFd, err := ioutil.TempFile("", "TestReader_Live") + writeFd, err := os.CreateTemp("", "TestReader_Live") require.NoError(t, err) defer os.Remove(writeFd.Name()) diff --git a/tsdb/wal/wal.go b/tsdb/wal/wal.go index 3bc2894d32..ace6a99566 100644 --- a/tsdb/wal/wal.go +++ b/tsdb/wal/wal.go @@ -20,7 +20,6 @@ import ( "fmt" "hash/crc32" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -802,7 +801,7 @@ type segmentRef struct { } func listSegments(dir string) (refs []segmentRef, err error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } diff --git a/tsdb/wal/watcher.go b/tsdb/wal/watcher.go index cdd20626a8..cde9cfa5ff 100644 --- a/tsdb/wal/watcher.go +++ b/tsdb/wal/watcher.go @@ -16,7 +16,6 @@ package wal import ( "fmt" "io" - "io/ioutil" "math" "os" "path" @@ -305,7 +304,7 @@ func (w *Watcher) firstAndLast() (int, int, error) { // Copied from tsdb/wal/wal.go so we do not have to open a WAL. // Plan is to move WAL watcher to TSDB and dedupe these implementations. func (w *Watcher) segments(dir string) ([]int, error) { - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, err } diff --git a/tsdb/wal_test.go b/tsdb/wal_test.go index b4ab54d0c0..325e65a92d 100644 --- a/tsdb/wal_test.go +++ b/tsdb/wal_test.go @@ -19,7 +19,6 @@ package tsdb import ( "encoding/binary" "io" - "io/ioutil" "math/rand" "os" "path" @@ -294,7 +293,7 @@ func TestWALRestoreCorrupted_invalidSegment(t *testing.T) { require.NoError(t, err) defer func(wal *SegmentWAL) { require.NoError(t, wal.Close()) }(wal) - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) require.NoError(t, err) fns := []string{} for _, f := range files { diff --git a/util/httputil/compression_test.go b/util/httputil/compression_test.go index f490f7e301..8512797613 100644 --- a/util/httputil/compression_test.go +++ b/util/httputil/compression_test.go @@ -17,7 +17,7 @@ import ( "bytes" "compress/gzip" "compress/zlib" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -64,7 +64,7 @@ func TestCompressionHandler_PlainText(t *testing.T) { resp, err := client.Get(server.URL + "/foo_endpoint") require.NoError(t, err, "client get failed with unexpected error") defer resp.Body.Close() - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err, "unexpected error while creating the response body reader") expected := "Hello World!" diff --git a/util/logging/file_test.go b/util/logging/file_test.go index 537a2a713b..0e760a4848 100644 --- a/util/logging/file_test.go +++ b/util/logging/file_test.go @@ -14,7 +14,6 @@ package logging import ( - "io/ioutil" "os" "strings" "testing" @@ -24,7 +23,7 @@ import ( ) func TestJSONFileLogger_basic(t *testing.T) { - f, err := ioutil.TempFile("", "logging") + f, err := os.CreateTemp("", "logging") require.NoError(t, err) defer func() { require.NoError(t, f.Close()) @@ -53,7 +52,7 @@ func TestJSONFileLogger_basic(t *testing.T) { } func TestJSONFileLogger_parallel(t *testing.T) { - f, err := ioutil.TempFile("", "logging") + f, err := os.CreateTemp("", "logging") require.NoError(t, err) defer func() { require.NoError(t, f.Close()) diff --git a/util/teststorage/storage.go b/util/teststorage/storage.go index 9f9cb4ceb7..ff9b33bbdd 100644 --- a/util/teststorage/storage.go +++ b/util/teststorage/storage.go @@ -14,7 +14,6 @@ package teststorage import ( - "io/ioutil" "os" "time" @@ -31,7 +30,7 @@ import ( // New returns a new TestStorage for testing purposes // that removes all associated files on closing. func New(t testutil.T) *TestStorage { - dir, err := ioutil.TempDir("", "test_storage") + dir, err := os.MkdirTemp("", "test_storage") require.NoError(t, err, "unexpected error while opening test directory") // Tests just load data for a series sequentially. Thus we diff --git a/util/testutil/directory.go b/util/testutil/directory.go index 70cf042273..71ed74ba55 100644 --- a/util/testutil/directory.go +++ b/util/testutil/directory.go @@ -16,7 +16,6 @@ package testutil import ( "crypto/sha256" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -120,7 +119,7 @@ func NewTemporaryDirectory(name string, t T) (handler TemporaryDirectory) { err error ) - directory, err = ioutil.TempDir(defaultDirectory, name) + directory, err = os.MkdirTemp(defaultDirectory, name) require.NoError(t, err) handler = temporaryDirectory{ diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go index 55155f8bcf..1c999ba33c 100644 --- a/web/api/v1/api_test.go +++ b/web/api/v1/api_test.go @@ -17,7 +17,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "math" "net/http" "net/http/httptest" @@ -2288,7 +2288,7 @@ func (f *fakeDB) CleanTombstones() error { return func (f *fakeDB) Delete(mint, maxt int64, ms ...*labels.Matcher) error { return f.err } func (f *fakeDB) Snapshot(dir string, withHead bool) error { return f.err } func (f *fakeDB) Stats(statsByLabelName string) (_ *tsdb.Stats, retErr error) { - dbDir, err := ioutil.TempDir("", "tsdb-api-ready") + dbDir, err := os.MkdirTemp("", "tsdb-api-ready") if err != nil { return nil, err } @@ -2501,7 +2501,7 @@ func TestRespondSuccess(t *testing.T) { if err != nil { t.Fatalf("Error on test request: %s", err) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { t.Fatalf("Error reading response body: %s", err) @@ -2537,7 +2537,7 @@ func TestRespondError(t *testing.T) { if err != nil { t.Fatalf("Error on test request: %s", err) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { t.Fatalf("Error reading response body: %s", err) @@ -2893,7 +2893,7 @@ func TestRespond(t *testing.T) { if err != nil { t.Fatalf("Error on test request: %s", err) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { t.Fatalf("Error reading response body: %s", err) diff --git a/web/web.go b/web/web.go index 0574549e5a..132582872f 100644 --- a/web/web.go +++ b/web/web.go @@ -19,7 +19,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" stdlog "log" "math" "net" @@ -386,7 +385,7 @@ func New(logger log.Logger, o *Options) *Handler { return } defer func() { _ = f.Close() }() - idx, err := ioutil.ReadAll(f) + idx, err := io.ReadAll(f) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error reading React index.html: %v", err) @@ -615,7 +614,7 @@ func (h *Handler) consoles(w http.ResponseWriter, r *http.Request) { return } defer file.Close() - text, err := ioutil.ReadAll(file) + text, err := io.ReadAll(file) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/web/web_test.go b/web/web_test.go index d5683840d5..2ea21a9ecb 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -18,7 +18,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -578,7 +577,7 @@ func TestAgentAPIEndPoints(t *testing.T) { } func cleanupTestResponse(t *testing.T, resp *http.Response) { - _, err := io.Copy(ioutil.Discard, resp.Body) + _, err := io.Copy(io.Discard, resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) } @@ -589,7 +588,7 @@ func cleanupSnapshot(t *testing.T, dbDir string, resp *http.Response) { Name string `json:"name"` } `json:"data"` }{} - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, json.Unmarshal(b, snapshot)) require.NotZero(t, snapshot.Data.Name, "snapshot directory not returned")