refactor: move from io/ioutil to io and os packages (#10528)

* refactor: move from io/ioutil to io and os packages
* use fs.DirEntry instead of os.FileInfo after os.ReadDir

Signed-off-by: MOREL Matthieu <matthieu.morel@cnp.fr>
This commit is contained in:
Matthieu MOREL 2022-04-27 11:24:36 +02:00 committed by GitHub
parent d8ca9aa67b
commit e2ede285a2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
76 changed files with 181 additions and 227 deletions

View file

@ -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

View file

@ -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))
}()

View file

@ -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())

View file

@ -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")

View file

@ -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
}

View file

@ -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)

View file

@ -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}
}

View file

@ -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
}

View file

@ -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)

View file

@ -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()
}()

View file

@ -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
}

View file

@ -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)

View file

@ -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
}

View file

@ -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

View file

@ -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)
}

View file

@ -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
}

View file

@ -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

View file

@ -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
}

View file

@ -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

View file

@ -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)
}

View file

@ -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")
}

View file

@ -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
}

View file

@ -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)

View file

@ -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)

View file

@ -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
}

View file

@ -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()

View file

@ -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.")
},

View file

@ -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)

View file

@ -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
}

View file

@ -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)}
}

View file

@ -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())

View file

@ -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()
}()

View file

@ -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)
}

View file

@ -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)
}

View file

@ -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)

View file

@ -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()

View file

@ -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
}

View file

@ -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()

View file

@ -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()
}()

View file

@ -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)
}

View file

@ -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)
}

View file

@ -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

View file

@ -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))
}

View file

@ -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
}

View file

@ -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

View file

@ -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)

View file

@ -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))

View file

@ -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")
}

View file

@ -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")
}

View file

@ -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
}

View file

@ -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
}

View file

@ -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 {

View file

@ -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
}

View file

@ -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

View file

@ -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.

View file

@ -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
}

View file

@ -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.

View file

@ -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
}

View file

@ -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.

View file

@ -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)

View file

@ -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
}

View file

@ -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 {

View file

@ -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)
}

View file

@ -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
}

View file

@ -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())

View file

@ -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())

View file

@ -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
}

View file

@ -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
}

View file

@ -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 {

View file

@ -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!"

View file

@ -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())

View file

@ -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

View file

@ -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{

View file

@ -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)

View file

@ -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

View file

@ -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")