refactor: move from io/ioutil to io and os package (#9811)

This commit is contained in:
Eng Zer Jun 2021-09-29 05:16:32 +08:00 committed by GitHub
parent c4d2ad85f0
commit 6a3b27126a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
165 changed files with 456 additions and 517 deletions

View File

@ -3,7 +3,7 @@ package config
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@ -933,7 +933,7 @@ func loadConfig(config string) ([]byte, error) {
} }
// If it isn't a https scheme, try it as a file // If it isn't a https scheme, try it as a file
return ioutil.ReadFile(config) return os.ReadFile(config)
} }
func fetchConfig(u *url.URL) ([]byte, error) { func fetchConfig(u *url.URL) ([]byte, error) {
@ -964,7 +964,7 @@ func fetchConfig(u *url.URL) ([]byte, error) {
return nil, fmt.Errorf("Retry %d of %d failed to retrieve remote config: %s", i, retries, resp.Status) return nil, fmt.Errorf("Retry %d of %d failed to retrieve remote config: %s", i, retries, resp.Status)
} }
defer resp.Body.Close() defer resp.Body.Close()
return ioutil.ReadAll(resp.Body) return io.ReadAll(resp.Body)
} }
return nil, nil return nil, nil

View File

@ -2,7 +2,7 @@ package internal
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -68,7 +68,7 @@ func TestStreamIdentityDecode(t *testing.T) {
dec, err := NewStreamContentDecoder("identity", &r) dec, err := NewStreamContentDecoder("identity", &r)
require.NoError(t, err) require.NoError(t, err)
data, err := ioutil.ReadAll(dec) data, err := io.ReadAll(dec)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte("howdy"), data) require.Equal(t, []byte("howdy"), data)

View File

@ -5,7 +5,6 @@ import (
"compress/gzip" "compress/gzip"
"crypto/rand" "crypto/rand"
"io" "io"
"io/ioutil"
"log" "log"
"os/exec" "os/exec"
"regexp" "regexp"
@ -182,7 +181,7 @@ func TestCompressWithGzip(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
defer gzipReader.Close() defer gzipReader.Close()
output, err := ioutil.ReadAll(gzipReader) output, err := io.ReadAll(gzipReader)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, testData, string(output)) assert.Equal(t, testData, string(output))
@ -203,7 +202,7 @@ func TestCompressWithGzipEarlyClose(t *testing.T) {
rc, err := CompressWithGzip(mr) rc, err := CompressWithGzip(mr)
assert.NoError(t, err) assert.NoError(t, err)
n, err := io.CopyN(ioutil.Discard, rc, 10000) n, err := io.CopyN(io.Discard, rc, 10000)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, int64(10000), n) assert.Equal(t, int64(10000), n)
@ -211,7 +210,7 @@ func TestCompressWithGzipEarlyClose(t *testing.T) {
err = rc.Close() err = rc.Close()
assert.NoError(t, err) assert.NoError(t, err)
n, err = io.CopyN(ioutil.Discard, rc, 10000) n, err = io.CopyN(io.Discard, rc, 10000)
assert.Error(t, io.EOF, err) assert.Error(t, io.EOF, err)
assert.Equal(t, int64(0), n) assert.Equal(t, int64(0), n)

View File

@ -5,7 +5,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os/exec" "os/exec"
"sync" "sync"
"sync/atomic" "sync/atomic"
@ -187,5 +186,5 @@ func isQuitting(ctx context.Context) bool {
} }
func defaultReadPipe(r io.Reader) { func defaultReadPipe(r io.Reader) {
io.Copy(ioutil.Discard, r) _, _ = io.Copy(io.Discard, r)
} }

View File

@ -1,7 +1,6 @@
package rotate package rotate
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -12,7 +11,7 @@ import (
) )
func TestFileWriter_NoRotation(t *testing.T) { func TestFileWriter_NoRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationNo") tempDir, err := os.MkdirTemp("", "RotationNo")
require.NoError(t, err) require.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test"), 0, 0, 0) writer, err := NewFileWriter(filepath.Join(tempDir, "test"), 0, 0, 0)
require.NoError(t, err) require.NoError(t, err)
@ -22,12 +21,12 @@ func TestFileWriter_NoRotation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
_, err = writer.Write([]byte("Hello World 2")) _, err = writer.Write([]byte("Hello World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 1, len(files)) assert.Equal(t, 1, len(files))
} }
func TestFileWriter_TimeRotation(t *testing.T) { func TestFileWriter_TimeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationTime") tempDir, err := os.MkdirTemp("", "RotationTime")
require.NoError(t, err) require.NoError(t, err)
interval, _ := time.ParseDuration("1s") interval, _ := time.ParseDuration("1s")
writer, err := NewFileWriter(filepath.Join(tempDir, "test"), interval, 0, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test"), interval, 0, -1)
@ -39,28 +38,28 @@ func TestFileWriter_TimeRotation(t *testing.T) {
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
_, err = writer.Write([]byte("Hello World 2")) _, err = writer.Write([]byte("Hello World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 2, len(files)) assert.Equal(t, 2, len(files))
} }
func TestFileWriter_ReopenTimeRotation(t *testing.T) { func TestFileWriter_ReopenTimeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationTime") tempDir, err := os.MkdirTemp("", "RotationTime")
require.NoError(t, err) require.NoError(t, err)
interval, _ := time.ParseDuration("1s") interval, _ := time.ParseDuration("1s")
filePath := filepath.Join(tempDir, "test.log") filePath := filepath.Join(tempDir, "test.log")
err = ioutil.WriteFile(filePath, []byte("Hello World"), 0644) err = os.WriteFile(filePath, []byte("Hello World"), 0644)
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
assert.NoError(t, err) assert.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), interval, 0, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), interval, 0, -1)
require.NoError(t, err) require.NoError(t, err)
defer func() { writer.Close(); os.RemoveAll(tempDir) }() defer func() { writer.Close(); os.RemoveAll(tempDir) }()
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 2, len(files)) assert.Equal(t, 2, len(files))
} }
func TestFileWriter_SizeRotation(t *testing.T) { func TestFileWriter_SizeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationSize") tempDir, err := os.MkdirTemp("", "RotationSize")
require.NoError(t, err) require.NoError(t, err)
maxSize := int64(9) maxSize := int64(9)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, -1)
@ -71,16 +70,16 @@ func TestFileWriter_SizeRotation(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
_, err = writer.Write([]byte("World 2")) _, err = writer.Write([]byte("World 2"))
require.NoError(t, err) require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 2, len(files)) assert.Equal(t, 2, len(files))
} }
func TestFileWriter_ReopenSizeRotation(t *testing.T) { func TestFileWriter_ReopenSizeRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationSize") tempDir, err := os.MkdirTemp("", "RotationSize")
require.NoError(t, err) require.NoError(t, err)
maxSize := int64(12) maxSize := int64(12)
filePath := filepath.Join(tempDir, "test.log") filePath := filepath.Join(tempDir, "test.log")
err = ioutil.WriteFile(filePath, []byte("Hello World"), 0644) err = os.WriteFile(filePath, []byte("Hello World"), 0644)
assert.NoError(t, err) assert.NoError(t, err)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, -1) writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, -1)
require.NoError(t, err) require.NoError(t, err)
@ -88,12 +87,12 @@ func TestFileWriter_ReopenSizeRotation(t *testing.T) {
_, err = writer.Write([]byte("Hello World Again")) _, err = writer.Write([]byte("Hello World Again"))
require.NoError(t, err) require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 2, len(files)) assert.Equal(t, 2, len(files))
} }
func TestFileWriter_DeleteArchives(t *testing.T) { func TestFileWriter_DeleteArchives(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationDeleteArchives") tempDir, err := os.MkdirTemp("", "RotationDeleteArchives")
require.NoError(t, err) require.NoError(t, err)
maxSize := int64(5) maxSize := int64(5)
writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, 2) writer, err := NewFileWriter(filepath.Join(tempDir, "test.log"), 0, maxSize, 2)
@ -112,14 +111,14 @@ func TestFileWriter_DeleteArchives(t *testing.T) {
_, err = writer.Write([]byte("Third file")) _, err = writer.Write([]byte("Third file"))
require.NoError(t, err) require.NoError(t, err)
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 3, len(files)) assert.Equal(t, 3, len(files))
for _, tempFile := range files { for _, tempFile := range files {
var bytes []byte var bytes []byte
var err error var err error
path := filepath.Join(tempDir, tempFile.Name()) path := filepath.Join(tempDir, tempFile.Name())
if bytes, err = ioutil.ReadFile(path); err != nil { if bytes, err = os.ReadFile(path); err != nil {
t.Error(err.Error()) t.Error(err.Error())
return return
} }
@ -133,7 +132,7 @@ func TestFileWriter_DeleteArchives(t *testing.T) {
} }
func TestFileWriter_CloseRotates(t *testing.T) { func TestFileWriter_CloseRotates(t *testing.T) {
tempDir, err := ioutil.TempDir("", "RotationClose") tempDir, err := os.MkdirTemp("", "RotationClose")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(tempDir) defer os.RemoveAll(tempDir)
maxSize := int64(9) maxSize := int64(9)
@ -142,7 +141,7 @@ func TestFileWriter_CloseRotates(t *testing.T) {
writer.Close() writer.Close()
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 1, len(files)) assert.Equal(t, 1, len(files))
assert.Regexp(t, "^test\\.[^\\.]+\\.log$", files[0].Name()) assert.Regexp(t, "^test\\.[^\\.]+\\.log$", files[0].Name())
} }

View File

@ -3,7 +3,6 @@ package logger
import ( import (
"bytes" "bytes"
"io" "io"
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@ -15,7 +14,7 @@ import (
) )
func TestWriteLogToFile(t *testing.T) { func TestWriteLogToFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := os.CreateTemp("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { os.Remove(tmpfile.Name()) }() defer func() { os.Remove(tmpfile.Name()) }()
@ -24,13 +23,13 @@ func TestWriteLogToFile(t *testing.T) {
log.Printf("I! TEST") log.Printf("I! TEST")
log.Printf("D! TEST") // <- should be ignored log.Printf("D! TEST") // <- should be ignored
f, err := ioutil.ReadFile(tmpfile.Name()) f, err := os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z I! TEST\n")) assert.Equal(t, f[19:], []byte("Z I! TEST\n"))
} }
func TestDebugWriteLogToFile(t *testing.T) { func TestDebugWriteLogToFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := os.CreateTemp("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { os.Remove(tmpfile.Name()) }() defer func() { os.Remove(tmpfile.Name()) }()
config := createBasicLogConfig(tmpfile.Name()) config := createBasicLogConfig(tmpfile.Name())
@ -38,13 +37,13 @@ func TestDebugWriteLogToFile(t *testing.T) {
SetupLogging(config) SetupLogging(config)
log.Printf("D! TEST") log.Printf("D! TEST")
f, err := ioutil.ReadFile(tmpfile.Name()) f, err := os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z D! TEST\n")) assert.Equal(t, f[19:], []byte("Z D! TEST\n"))
} }
func TestErrorWriteLogToFile(t *testing.T) { func TestErrorWriteLogToFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := os.CreateTemp("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { os.Remove(tmpfile.Name()) }() defer func() { os.Remove(tmpfile.Name()) }()
config := createBasicLogConfig(tmpfile.Name()) config := createBasicLogConfig(tmpfile.Name())
@ -53,13 +52,13 @@ func TestErrorWriteLogToFile(t *testing.T) {
log.Printf("E! TEST") log.Printf("E! TEST")
log.Printf("I! TEST") // <- should be ignored log.Printf("I! TEST") // <- should be ignored
f, err := ioutil.ReadFile(tmpfile.Name()) f, err := os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z E! TEST\n")) assert.Equal(t, f[19:], []byte("Z E! TEST\n"))
} }
func TestAddDefaultLogLevel(t *testing.T) { func TestAddDefaultLogLevel(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := os.CreateTemp("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { os.Remove(tmpfile.Name()) }() defer func() { os.Remove(tmpfile.Name()) }()
config := createBasicLogConfig(tmpfile.Name()) config := createBasicLogConfig(tmpfile.Name())
@ -67,13 +66,13 @@ func TestAddDefaultLogLevel(t *testing.T) {
SetupLogging(config) SetupLogging(config)
log.Printf("TEST") log.Printf("TEST")
f, err := ioutil.ReadFile(tmpfile.Name()) f, err := os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z I! TEST\n")) assert.Equal(t, f[19:], []byte("Z I! TEST\n"))
} }
func TestWriteToTruncatedFile(t *testing.T) { func TestWriteToTruncatedFile(t *testing.T) {
tmpfile, err := ioutil.TempFile("", "") tmpfile, err := os.CreateTemp("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer func() { os.Remove(tmpfile.Name()) }() defer func() { os.Remove(tmpfile.Name()) }()
config := createBasicLogConfig(tmpfile.Name()) config := createBasicLogConfig(tmpfile.Name())
@ -81,7 +80,7 @@ func TestWriteToTruncatedFile(t *testing.T) {
SetupLogging(config) SetupLogging(config)
log.Printf("TEST") log.Printf("TEST")
f, err := ioutil.ReadFile(tmpfile.Name()) f, err := os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z I! TEST\n")) assert.Equal(t, f[19:], []byte("Z I! TEST\n"))
@ -91,13 +90,13 @@ func TestWriteToTruncatedFile(t *testing.T) {
log.Printf("SHOULD BE FIRST") log.Printf("SHOULD BE FIRST")
f, err = ioutil.ReadFile(tmpfile.Name()) f, err = os.ReadFile(tmpfile.Name())
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, f[19:], []byte("Z I! SHOULD BE FIRST\n")) assert.Equal(t, f[19:], []byte("Z I! SHOULD BE FIRST\n"))
} }
func TestWriteToFileInRotation(t *testing.T) { func TestWriteToFileInRotation(t *testing.T) {
tempDir, err := ioutil.TempDir("", "LogRotation") tempDir, err := os.MkdirTemp("", "LogRotation")
require.NoError(t, err) require.NoError(t, err)
cfg := createBasicLogConfig(filepath.Join(tempDir, "test.log")) cfg := createBasicLogConfig(filepath.Join(tempDir, "test.log"))
cfg.LogTarget = LogTargetFile cfg.LogTarget = LogTargetFile
@ -110,7 +109,7 @@ func TestWriteToFileInRotation(t *testing.T) {
log.Printf("I! TEST 1") // Writes 31 bytes, will rotate log.Printf("I! TEST 1") // Writes 31 bytes, will rotate
log.Printf("I! TEST") // Writes 29 byes, no rotation expected log.Printf("I! TEST") // Writes 29 byes, no rotation expected
files, _ := ioutil.ReadDir(tempDir) files, _ := os.ReadDir(tempDir)
assert.Equal(t, 2, len(files)) assert.Equal(t, 2, len(files))
} }

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
"strings" "strings"
@ -78,7 +77,7 @@ func (c *CookieAuthConfig) authRenewal(ctx context.Context, ticker *clockutil.Ti
func (c *CookieAuthConfig) auth() error { func (c *CookieAuthConfig) auth() error {
var body io.ReadCloser var body io.ReadCloser
if c.Body != "" { if c.Body != "" {
body = ioutil.NopCloser(strings.NewReader(c.Body)) body = io.NopCloser(strings.NewReader(c.Body))
defer body.Close() defer body.Close()
} }
@ -97,7 +96,7 @@ func (c *CookieAuthConfig) auth() error {
} }
defer resp.Body.Close() defer resp.Body.Close()
if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil { if _, err = io.Copy(io.Discard, resp.Body); err != nil {
return err return err
} }

View File

@ -3,7 +3,7 @@ package cookie
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"sync/atomic" "sync/atomic"
@ -50,7 +50,7 @@ func newFakeServer(t *testing.T) fakeServer {
case authEndpointNoCreds: case authEndpointNoCreds:
authed() authed()
case authEndpointWithBody: case authEndpointWithBody:
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)
if !cmp.Equal([]byte(reqBody), body) { if !cmp.Equal([]byte(reqBody), body) {
w.WriteHeader(http.StatusUnauthorized) w.WriteHeader(http.StatusUnauthorized)

View File

@ -2,7 +2,7 @@ package encoding
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"testing" "testing"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -66,7 +66,7 @@ func TestDecoder(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
buf := bytes.NewBuffer(tt.input) buf := bytes.NewBuffer(tt.input)
r := decoder.Reader(buf) r := decoder.Reader(buf)
actual, err := ioutil.ReadAll(r) actual, err := io.ReadAll(r)
if tt.expectedErr { if tt.expectedErr {
require.Error(t, err) require.Error(t, err)
return return

View File

@ -1,7 +1,7 @@
package logrus package logrus
import ( import (
"io/ioutil" "io"
"log" "log"
"strings" "strings"
"sync" "sync"
@ -19,7 +19,7 @@ type LogHook struct {
// that directly log to the logrus system without providing an override method. // that directly log to the logrus system without providing an override method.
func InstallHook() { func InstallHook() {
once.Do(func() { once.Do(func() {
logrus.SetOutput(ioutil.Discard) logrus.SetOutput(io.Discard)
logrus.AddHook(&LogHook{}) logrus.AddHook(&LogHook{})
}) })
} }

View File

@ -3,7 +3,6 @@ package shim
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os" "os"
@ -53,7 +52,7 @@ func LoadConfig(filePath *string) (loaded loadedConfig, err error) {
var data string var data string
conf := config{} conf := config{}
if filePath != nil && *filePath != "" { if filePath != nil && *filePath != "" {
b, err := ioutil.ReadFile(*filePath) b, err := os.ReadFile(*filePath)
if err != nil { if err != nil {
return loadedConfig{}, err return loadedConfig{}, err
} }

View File

@ -3,7 +3,6 @@ package shim
import ( import (
"bufio" "bufio"
"io" "io"
"io/ioutil"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -45,7 +44,9 @@ func TestInputShimStdinSignalingWorks(t *testing.T) {
require.Equal(t, "measurement,tag=tag field=1i 1234000005678\n", out) require.Equal(t, "measurement,tag=tag field=1i 1234000005678\n", out)
stdinWriter.Close() stdinWriter.Close()
go ioutil.ReadAll(r) go func() {
_, _ = io.ReadAll(r)
}()
// check that it exits cleanly // check that it exits cleanly
<-exited <-exited
} }

View File

@ -3,7 +3,6 @@ package shim
import ( import (
"bufio" "bufio"
"io" "io"
"io/ioutil"
"math/rand" "math/rand"
"sync" "sync"
"testing" "testing"
@ -84,7 +83,9 @@ func testSendAndRecieve(t *testing.T, fieldKey string, fieldValue string) {
val2, ok := mOut.Fields()[fieldKey] val2, ok := mOut.Fields()[fieldKey]
require.True(t, ok) require.True(t, ok)
require.Equal(t, fieldValue, val2) require.Equal(t, fieldValue, val2)
go ioutil.ReadAll(r) go func() {
_, _ = io.ReadAll(r)
}()
wg.Wait() wg.Wait()
} }

View File

@ -4,7 +4,7 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
) )
@ -147,7 +147,7 @@ func (c *ServerConfig) TLSConfig() (*tls.Config, error) {
func makeCertPool(certFiles []string) (*x509.CertPool, error) { func makeCertPool(certFiles []string) (*x509.CertPool, error) {
pool := x509.NewCertPool() pool := x509.NewCertPool()
for _, certFile := range certFiles { for _, certFile := range certFiles {
pem, err := ioutil.ReadFile(certFile) pem, err := os.ReadFile(certFile)
if err != nil { if err != nil {
return nil, fmt.Errorf( return nil, fmt.Errorf(
"could not read certificate %q: %v", certFile, err) "could not read certificate %q: %v", certFile, err)

View File

@ -3,7 +3,7 @@ package activemq
import ( import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -184,7 +184,7 @@ func (a *ActiveMQ) GetMetrics(u string) ([]byte, error) {
return nil, fmt.Errorf("GET %s returned status %q", u, resp.Status) return nil, fmt.Errorf("GET %s returned status %q", u, resp.Status)
} }
return ioutil.ReadAll(resp.Body) return io.ReadAll(resp.Body)
} }
func (a *ActiveMQ) GatherQueuesMetrics(acc telegraf.Accumulator, queues Queues) { func (a *ActiveMQ) GatherQueuesMetrics(acc telegraf.Accumulator, queues Queues) {

View File

@ -2,7 +2,7 @@ package aliyuncms
import ( import (
"bytes" "bytes"
"io/ioutil" "io"
"net/http" "net/http"
"testing" "testing"
"time" "time"
@ -132,7 +132,7 @@ func TestPluginInitialize(t *testing.T) {
httpResp := &http.Response{ httpResp := &http.Response{
StatusCode: 200, StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{ `{
"LoadBalancers": "LoadBalancers":
{ {
@ -359,7 +359,7 @@ func TestGetDiscoveryDataAcrossRegions(t *testing.T) {
region: "cn-hongkong", region: "cn-hongkong",
httpResp: &http.Response{ httpResp: &http.Response{
StatusCode: 200, StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString(`{}`)), Body: io.NopCloser(bytes.NewBufferString(`{}`)),
}, },
totalCount: 0, totalCount: 0,
pageSize: 0, pageSize: 0,
@ -372,7 +372,7 @@ func TestGetDiscoveryDataAcrossRegions(t *testing.T) {
region: "cn-hongkong", region: "cn-hongkong",
httpResp: &http.Response{ httpResp: &http.Response{
StatusCode: 200, StatusCode: 200,
Body: ioutil.NopCloser(bytes.NewBufferString( Body: io.NopCloser(bytes.NewBufferString(
`{ `{
"LoadBalancers": "LoadBalancers":
{ {

View File

@ -1,7 +1,7 @@
package amd_rocm_smi package amd_rocm_smi
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -78,7 +78,7 @@ func TestGatherValidJSON(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
octets, err := ioutil.ReadFile(filepath.Join("testdata", tt.filename)) octets, err := os.ReadFile(filepath.Join("testdata", tt.filename))
require.NoError(t, err) require.NoError(t, err)
err = gatherROCmSMI(octets, &acc) err = gatherROCmSMI(octets, &acc)

View File

@ -8,7 +8,6 @@ package bcache
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -85,7 +84,7 @@ func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error {
if len(metrics) == 0 { if len(metrics) == 0 {
return errors.New("can't read any stats file") return errors.New("can't read any stats file")
} }
file, err := ioutil.ReadFile(bdev + "/dirty_data") file, err := os.ReadFile(bdev + "/dirty_data")
if err != nil { if err != nil {
return err return err
} }
@ -97,7 +96,7 @@ func (b *Bcache) gatherBcache(bdev string, acc telegraf.Accumulator) error {
for _, path := range metrics { for _, path := range metrics {
key := filepath.Base(path) key := filepath.Base(path)
file, err := ioutil.ReadFile(path) file, err := os.ReadFile(path)
rawValue := strings.TrimSpace(string(file)) rawValue := strings.TrimSpace(string(file))
if err != nil { if err != nil {
return err return err

View File

@ -4,7 +4,6 @@
package bcache package bcache
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -50,39 +49,39 @@ func TestBcacheGeneratesMetrics(t *testing.T) {
err = os.MkdirAll(testBcacheUUIDPath+"/bdev0/stats_total", 0755) err = os.MkdirAll(testBcacheUUIDPath+"/bdev0/stats_total", 0755)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/dirty_data", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/dirty_data",
[]byte(dirtyData), 0644) []byte(dirtyData), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/bypassed", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/bypassed",
[]byte(bypassed), 0644) []byte(bypassed), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_bypass_hits", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_bypass_hits",
[]byte(cacheBypassHits), 0644) []byte(cacheBypassHits), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_bypass_misses", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_bypass_misses",
[]byte(cacheBypassMisses), 0644) []byte(cacheBypassMisses), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_hit_ratio", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_hit_ratio",
[]byte(cacheHitRatio), 0644) []byte(cacheHitRatio), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_hits", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_hits",
[]byte(cacheHits), 0644) []byte(cacheHits), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_miss_collisions", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_miss_collisions",
[]byte(cacheMissCollisions), 0644) []byte(cacheMissCollisions), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_misses", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_misses",
[]byte(cacheMisses), 0644) []byte(cacheMisses), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_readaheads", err = os.WriteFile(testBcacheUUIDPath+"/bdev0/stats_total/cache_readaheads",
[]byte(cacheReadaheads), 0644) []byte(cacheReadaheads), 0644)
require.NoError(t, err) require.NoError(t, err)

View File

@ -2,11 +2,11 @@ package beat
import ( import (
"fmt" "fmt"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
"os"
"testing" "testing"
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
@ -31,7 +31,7 @@ func Test_BeatStats(t *testing.T) {
require.FailNow(t, "cannot handle request") require.FailNow(t, "cannot handle request")
} }
data, err := ioutil.ReadFile(jsonFilePath) data, err := os.ReadFile(jsonFilePath)
require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath) require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath)
_, err = w.Write(data) _, err = w.Write(data)
require.NoError(t, err, "could not write data") require.NoError(t, err, "could not write data")
@ -175,7 +175,7 @@ func Test_BeatRequest(t *testing.T) {
require.FailNow(t, "cannot handle request") require.FailNow(t, "cannot handle request")
} }
data, err := ioutil.ReadFile(jsonFilePath) data, err := os.ReadFile(jsonFilePath)
require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath) require.NoErrorf(t, err, "could not read from data file %s", jsonFilePath)
require.Equal(t, request.Host, "beat.test.local") require.Equal(t, request.Host, "beat.test.local")
require.Equal(t, request.Method, "POST") require.Equal(t, request.Method, "POST")

View File

@ -3,7 +3,6 @@ package bond
import ( import (
"bufio" "bufio"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -53,7 +52,7 @@ func (bond *Bond) Gather(acc telegraf.Accumulator) error {
} }
for _, bondName := range bondNames { for _, bondName := range bondNames {
bondAbsPath := bond.HostProc + "/net/bonding/" + bondName bondAbsPath := bond.HostProc + "/net/bonding/" + bondName
file, err := ioutil.ReadFile(bondAbsPath) file, err := os.ReadFile(bondAbsPath)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("error inspecting '%s' interface: %v", bondAbsPath, err)) acc.AddError(fmt.Errorf("error inspecting '%s' interface: %v", bondAbsPath, err))
continue continue

View File

@ -2,7 +2,6 @@ package burrow
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@ -28,7 +27,7 @@ func getResponseJSON(requestURI string) ([]byte, int) {
} }
// respond with file // respond with file
b, _ := ioutil.ReadFile(jsonFile) b, _ := os.ReadFile(jsonFile)
return b, code return b, code
} }

View File

@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@ -217,7 +217,7 @@ func (c *Cassandra) getAttr(requestURL *url.URL) (map[string]interface{}, error)
} }
// read body // read body
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -2,7 +2,7 @@ package cassandra
import ( import (
_ "fmt" _ "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -109,7 +109,7 @@ type jolokiaClientStub struct {
func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) { func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) {
resp := http.Response{} resp := http.Response{}
resp.StatusCode = c.statusCode resp.StatusCode = c.statusCode
resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) resp.Body = io.NopCloser(strings.NewReader(c.responseBody))
return &resp, nil return &resp, nil
} }

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
@ -206,7 +206,7 @@ var perfDump = func(binary string, socket *socket) (string, error) {
} }
var findSockets = func(c *Ceph) ([]*socket, error) { var findSockets = func(c *Ceph) ([]*socket, error) {
listing, err := ioutil.ReadDir(c.SocketDir) listing, err := os.ReadDir(c.SocketDir)
if err != nil { if err != nil {
return []*socket{}, fmt.Errorf("Failed to read socket directory '%s': %v", c.SocketDir, err) return []*socket{}, fmt.Errorf("Failed to read socket directory '%s': %v", c.SocketDir, err)
} }

View File

@ -2,7 +2,6 @@ package ceph
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@ -113,7 +112,7 @@ func TestGather(t *testing.T) {
} }
func TestFindSockets(t *testing.T) { func TestFindSockets(t *testing.T) {
tmpdir, err := ioutil.TempDir("", "socktest") tmpdir, err := os.MkdirTemp("", "socktest")
require.NoError(t, err) require.NoError(t, err)
defer func() { defer func() {
err := os.Remove(tmpdir) err := os.Remove(tmpdir)
@ -189,7 +188,7 @@ func createTestFiles(dir string, st *SockTest) error {
writeFile := func(prefix string, i int) error { writeFile := func(prefix string, i int) error {
f := sockFile(prefix, i) f := sockFile(prefix, i)
fpath := filepath.Join(dir, f) fpath := filepath.Join(dir, f)
return ioutil.WriteFile(fpath, []byte(""), 0777) return os.WriteFile(fpath, []byte(""), 0777)
} }
return tstFileApply(st, writeFile) return tstFileApply(st, writeFile)
} }

View File

@ -5,7 +5,6 @@ package cgroup
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -46,7 +45,7 @@ func (g *CGroup) gatherDir(acc telegraf.Accumulator, dir string) error {
return file.err return file.err
} }
raw, err := ioutil.ReadFile(file.path) raw, err := os.ReadFile(file.path)
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -590,7 +589,7 @@ func (ch *ClickHouse) execQuery(address *url.URL, query string, i interface{}) e
} }
defer func() { _ = resp.Body.Close() }() defer func() { _ = resp.Body.Close() }()
if resp.StatusCode >= 300 { if resp.StatusCode >= 300 {
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 200)) body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return &clickhouseError{ return &clickhouseError{
StatusCode: resp.StatusCode, StatusCode: resp.StatusCode,
body: body, body: body,
@ -606,7 +605,7 @@ func (ch *ClickHouse) execQuery(address *url.URL, query string, i interface{}) e
return err return err
} }
if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { if _, err := io.Copy(io.Discard, resp.Body); err != nil {
return err return err
} }
return nil return nil

View File

@ -5,7 +5,7 @@ import (
"crypto/subtle" "crypto/subtle"
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"sync" "sync"
"time" "time"
@ -222,7 +222,7 @@ func (p *PubSubPush) serveWrite(res http.ResponseWriter, req *http.Request) {
} }
body := http.MaxBytesReader(res, req.Body, int64(p.MaxBodySize)) body := http.MaxBytesReader(res, req.Body, int64(p.MaxBodySize))
bytes, err := ioutil.ReadAll(body) bytes, err := io.ReadAll(body)
if err != nil { if err != nil {
res.WriteHeader(http.StatusRequestEntityTooLarge) res.WriteHeader(http.StatusRequestEntityTooLarge)
return return

View File

@ -5,14 +5,14 @@ package conntrack
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"path/filepath"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs" "github.com/influxdata/telegraf/plugins/inputs"
"path/filepath"
) )
type Conntrack struct { type Conntrack struct {
@ -91,7 +91,7 @@ func (c *Conntrack) Gather(acc telegraf.Accumulator) error {
continue continue
} }
contents, err := ioutil.ReadFile(fName) contents, err := os.ReadFile(fName)
if err != nil { if err != nil {
acc.AddError(fmt.Errorf("E! failed to read file '%s': %v", fName, err)) acc.AddError(fmt.Errorf("E! failed to read file '%s': %v", fName, err))
continue continue

View File

@ -4,7 +4,6 @@
package conntrack package conntrack
import ( import (
"io/ioutil"
"os" "os"
"path" "path"
"strconv" "strconv"
@ -35,11 +34,11 @@ func TestNoFilesFound(t *testing.T) {
func TestDefaultsUsed(t *testing.T) { func TestDefaultsUsed(t *testing.T) {
defer restoreDflts(dfltFiles, dfltDirs) defer restoreDflts(dfltFiles, dfltDirs)
tmpdir, err := ioutil.TempDir("", "tmp1") tmpdir, err := os.MkdirTemp("", "tmp1")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpdir) defer os.Remove(tmpdir)
tmpFile, err := ioutil.TempFile(tmpdir, "ip_conntrack_count") tmpFile, err := os.CreateTemp(tmpdir, "ip_conntrack_count")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpFile.Name()) defer os.Remove(tmpFile.Name())
@ -48,7 +47,7 @@ func TestDefaultsUsed(t *testing.T) {
dfltFiles = []string{fname} dfltFiles = []string{fname}
count := 1234321 count := 1234321
require.NoError(t, ioutil.WriteFile(tmpFile.Name(), []byte(strconv.Itoa(count)), 0660)) require.NoError(t, os.WriteFile(tmpFile.Name(), []byte(strconv.Itoa(count)), 0660))
c := &Conntrack{} c := &Conntrack{}
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}
@ -59,13 +58,13 @@ func TestDefaultsUsed(t *testing.T) {
func TestConfigsUsed(t *testing.T) { func TestConfigsUsed(t *testing.T) {
defer restoreDflts(dfltFiles, dfltDirs) defer restoreDflts(dfltFiles, dfltDirs)
tmpdir, err := ioutil.TempDir("", "tmp1") tmpdir, err := os.MkdirTemp("", "tmp1")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(tmpdir) defer os.Remove(tmpdir)
cntFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_count") cntFile, err := os.CreateTemp(tmpdir, "nf_conntrack_count")
require.NoError(t, err) require.NoError(t, err)
maxFile, err := ioutil.TempFile(tmpdir, "nf_conntrack_max") maxFile, err := os.CreateTemp(tmpdir, "nf_conntrack_max")
require.NoError(t, err) require.NoError(t, err)
defer os.Remove(cntFile.Name()) defer os.Remove(cntFile.Name())
defer os.Remove(maxFile.Name()) defer os.Remove(maxFile.Name())
@ -77,8 +76,8 @@ func TestConfigsUsed(t *testing.T) {
count := 1234321 count := 1234321
max := 9999999 max := 9999999
require.NoError(t, ioutil.WriteFile(cntFile.Name(), []byte(strconv.Itoa(count)), 0660)) require.NoError(t, os.WriteFile(cntFile.Name(), []byte(strconv.Itoa(count)), 0660))
require.NoError(t, ioutil.WriteFile(maxFile.Name(), []byte(strconv.Itoa(max)), 0660)) require.NoError(t, os.WriteFile(maxFile.Name(), []byte(strconv.Itoa(max)), 0660))
c := &Conntrack{} c := &Conntrack{}
acc := &testutil.Accumulator{} acc := &testutil.Accumulator{}

View File

@ -4,7 +4,7 @@ import (
"context" "context"
"crypto/rsa" "crypto/rsa"
"fmt" "fmt"
"io/ioutil" "os"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
@ -48,7 +48,7 @@ func (c *ServiceAccount) IsExpired() bool {
} }
func (c *TokenCreds) Token(_ context.Context, _ Client) (string, error) { func (c *TokenCreds) Token(_ context.Context, _ Client) (string, error) {
octets, err := ioutil.ReadFile(c.Path) octets, err := os.ReadFile(c.Path)
if err != nil { if err != nil {
return "", fmt.Errorf("error reading token file %q: %s", c.Path, err) return "", fmt.Errorf("error reading token file %q: %s", c.Path, err)
} }

View File

@ -2,8 +2,8 @@ package dcos
import ( import (
"context" "context"
"io/ioutil"
"net/url" "net/url"
"os"
"sort" "sort"
"strings" "strings"
"sync" "sync"
@ -370,7 +370,7 @@ func (d *DCOS) createClient() (Client, error) {
func (d *DCOS) createCredentials() (Credentials, error) { func (d *DCOS) createCredentials() (Credentials, error) {
if d.ServiceAccountID != "" && d.ServiceAccountPrivateKey != "" { if d.ServiceAccountID != "" && d.ServiceAccountPrivateKey != "" {
bs, err := ioutil.ReadFile(d.ServiceAccountPrivateKey) bs, err := os.ReadFile(d.ServiceAccountPrivateKey)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -7,7 +7,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -108,7 +107,7 @@ func (monitor *DirectoryMonitor) Description() string {
func (monitor *DirectoryMonitor) Gather(_ telegraf.Accumulator) error { func (monitor *DirectoryMonitor) Gather(_ telegraf.Accumulator) error {
// Get all files sitting in the directory. // Get all files sitting in the directory.
files, err := ioutil.ReadDir(monitor.Directory) files, err := os.ReadDir(monitor.Directory)
if err != nil { if err != nil {
return fmt.Errorf("unable to monitor the targeted directory: %w", err) return fmt.Errorf("unable to monitor the targeted directory: %w", err)
} }
@ -183,7 +182,7 @@ func (monitor *DirectoryMonitor) Monitor() {
} }
} }
func (monitor *DirectoryMonitor) processFile(file os.FileInfo) { func (monitor *DirectoryMonitor) processFile(file os.DirEntry) {
if file.IsDir() { if file.IsDir() {
return return
} }

View File

@ -3,7 +3,6 @@ package directory_monitor
import ( import (
"bytes" "bytes"
"compress/gzip" "compress/gzip"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -20,9 +19,9 @@ func TestCSVGZImport(t *testing.T) {
testCsvGzFile := "test.csv.gz" testCsvGzFile := "test.csv.gz"
// Establish process directory and finished directory. // Establish process directory and finished directory.
finishedDirectory, err := ioutil.TempDir("", "finished") finishedDirectory, err := os.MkdirTemp("", "finished")
require.NoError(t, err) require.NoError(t, err)
processDirectory, err := ioutil.TempDir("", "test") processDirectory, err := os.MkdirTemp("", "test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(processDirectory) defer os.RemoveAll(processDirectory)
defer os.RemoveAll(finishedDirectory) defer os.RemoveAll(finishedDirectory)
@ -62,7 +61,7 @@ func TestCSVGZImport(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
err = w.Close() err = w.Close()
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(processDirectory, testCsvGzFile), b.Bytes(), 0666) err = os.WriteFile(filepath.Join(processDirectory, testCsvGzFile), b.Bytes(), 0666)
require.NoError(t, err) require.NoError(t, err)
// Start plugin before adding file. // Start plugin before adding file.
@ -89,9 +88,9 @@ func TestMultipleJSONFileImports(t *testing.T) {
testJSONFile := "test.json" testJSONFile := "test.json"
// Establish process directory and finished directory. // Establish process directory and finished directory.
finishedDirectory, err := ioutil.TempDir("", "finished") finishedDirectory, err := os.MkdirTemp("", "finished")
require.NoError(t, err) require.NoError(t, err)
processDirectory, err := ioutil.TempDir("", "test") processDirectory, err := os.MkdirTemp("", "test")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(processDirectory) defer os.RemoveAll(processDirectory)
defer os.RemoveAll(finishedDirectory) defer os.RemoveAll(finishedDirectory)

View File

@ -4,7 +4,6 @@
package diskio package diskio
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -20,7 +19,7 @@ S:foo/bar/devlink1
// setupNullDisk sets up fake udev info as if /dev/null were a disk. // setupNullDisk sets up fake udev info as if /dev/null were a disk.
func setupNullDisk(t *testing.T, s *DiskIO, devName string) func() { func setupNullDisk(t *testing.T, s *DiskIO, devName string) func() {
td, err := ioutil.TempFile("", ".telegraf.DiskInfoTest") td, err := os.CreateTemp("", ".telegraf.DiskInfoTest")
require.NoError(t, err) require.NoError(t, err)
if s.infoCache == nil { if s.infoCache == nil {

View File

@ -3,7 +3,7 @@ package docker
import ( import (
"context" "context"
"crypto/tls" "crypto/tls"
"io/ioutil" "io"
"reflect" "reflect"
"sort" "sort"
"strings" "strings"
@ -1060,7 +1060,7 @@ func TestContainerName(t *testing.T) {
} }
client.ContainerStatsF = func(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { client.ContainerStatsF = func(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) {
return types.ContainerStats{ return types.ContainerStats{
Body: ioutil.NopCloser(strings.NewReader(`{"name": "logspout"}`)), Body: io.NopCloser(strings.NewReader(`{"name": "logspout"}`)),
}, nil }, nil
} }
return &client, nil return &client, nil
@ -1080,7 +1080,7 @@ func TestContainerName(t *testing.T) {
} }
client.ContainerStatsF = func(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { client.ContainerStatsF = func(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) {
return types.ContainerStats{ return types.ContainerStats{
Body: ioutil.NopCloser(strings.NewReader(`{}`)), Body: io.NopCloser(strings.NewReader(`{}`)),
}, nil }, nil
} }
return &client, nil return &client, nil

View File

@ -2,7 +2,7 @@ package docker
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"strings" "strings"
"time" "time"
@ -344,7 +344,7 @@ func containerStats(s string) types.ContainerStats {
}, },
"read": "2016-02-24T11:42:27.472459608-05:00" "read": "2016-02-24T11:42:27.472459608-05:00"
}`, name) }`, name)
stat.Body = ioutil.NopCloser(strings.NewReader(jsonStat)) stat.Body = io.NopCloser(strings.NewReader(jsonStat))
return stat return stat
} }
@ -488,7 +488,7 @@ func containerStatsWindows() types.ContainerStats {
}, },
"name":"/gt_test_iis", "name":"/gt_test_iis",
}` }`
stat.Body = ioutil.NopCloser(strings.NewReader(jsonStat)) stat.Body = io.NopCloser(strings.NewReader(jsonStat))
return stat return stat
} }

View File

@ -3,7 +3,6 @@ package ecs
import ( import (
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
@ -113,7 +112,7 @@ func (c *EcsClient) Task() (*Task, error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 200)) body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return nil, fmt.Errorf("%s returned HTTP status %s: %q", c.taskURL, resp.Status, body) return nil, fmt.Errorf("%s returned HTTP status %s: %q", c.taskURL, resp.Status, body)
} }
@ -137,7 +136,7 @@ func (c *EcsClient) ContainerStats() (map[string]types.StatsJSON, error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 200)) body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return nil, fmt.Errorf("%s returned HTTP status %s: %q", c.statsURL, resp.Status, body) return nil, fmt.Errorf("%s returned HTTP status %s: %q", c.statsURL, resp.Status, body)
} }

View File

@ -3,7 +3,7 @@ package ecs
import ( import (
"bytes" "bytes"
"errors" "errors"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@ -108,7 +108,7 @@ func TestEcsClient_Task(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(rc), Body: io.NopCloser(rc),
}, nil }, nil
}, },
}, },
@ -129,7 +129,7 @@ func TestEcsClient_Task(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusInternalServerError, StatusCode: http.StatusInternalServerError,
Body: ioutil.NopCloser(bytes.NewReader([]byte("foo"))), Body: io.NopCloser(bytes.NewReader([]byte("foo"))),
}, nil }, nil
}, },
}, },
@ -141,7 +141,7 @@ func TestEcsClient_Task(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte("foo"))), Body: io.NopCloser(bytes.NewReader([]byte("foo"))),
}, nil }, nil
}, },
}, },
@ -179,7 +179,7 @@ func TestEcsClient_ContainerStats(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(rc), Body: io.NopCloser(rc),
}, nil }, nil
}, },
}, },
@ -201,7 +201,7 @@ func TestEcsClient_ContainerStats(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusOK, StatusCode: http.StatusOK,
Body: ioutil.NopCloser(bytes.NewReader([]byte("foo"))), Body: io.NopCloser(bytes.NewReader([]byte("foo"))),
}, nil }, nil
}, },
}, },
@ -214,7 +214,7 @@ func TestEcsClient_ContainerStats(t *testing.T) {
do: func(req *http.Request) (*http.Response, error) { do: func(req *http.Request) (*http.Response, error) {
return &http.Response{ return &http.Response{
StatusCode: http.StatusInternalServerError, StatusCode: http.StatusInternalServerError,
Body: ioutil.NopCloser(bytes.NewReader([]byte("foo"))), Body: io.NopCloser(bytes.NewReader([]byte("foo"))),
}, nil }, nil
}, },
}, },

View File

@ -3,7 +3,7 @@ package elasticsearch
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"regexp" "regexp"
"sort" "sort"
@ -702,7 +702,7 @@ func (e *Elasticsearch) getCatMaster(url string) (string, error) {
// future calls. // future calls.
return "", fmt.Errorf("elasticsearch: Unable to retrieve master node information. API responded with status-code %d, expected %d", r.StatusCode, http.StatusOK) return "", fmt.Errorf("elasticsearch: Unable to retrieve master node information. API responded with status-code %d, expected %d", r.StatusCode, http.StatusOK)
} }
response, err := ioutil.ReadAll(r.Body) response, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return "", err return "", err

View File

@ -1,7 +1,7 @@
package elasticsearch package elasticsearch
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -44,7 +44,7 @@ func (t *transportMock) RoundTrip(r *http.Request) (*http.Response, error) {
StatusCode: t.statusCode, StatusCode: t.statusCode,
} }
res.Header.Set("Content-Type", "application/json") res.Header.Set("Content-Type", "application/json")
res.Body = ioutil.NopCloser(strings.NewReader(t.body)) res.Body = io.NopCloser(strings.NewReader(t.body))
return res, nil return res, nil
} }

View File

@ -8,7 +8,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"os/signal" "os/signal"
"strings" "strings"
@ -274,7 +273,7 @@ func LoadConfig(filePath *string) ([]telegraf.Input, error) {
return DefaultImportedPlugins() return DefaultImportedPlugins()
} }
b, err := ioutil.ReadFile(*filePath) b, err := os.ReadFile(*filePath)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -2,7 +2,7 @@ package file
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
@ -115,7 +115,7 @@ func (f *File) readMetric(filename string) ([]telegraf.Metric, error) {
defer file.Close() defer file.Close()
r, _ := utfbom.Skip(f.decoder.Reader(file)) r, _ := utfbom.Skip(f.decoder.Reader(file))
fileContents, err := ioutil.ReadAll(r) fileContents, err := io.ReadAll(r)
if err != nil { if err != nil {
return nil, fmt.Errorf("E! Error file: %v could not be read, %s", filename, err) return nil, fmt.Errorf("E! Error file: %v could not be read, %s", filename, err)
} }

View File

@ -3,7 +3,7 @@ package fluentd
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
@ -104,7 +104,7 @@ func (h *Fluentd) Gather(acc telegraf.Accumulator) error {
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return fmt.Errorf("unable to read the HTTP body \"%s\": %v", string(body), err) return fmt.Errorf("unable to read the HTTP body \"%s\": %v", string(body), err)

View File

@ -5,7 +5,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -264,7 +264,7 @@ func (h *GrayLog) sendRequest(serverURL string) (string, float64, error) {
defer resp.Body.Close() defer resp.Body.Close()
responseTime := time.Since(start).Seconds() responseTime := time.Since(start).Seconds()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return string(body), responseTime, err return string(body), responseTime, err
} }

View File

@ -1,7 +1,7 @@
package graylog package graylog
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -115,7 +115,7 @@ func (c *mockHTTPClient) MakeRequest(req *http.Request) (*http.Response, error)
resp.StatusCode = 405 // Method not allowed resp.StatusCode = 405 // Method not allowed
} }
resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) resp.Body = io.NopCloser(strings.NewReader(c.responseBody))
return &resp, nil return &resp, nil
} }

View File

@ -4,8 +4,8 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"os"
"strings" "strings"
"sync" "sync"
@ -180,7 +180,7 @@ func (h *HTTP) gatherURL(
} }
if h.BearerToken != "" { if h.BearerToken != "" {
token, err := ioutil.ReadFile(h.BearerToken) token, err := os.ReadFile(h.BearerToken)
if err != nil { if err != nil {
return err return err
} }
@ -225,7 +225,7 @@ func (h *HTTP) gatherURL(
h.SuccessStatusCodes) h.SuccessStatusCodes)
} }
b, err := ioutil.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }
@ -254,7 +254,7 @@ func makeRequestBodyReader(contentEncoding, body string) (io.ReadCloser, error)
} }
return rc, nil return rc, nil
} }
return ioutil.NopCloser(reader), nil return io.NopCloser(reader), nil
} }
func init() { func init() {

View File

@ -3,7 +3,7 @@ package http_test
import ( import (
"compress/gzip" "compress/gzip"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@ -183,7 +183,7 @@ func TestBodyAndContentEncoding(t *testing.T) {
URLs: []string{url}, URLs: []string{url},
}, },
queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte(""), body) require.Equal(t, []byte(""), body)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -197,7 +197,7 @@ func TestBodyAndContentEncoding(t *testing.T) {
Body: "test", Body: "test",
}, },
queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte("test"), body) require.Equal(t, []byte("test"), body)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -211,7 +211,7 @@ func TestBodyAndContentEncoding(t *testing.T) {
Body: "test", Body: "test",
}, },
queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) { queryHandlerFunc: func(t *testing.T, w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte("test"), body) require.Equal(t, []byte("test"), body)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -230,7 +230,7 @@ func TestBodyAndContentEncoding(t *testing.T) {
gr, err := gzip.NewReader(r.Body) gr, err := gzip.NewReader(r.Body)
require.NoError(t, err) require.NoError(t, err)
body, err := ioutil.ReadAll(gr) body, err := io.ReadAll(gr)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []byte("test"), body) require.Equal(t, []byte("test"), body)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View File

@ -4,7 +4,7 @@ import (
"compress/gzip" "compress/gzip"
"crypto/subtle" "crypto/subtle"
"crypto/tls" "crypto/tls"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -292,7 +292,7 @@ func (h *HTTPListenerV2) collectBody(res http.ResponseWriter, req *http.Request)
} }
defer r.Close() defer r.Close()
maxReader := http.MaxBytesReader(res, r, int64(h.MaxBodySize)) maxReader := http.MaxBytesReader(res, r, int64(h.MaxBodySize))
bytes, err := ioutil.ReadAll(maxReader) bytes, err := io.ReadAll(maxReader)
if err != nil { if err != nil {
if err := tooLarge(res); err != nil { if err := tooLarge(res); err != nil {
h.Log.Debugf("error in too-large: %v", err) h.Log.Debugf("error in too-large: %v", err)
@ -302,7 +302,7 @@ func (h *HTTPListenerV2) collectBody(res http.ResponseWriter, req *http.Request)
return bytes, true return bytes, true
case "snappy": case "snappy":
defer req.Body.Close() defer req.Body.Close()
bytes, err := ioutil.ReadAll(req.Body) bytes, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
h.Log.Debug(err.Error()) h.Log.Debug(err.Error())
if err := badRequest(res); err != nil { if err := badRequest(res); err != nil {
@ -322,7 +322,7 @@ func (h *HTTPListenerV2) collectBody(res http.ResponseWriter, req *http.Request)
return bytes, true return bytes, true
default: default:
defer req.Body.Close() defer req.Body.Close()
bytes, err := ioutil.ReadAll(req.Body) bytes, err := io.ReadAll(req.Body)
if err != nil { if err != nil {
h.Log.Debug(err.Error()) h.Log.Debug(err.Error())
if err := badRequest(res); err != nil { if err := badRequest(res); err != nil {

View File

@ -4,9 +4,9 @@ import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os"
"runtime" "runtime"
"strconv" "strconv"
"sync" "sync"
@ -361,7 +361,7 @@ func TestWriteHTTPGzippedData(t *testing.T) {
require.NoError(t, listener.Start(acc)) require.NoError(t, listener.Start(acc))
defer listener.Stop() defer listener.Stop()
data, err := ioutil.ReadFile("./testdata/testmsgs.gz") data, err := os.ReadFile("./testdata/testmsgs.gz")
require.NoError(t, err) require.NoError(t, err)
req, err := http.NewRequest("POST", createURL(listener, "http", "/write", ""), bytes.NewBuffer(data)) req, err := http.NewRequest("POST", createURL(listener, "http", "/write", ""), bytes.NewBuffer(data))

View File

@ -4,10 +4,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
"os"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -277,7 +277,7 @@ func (h *HTTPResponse) httpGather(u string) (map[string]interface{}, map[string]
} }
if h.BearerToken != "" { if h.BearerToken != "" {
token, err := ioutil.ReadFile(h.BearerToken) token, err := os.ReadFile(h.BearerToken)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
@ -339,7 +339,7 @@ func (h *HTTPResponse) httpGather(u string) (map[string]interface{}, map[string]
if h.ResponseBodyMaxSize == 0 { if h.ResponseBodyMaxSize == 0 {
h.ResponseBodyMaxSize = config.Size(defaultResponseBodyMaxSize) h.ResponseBodyMaxSize = config.Size(defaultResponseBodyMaxSize)
} }
bodyBytes, err := ioutil.ReadAll(io.LimitReader(resp.Body, int64(h.ResponseBodyMaxSize)+1)) bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, int64(h.ResponseBodyMaxSize)+1))
// Check first if the response body size exceeds the limit. // Check first if the response body size exceeds the limit.
if err == nil && int64(len(bodyBytes)) > int64(h.ResponseBodyMaxSize) { if err == nil && int64(len(bodyBytes)) > int64(h.ResponseBodyMaxSize) {
h.setBodyReadError("The body of the HTTP Response is too large", bodyBytes, fields, tags) h.setBodyReadError("The body of the HTTP Response is too large", bodyBytes, fields, tags)

View File

@ -8,7 +8,7 @@ package http_response
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
@ -123,7 +123,7 @@ func setUpTestMux() http.Handler {
fmt.Fprintf(w, "used post correctly!") fmt.Fprintf(w, "used post correctly!")
}) })
mux.HandleFunc("/musthaveabody", func(w http.ResponseWriter, req *http.Request) { mux.HandleFunc("/musthaveabody", func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body) body, err := io.ReadAll(req.Body)
//nolint:errcheck,revive //nolint:errcheck,revive
req.Body.Close() req.Body.Close()
if err != nil { if err != nil {

View File

@ -3,7 +3,7 @@ package httpjson
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@ -263,7 +263,7 @@ func (h *HTTPJSON) sendRequest(serverURL string) (string, float64, error) {
defer resp.Body.Close() defer resp.Body.Close()
responseTime := time.Since(start).Seconds() responseTime := time.Since(start).Seconds()
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return string(body), responseTime, err return string(body), responseTime, err
} }

View File

@ -2,7 +2,7 @@ package httpjson
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
@ -143,7 +143,7 @@ func (c *mockHTTPClient) MakeRequest(req *http.Request) (*http.Response, error)
resp.StatusCode = 405 // Method not allowed resp.StatusCode = 405 // Method not allowed
} }
resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) resp.Body = io.NopCloser(strings.NewReader(c.responseBody))
return &resp, nil return &resp, nil
} }
@ -377,7 +377,7 @@ func TestHttpJsonPOST(t *testing.T) {
"api_key": "mykey", "api_key": "mykey",
} }
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "api_key=mykey", string(body)) assert.Equal(t, "api_key=mykey", string(body))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)

View File

@ -4,9 +4,9 @@ import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"os"
"runtime" "runtime"
"strconv" "strconv"
"sync" "sync"
@ -406,7 +406,7 @@ func TestWriteGzippedData(t *testing.T) {
require.NoError(t, listener.Start(acc)) require.NoError(t, listener.Start(acc))
defer listener.Stop() defer listener.Stop()
data, err := ioutil.ReadFile("./testdata/testmsgs.gz") data, err := os.ReadFile("./testdata/testmsgs.gz")
require.NoError(t, err) require.NoError(t, err)
req, err := http.NewRequest("POST", createURL(listener, "http", "/write", ""), bytes.NewBuffer(data)) req, err := http.NewRequest("POST", createURL(listener, "http", "/write", ""), bytes.NewBuffer(data))

View File

@ -6,7 +6,7 @@ import (
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"time" "time"
@ -256,7 +256,7 @@ func (h *InfluxDBV2Listener) handleWrite() http.HandlerFunc {
var readErr error var readErr error
var bytes []byte var bytes []byte
//body = http.MaxBytesReader(res, req.Body, 1000000) //p.MaxBodySize.Size) //body = http.MaxBytesReader(res, req.Body, 1000000) //p.MaxBodySize.Size)
bytes, readErr = ioutil.ReadAll(body) bytes, readErr = io.ReadAll(body)
if readErr != nil { if readErr != nil {
h.Log.Debugf("Error parsing the request body: %v", readErr.Error()) h.Log.Debugf("Error parsing the request body: %v", readErr.Error())
if err := badRequest(res, InternalError, readErr.Error()); err != nil { if err := badRequest(res, InternalError, readErr.Error()); err != nil {

View File

@ -5,9 +5,10 @@ import (
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"os"
"runtime" "runtime"
"strconv" "strconv"
"sync" "sync"
@ -363,7 +364,7 @@ func TestWriteGzippedData(t *testing.T) {
require.NoError(t, listener.Start(acc)) require.NoError(t, listener.Start(acc))
defer listener.Stop() defer listener.Stop()
data, err := ioutil.ReadFile("./testdata/testmsgs.gz") data, err := os.ReadFile("./testdata/testmsgs.gz")
require.NoError(t, err) require.NoError(t, err)
req, err := http.NewRequest("POST", createURL(listener, "http", "/api/v2/write", "bucket=mybucket"), bytes.NewBuffer(data)) req, err := http.NewRequest("POST", createURL(listener, "http", "/api/v2/write", "bucket=mybucket"), bytes.NewBuffer(data))
@ -485,7 +486,7 @@ func TestReady(t *testing.T) {
resp, err := http.Get(createURL(listener, "http", "/api/v2/ready", "")) resp, err := http.Get(createURL(listener, "http", "/api/v2/ready", ""))
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, "application/json", resp.Header["Content-Type"][0]) require.Equal(t, "application/json", resp.Header["Content-Type"][0])
bodyBytes, err := ioutil.ReadAll(resp.Body) bodyBytes, err := io.ReadAll(resp.Body)
require.NoError(t, err) require.NoError(t, err)
require.Contains(t, string(bodyBytes), "\"status\":\"ready\"") require.Contains(t, string(bodyBytes), "\"status\":\"ready\"")
require.NoError(t, resp.Body.Close()) require.NoError(t, resp.Body.Close())

View File

@ -8,7 +8,6 @@ import (
"encoding/binary" "encoding/binary"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -107,7 +106,7 @@ func (fs *fileServiceImpl) getStringsMatchingPatternOnPath(path string) ([]strin
// readFile reads file on path and return string content. // readFile reads file on path and return string content.
func (fs *fileServiceImpl) readFile(path string) ([]byte, error) { func (fs *fileServiceImpl) readFile(path string) ([]byte, error) {
out, err := ioutil.ReadFile(path) out, err := os.ReadFile(path)
if err != nil { if err != nil {
return make([]byte, 0), err return make([]byte, 0), err
} }
@ -116,7 +115,7 @@ func (fs *fileServiceImpl) readFile(path string) ([]byte, error) {
// readFileToFloat64 reads file on path and tries to parse content to float64. // readFileToFloat64 reads file on path and tries to parse content to float64.
func (fs *fileServiceImpl) readFileToFloat64(reader io.Reader) (float64, int64, error) { func (fs *fileServiceImpl) readFileToFloat64(reader io.Reader) (float64, int64, error) {
read, err := ioutil.ReadAll(reader) read, err := io.ReadAll(reader)
if err != nil { if err != nil {
return 0, 0, err return 0, 0, err
} }

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
@ -153,7 +153,7 @@ func (j *Jolokia) doRequest(req *http.Request) ([]map[string]interface{}, error)
} }
// read body // read body
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -2,7 +2,7 @@ package jolokia
import ( import (
_ "fmt" _ "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -116,7 +116,7 @@ type jolokiaClientStub struct {
func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) { func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) {
resp := http.Response{} resp := http.Response{}
resp.StatusCode = c.statusCode resp.StatusCode = c.statusCode
resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) resp.Body = io.NopCloser(strings.NewReader(c.responseBody))
return &resp, nil return &resp, nil
} }

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -149,7 +149,7 @@ func (c *Client) read(requests []ReadRequest) ([]ReadResponse, error) {
c.URL, resp.StatusCode, http.StatusText(resp.StatusCode), http.StatusOK, http.StatusText(http.StatusOK)) c.URL, resp.StatusCode, http.StatusText(resp.StatusCode), http.StatusOK, http.StatusText(http.StatusOK))
} }
responseBody, err := ioutil.ReadAll(resp.Body) responseBody, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -3,7 +3,7 @@ package jolokia2
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
@ -20,7 +20,7 @@ func TestJolokia2_ClientAuthRequest(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, _ = r.BasicAuth() username, password, _ = r.BasicAuth()
body, _ := ioutil.ReadAll(r.Body) body, _ := io.ReadAll(r.Body)
require.NoError(t, json.Unmarshal(body, &requests)) require.NoError(t, json.Unmarshal(body, &requests))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
@ -56,7 +56,7 @@ func TestJolokia2_ClientProxyAuthRequest(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
username, password, _ = r.BasicAuth() username, password, _ = r.BasicAuth()
body, _ := ioutil.ReadAll(r.Body) body, _ := io.ReadAll(r.Body)
require.NoError(t, json.Unmarshal(body, &requests)) require.NoError(t, json.Unmarshal(body, &requests))
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
_, err := fmt.Fprintf(w, "[]") _, err := fmt.Fprintf(w, "[]")

View File

@ -6,7 +6,6 @@ package kernel
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -41,7 +40,7 @@ func (k *Kernel) Gather(acc telegraf.Accumulator) error {
return err return err
} }
entropyData, err := ioutil.ReadFile(k.entropyStatFile) entropyData, err := os.ReadFile(k.entropyStatFile)
if err != nil { if err != nil {
return err return err
} }
@ -109,7 +108,7 @@ func (k *Kernel) getProcStat() ([]byte, error) {
return nil, err return nil, err
} }
data, err := ioutil.ReadFile(k.statFile) data, err := os.ReadFile(k.statFile)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,7 +4,6 @@
package kernel package kernel
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -169,7 +168,7 @@ const entropyStatFilePartial = `1024`
const entropyStatFileInvalid = `` const entropyStatFileInvalid = ``
func makeFakeStatFile(t *testing.T, content []byte) string { func makeFakeStatFile(t *testing.T, content []byte) string {
tmpfile, err := ioutil.TempFile("", "kernel_test") tmpfile, err := os.CreateTemp("", "kernel_test")
require.NoError(t, err) require.NoError(t, err)
_, err = tmpfile.Write(content) _, err = tmpfile.Write(content)

View File

@ -6,7 +6,6 @@ package kernel_vmstat
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"strconv" "strconv"
@ -61,7 +60,7 @@ func (k *KernelVmstat) getProcVmstat() ([]byte, error) {
return nil, err return nil, err
} }
data, err := ioutil.ReadFile(k.statFile) data, err := os.ReadFile(k.statFile)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,7 +4,6 @@
package kernel_vmstat package kernel_vmstat
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -300,7 +299,7 @@ thp_collapse_alloc_failed 102214
thp_split abcd` thp_split abcd`
func makeFakeVMStatFile(t *testing.T, content []byte) string { func makeFakeVMStatFile(t *testing.T, content []byte) string {
tmpfile, err := ioutil.TempFile("", "kernel_vmstat_test") tmpfile, err := os.CreateTemp("", "kernel_vmstat_test")
require.NoError(t, err) require.NoError(t, err)
_, err = tmpfile.Write(content) _, err = tmpfile.Write(content)

View File

@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
@ -253,7 +252,7 @@ func (k *Kibana) gatherJSONData(url string, v interface{}) (host string, err err
if response.StatusCode != http.StatusOK { if response.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(response.Body, 200)) body, _ := io.ReadAll(io.LimitReader(response.Body, 200))
return request.Host, fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body) return request.Host, fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body)
} }

View File

@ -1,7 +1,7 @@
package kibana package kibana
import ( import (
"io/ioutil" "io"
"net/http" "net/http"
"strings" "strings"
"testing" "testing"
@ -46,7 +46,7 @@ func (t *transportMock) RoundTrip(r *http.Request) (*http.Response, error) {
StatusCode: t.statusCode, StatusCode: t.statusCode,
} }
res.Header.Set("Content-Type", "application/json") res.Header.Set("Content-Type", "application/json")
res.Body = ioutil.NopCloser(strings.NewReader(t.body)) res.Body = io.NopCloser(strings.NewReader(t.body))
return res, nil return res, nil
} }

View File

@ -6,7 +6,7 @@ import (
"compress/zlib" "compress/zlib"
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"math/big" "math/big"
"strings" "strings"
"sync" "sync"
@ -349,7 +349,7 @@ func processGzip(data []byte) ([]byte, error) {
return nil, err return nil, err
} }
defer zipData.Close() defer zipData.Close()
return ioutil.ReadAll(zipData) return io.ReadAll(zipData)
} }
func processZlib(data []byte) ([]byte, error) { func processZlib(data []byte) ([]byte, error) {
@ -358,7 +358,7 @@ func processZlib(data []byte) ([]byte, error) {
return nil, err return nil, err
} }
defer zlibData.Close() defer zlibData.Close()
return ioutil.ReadAll(zlibData) return io.ReadAll(zlibData)
} }
func processNoOp(data []byte) ([]byte, error) { func processNoOp(data []byte) ([]byte, error) {

View File

@ -3,8 +3,8 @@ package kube_inventory
import ( import (
"context" "context"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"os"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -101,7 +101,7 @@ func (ki *KubernetesInventory) Init() error {
} }
if ki.BearerToken != "" { if ki.BearerToken != "" {
token, err := ioutil.ReadFile(ki.BearerToken) token, err := os.ReadFile(ki.BearerToken)
if err != nil { if err != nil {
return err return err
} }

View File

@ -3,8 +3,8 @@ package kubernetes
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"os"
"strings" "strings"
"time" "time"
@ -93,7 +93,7 @@ func (k *Kubernetes) Init() error {
} }
if k.BearerToken != "" { if k.BearerToken != "" {
token, err := ioutil.ReadFile(k.BearerToken) token, err := os.ReadFile(k.BearerToken)
if err != nil { if err != nil {
return err return err
} }

View File

@ -1,7 +1,6 @@
package leofs package leofs
import ( import (
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"runtime" "runtime"
@ -132,7 +131,7 @@ func testMain(t *testing.T, code string, endpoint string, serverType ServerType)
// Build the fake snmpwalk for test // Build the fake snmpwalk for test
src := os.TempDir() + "/test.go" src := os.TempDir() + "/test.go"
require.NoError(t, ioutil.WriteFile(src, []byte(code), 0600)) require.NoError(t, os.WriteFile(src, []byte(code), 0600))
defer os.Remove(src) defer os.Remove(src)
require.NoError(t, exec.Command("go", "build", "-o", executable, src).Run()) require.NoError(t, exec.Command("go", "build", "-o", executable, src).Run())

View File

@ -3,7 +3,6 @@ package linux_sysctl_fs
import ( import (
"bytes" "bytes"
"errors" "errors"
"io/ioutil"
"os" "os"
"strconv" "strconv"
@ -29,7 +28,7 @@ func (sfs SysctlFS) SampleConfig() string {
} }
func (sfs *SysctlFS) gatherList(file string, fields map[string]interface{}, fieldNames ...string) error { func (sfs *SysctlFS) gatherList(file string, fields map[string]interface{}, fieldNames ...string) error {
bs, err := ioutil.ReadFile(sfs.path + "/" + file) bs, err := os.ReadFile(sfs.path + "/" + file)
if err != nil { if err != nil {
// Ignore non-existing entries // Ignore non-existing entries
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
@ -58,7 +57,7 @@ func (sfs *SysctlFS) gatherList(file string, fields map[string]interface{}, fiel
} }
func (sfs *SysctlFS) gatherOne(name string, fields map[string]interface{}) error { func (sfs *SysctlFS) gatherOne(name string, fields map[string]interface{}) error {
bs, err := ioutil.ReadFile(sfs.path + "/" + name) bs, err := os.ReadFile(sfs.path + "/" + name)
if err != nil { if err != nil {
// Ignore non-existing entries // Ignore non-existing entries
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {

View File

@ -1,7 +1,6 @@
package linux_sysctl_fs package linux_sysctl_fs
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -10,16 +9,16 @@ import (
) )
func TestSysctlFSGather(t *testing.T) { func TestSysctlFSGather(t *testing.T) {
td, err := ioutil.TempDir("", "") td, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(td) defer os.RemoveAll(td)
require.NoError(t, ioutil.WriteFile(td+"/aio-nr", []byte("100\n"), 0644)) require.NoError(t, os.WriteFile(td+"/aio-nr", []byte("100\n"), 0644))
require.NoError(t, ioutil.WriteFile(td+"/aio-max-nr", []byte("101\n"), 0644)) require.NoError(t, os.WriteFile(td+"/aio-max-nr", []byte("101\n"), 0644))
require.NoError(t, ioutil.WriteFile(td+"/super-nr", []byte("102\n"), 0644)) require.NoError(t, os.WriteFile(td+"/super-nr", []byte("102\n"), 0644))
require.NoError(t, ioutil.WriteFile(td+"/super-max", []byte("103\n"), 0644)) require.NoError(t, os.WriteFile(td+"/super-max", []byte("103\n"), 0644))
require.NoError(t, ioutil.WriteFile(td+"/file-nr", []byte("104\t0\t106\n"), 0644)) require.NoError(t, os.WriteFile(td+"/file-nr", []byte("104\t0\t106\n"), 0644))
require.NoError(t, ioutil.WriteFile(td+"/inode-state", []byte("107\t108\t109\t0\t0\t0\t0\n"), 0644)) require.NoError(t, os.WriteFile(td+"/inode-state", []byte("107\t108\t109\t0\t0\t0\t0\n"), 0644))
sfs := &SysctlFS{ sfs := &SysctlFS{
path: td, path: td,

View File

@ -1,7 +1,6 @@
package logparser package logparser
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -111,7 +110,7 @@ func TestGrokParseLogFiles(t *testing.T) {
} }
func TestGrokParseLogFilesAppearLater(t *testing.T) { func TestGrokParseLogFilesAppearLater(t *testing.T) {
emptydir, err := ioutil.TempDir("", "TestGrokParseLogFilesAppearLater") emptydir, err := os.MkdirTemp("", "TestGrokParseLogFilesAppearLater")
defer os.RemoveAll(emptydir) defer os.RemoveAll(emptydir)
assert.NoError(t, err) assert.NoError(t, err)
@ -131,10 +130,10 @@ func TestGrokParseLogFilesAppearLater(t *testing.T) {
assert.Equal(t, acc.NFields(), 0) assert.Equal(t, acc.NFields(), 0)
input, err := ioutil.ReadFile(filepath.Join(testdataDir, "test_a.log")) input, err := os.ReadFile(filepath.Join(testdataDir, "test_a.log"))
assert.NoError(t, err) assert.NoError(t, err)
err = ioutil.WriteFile(filepath.Join(emptydir, "test_a.log"), input, 0644) err = os.WriteFile(filepath.Join(emptydir, "test_a.log"), input, 0644)
assert.NoError(t, err) assert.NoError(t, err)
assert.NoError(t, acc.GatherError(logparser.Gather)) assert.NoError(t, acc.GatherError(logparser.Gather))

View File

@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
@ -206,7 +205,7 @@ func (logstash *Logstash) gatherJSONData(url string, value interface{}) error {
defer response.Body.Close() defer response.Body.Close()
if response.StatusCode != http.StatusOK { if response.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(response.Body, 200)) body, _ := io.ReadAll(io.LimitReader(response.Body, 200))
return fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body) return fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body)
} }

View File

@ -8,7 +8,7 @@
package lustre2 package lustre2
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv" "strconv"
@ -374,7 +374,7 @@ func (l *Lustre2) GetLustreProcStats(fileglob string, wantedFields []*mapping) e
name := path[len(path)-2] name := path[len(path)-2]
//lines, err := internal.ReadLines(file) //lines, err := internal.ReadLines(file)
wholeFile, err := ioutil.ReadFile(file) wholeFile, err := os.ReadFile(file)
if err != nil { if err != nil {
return err return err
} }

View File

@ -4,7 +4,6 @@
package lustre2 package lustre2
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -149,13 +148,13 @@ func TestLustre2GeneratesMetrics(t *testing.T) {
err = os.MkdirAll(obddir+"/"+ostName, 0755) err = os.MkdirAll(obddir+"/"+ostName, 0755)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(mdtdir+"/"+ostName+"/md_stats", []byte(mdtProcContents), 0644) err = os.WriteFile(mdtdir+"/"+ostName+"/md_stats", []byte(mdtProcContents), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(osddir+"/"+ostName+"/stats", []byte(osdldiskfsProcContents), 0644) err = os.WriteFile(osddir+"/"+ostName+"/stats", []byte(osdldiskfsProcContents), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(obddir+"/"+ostName+"/stats", []byte(obdfilterProcContents), 0644) err = os.WriteFile(obddir+"/"+ostName+"/stats", []byte(obdfilterProcContents), 0644)
require.NoError(t, err) require.NoError(t, err)
// Begin by testing standard Lustre stats // Begin by testing standard Lustre stats
@ -218,10 +217,10 @@ func TestLustre2GeneratesJobstatsMetrics(t *testing.T) {
err = os.MkdirAll(obddir+"/"+ostName, 0755) err = os.MkdirAll(obddir+"/"+ostName, 0755)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(mdtdir+"/"+ostName+"/job_stats", []byte(mdtJobStatsContents), 0644) err = os.WriteFile(mdtdir+"/"+ostName+"/job_stats", []byte(mdtJobStatsContents), 0644)
require.NoError(t, err) require.NoError(t, err)
err = ioutil.WriteFile(obddir+"/"+ostName+"/job_stats", []byte(obdfilterJobStatsContents), 0644) err = os.WriteFile(obddir+"/"+ostName+"/job_stats", []byte(obdfilterJobStatsContents), 0644)
require.NoError(t, err) require.NoError(t, err)
// Test Lustre Jobstats // Test Lustre Jobstats

View File

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
@ -148,11 +147,11 @@ func runChimp(api *ChimpAPI, params ReportsParams) ([]byte, error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 200)) body, _ := io.ReadAll(io.LimitReader(resp.Body, 200))
return nil, fmt.Errorf("%s returned HTTP status %s: %q", api.url.String(), resp.Status, body) return nil, fmt.Errorf("%s returned HTTP status %s: %q", api.url.String(), resp.Status, body)
} }
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -20,7 +20,6 @@ package mdstat
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"regexp" "regexp"
"sort" "sort"
@ -291,7 +290,7 @@ func (k *MdstatConf) getProcMdstat() ([]byte, error) {
return nil, err return nil, err
} }
data, err := ioutil.ReadFile(mdStatFile) data, err := os.ReadFile(mdStatFile)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,7 +4,6 @@
package mdstat package mdstat
import ( import (
"io/ioutil"
"os" "os"
"testing" "testing"
@ -134,7 +133,7 @@ unused devices: <none>
` `
func makeFakeMDStatFile(content []byte) (filename string) { func makeFakeMDStatFile(content []byte) (filename string) {
fileobj, err := ioutil.TempFile("", "mdstat") fileobj, err := os.CreateTemp("", "mdstat")
if err != nil { if err != nil {
panic(err) panic(err)
} }

View File

@ -3,7 +3,7 @@ package mesos
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"io/ioutil" "io"
"log" "log"
"net" "net"
"net/http" "net/http"
@ -558,7 +558,7 @@ func (m *Mesos) gatherMainMetrics(u *url.URL, role Role, acc telegraf.Accumulato
return err return err
} }
data, err := ioutil.ReadAll(resp.Body) data, err := io.ReadAll(resp.Body)
// Ignore the returned error to not shadow the initial one // Ignore the returned error to not shadow the initial one
//nolint:errcheck,revive //nolint:errcheck,revive
resp.Body.Close() resp.Body.Close()

View File

@ -3,8 +3,8 @@ package multifile
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"math" "math"
"os"
"path" "path"
"strconv" "strconv"
"time" "time"
@ -84,7 +84,7 @@ func (m *MultiFile) Gather(acc telegraf.Accumulator) error {
tags := make(map[string]string) tags := make(map[string]string)
for _, file := range m.Files { for _, file := range m.Files {
fileContents, err := ioutil.ReadFile(file.Name) fileContents, err := os.ReadFile(file.Name)
if err != nil { if err != nil {
if m.FailEarly { if m.FailEarly {

View File

@ -5,7 +5,7 @@ package nats
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"path" "path"
@ -56,7 +56,7 @@ func (n *Nats) Gather(acc telegraf.Accumulator) error {
} }
defer resp.Body.Close() defer resp.Body.Close()
bytes, err := ioutil.ReadAll(resp.Body) bytes, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }

View File

@ -5,7 +5,7 @@ package neptuneapex
import ( import (
"encoding/xml" "encoding/xml"
"fmt" "fmt"
"io/ioutil" "io"
"math" "math"
"net/http" "net/http"
"strconv" "strconv"
@ -276,7 +276,7 @@ func (n *NeptuneApex) sendRequest(server string) ([]byte, error) {
url, resp.StatusCode, http.StatusText(resp.StatusCode), url, resp.StatusCode, http.StatusText(resp.StatusCode),
http.StatusOK, http.StatusText(http.StatusOK)) http.StatusOK, http.StatusText(http.StatusOK))
} }
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to read output from %q: %v", url, err) return nil, fmt.Errorf("unable to read output from %q: %v", url, err)
} }

View File

@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"net" "net"
"net/http" "net/http"
"net/url" "net/url"
@ -70,7 +70,7 @@ func (n *NginxPlusAPI) gatherURL(addr *url.URL, path string) ([]byte, error) {
contentType := strings.Split(resp.Header.Get("Content-Type"), ";")[0] contentType := strings.Split(resp.Header.Get("Content-Type"), ";")[0]
switch contentType { switch contentType {
case "application/json": case "application/json":
body, err := ioutil.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,7 +4,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
@ -153,7 +152,7 @@ func (check *NginxUpstreamCheck) gatherJSONData(url string, value interface{}) e
defer response.Body.Close() defer response.Body.Close()
if response.StatusCode != http.StatusOK { if response.StatusCode != http.StatusOK {
// ignore the err here; LimitReader returns io.EOF and we're not interested in read errors. // ignore the err here; LimitReader returns io.EOF and we're not interested in read errors.
body, _ := ioutil.ReadAll(io.LimitReader(response.Body, 200)) body, _ := io.ReadAll(io.LimitReader(response.Body, 200))
return fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body) return fmt.Errorf("%s returned HTTP status %s: %q", url, response.Status, body)
} }

View File

@ -25,7 +25,7 @@ package nsq
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"net/url" "net/url"
"strconv" "strconv"
@ -131,7 +131,7 @@ func (n *NSQ) gatherEndpoint(e string, acc telegraf.Accumulator) error {
return fmt.Errorf("%s returned HTTP status %s", u.String(), r.Status) return fmt.Errorf("%s returned HTTP status %s", u.String(), r.Status)
} }
body, err := ioutil.ReadAll(r.Body) body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
return fmt.Errorf(`error reading body: %s`, err) return fmt.Errorf(`error reading body: %s`, err)
} }

View File

@ -2,7 +2,6 @@ package nstat
import ( import (
"bytes" "bytes"
"io/ioutil"
"os" "os"
"strconv" "strconv"
@ -62,7 +61,7 @@ func (ns *Nstat) Gather(acc telegraf.Accumulator) error {
// load paths, get from env if config values are empty // load paths, get from env if config values are empty
ns.loadPaths() ns.loadPaths()
netstat, err := ioutil.ReadFile(ns.ProcNetNetstat) netstat, err := os.ReadFile(ns.ProcNetNetstat)
if err != nil { if err != nil {
return err return err
} }
@ -71,14 +70,14 @@ func (ns *Nstat) Gather(acc telegraf.Accumulator) error {
ns.gatherNetstat(netstat, acc) ns.gatherNetstat(netstat, acc)
// collect SNMP data // collect SNMP data
snmp, err := ioutil.ReadFile(ns.ProcNetSNMP) snmp, err := os.ReadFile(ns.ProcNetSNMP)
if err != nil { if err != nil {
return err return err
} }
ns.gatherSNMP(snmp, acc) ns.gatherSNMP(snmp, acc)
// collect SNMP6 data, if SNMP6 directory exists (IPv6 enabled) // collect SNMP6 data, if SNMP6 directory exists (IPv6 enabled)
snmp6, err := ioutil.ReadFile(ns.ProcNetSNMP6) snmp6, err := os.ReadFile(ns.ProcNetSNMP6)
if err == nil { if err == nil {
ns.gatherSNMP6(snmp6, acc) ns.gatherSNMP6(snmp6, acc)
} else if !os.IsNotExist(err) { } else if !os.IsNotExist(err) {

View File

@ -1,7 +1,7 @@
package nvidia_smi package nvidia_smi
import ( import (
"io/ioutil" "os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
@ -139,7 +139,7 @@ func TestGatherValidXML(t *testing.T) {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
var acc testutil.Accumulator var acc testutil.Accumulator
octets, err := ioutil.ReadFile(filepath.Join("testdata", tt.filename)) octets, err := os.ReadFile(filepath.Join("testdata", tt.filename))
require.NoError(t, err) require.NoError(t, err)
err = gatherNvidiaSMI(octets, &acc) err = gatherNvidiaSMI(octets, &acc)

View File

@ -9,7 +9,6 @@ import (
"crypto/x509/pkix" "crypto/x509/pkix"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil"
"log" "log"
"math/big" "math/big"
"net" "net"
@ -27,7 +26,7 @@ import (
// SELF SIGNED CERT FUNCTIONS // SELF SIGNED CERT FUNCTIONS
func newTempDir() (string, error) { func newTempDir() (string, error) {
dir, err := ioutil.TempDir("", "ssc") dir, err := os.MkdirTemp("", "ssc")
return dir, err return dir, err
} }

View File

@ -2,7 +2,6 @@ package passenger
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -28,7 +27,7 @@ func fakePassengerStatus(stat string) (string, error) {
} }
tempFilePath := filepath.Join(os.TempDir(), "passenger-status"+fileExtension) tempFilePath := filepath.Join(os.TempDir(), "passenger-status"+fileExtension)
if err := ioutil.WriteFile(tempFilePath, []byte(content), 0700); err != nil { if err := os.WriteFile(tempFilePath, []byte(content), 0700); err != nil {
return "", err return "", err
} }

View File

@ -10,7 +10,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"net" "net"
"net/http" "net/http"
"net/http/cgi" "net/http/cgi"
@ -161,7 +160,7 @@ func (c *child) serve() {
var errCloseConn = errors.New("fcgi: connection should be closed") var errCloseConn = errors.New("fcgi: connection should be closed")
var emptyBody = ioutil.NopCloser(strings.NewReader("")) var emptyBody = io.NopCloser(strings.NewReader(""))
// ErrRequestAborted is returned by Read when a handler attempts to read the // ErrRequestAborted is returned by Read when a handler attempts to read the
// body of a request that has been aborted by the web server. // body of a request that has been aborted by the web server.
@ -295,7 +294,7 @@ func (c *child) serveRequest(req *request, body io.ReadCloser) {
// can properly cut off the client sending all the data. // can properly cut off the client sending all the data.
// For now just bound it a little and // For now just bound it a little and
//nolint:errcheck,revive //nolint:errcheck,revive
io.CopyN(ioutil.Discard, body, 100<<20) io.CopyN(io.Discard, body, 100<<20)
//nolint:errcheck,revive //nolint:errcheck,revive
body.Close() body.Close()

View File

@ -8,7 +8,6 @@ import (
"bytes" "bytes"
"errors" "errors"
"io" "io"
"io/ioutil"
"net/http" "net/http"
"testing" "testing"
) )
@ -242,7 +241,7 @@ func TestChildServeCleansUp(t *testing.T) {
r *http.Request, r *http.Request,
) { ) {
// block on reading body of request // block on reading body of request
_, err := io.Copy(ioutil.Discard, r.Body) _, err := io.Copy(io.Discard, r.Body)
if err != tt.err { if err != tt.err {
t.Errorf("Expected %#v, got %#v", tt.err, err) t.Errorf("Expected %#v, got %#v", tt.err, err)
} }
@ -274,7 +273,7 @@ func TestMalformedParams(_ *testing.T) {
// end of params // end of params
1, 4, 0, 1, 0, 0, 0, 0, 1, 4, 0, 1, 0, 0, 0, 0,
} }
rw := rwNopCloser{bytes.NewReader(input), ioutil.Discard} rw := rwNopCloser{bytes.NewReader(input), io.Discard}
c := newChild(rw, http.DefaultServeMux) c := newChild(rw, http.DefaultServeMux)
c.serve() c.serve()
} }

View File

@ -4,7 +4,6 @@
package postfix package postfix
import ( import (
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -15,7 +14,7 @@ import (
) )
func TestGather(t *testing.T) { func TestGather(t *testing.T) {
td, err := ioutil.TempDir("", "") td, err := os.MkdirTemp("", "")
require.NoError(t, err) require.NoError(t, err)
defer os.RemoveAll(td) defer os.RemoveAll(td)
@ -23,12 +22,12 @@ func TestGather(t *testing.T) {
require.NoError(t, os.MkdirAll(filepath.FromSlash(td+"/"+q), 0755)) require.NoError(t, os.MkdirAll(filepath.FromSlash(td+"/"+q), 0755))
} }
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/active/01"), []byte("abc"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/active/01"), []byte("abc"), 0644))
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/active/02"), []byte("defg"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/active/02"), []byte("defg"), 0644))
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/hold/01"), []byte("abc"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/hold/01"), []byte("abc"), 0644))
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/incoming/01"), []byte("abcd"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/incoming/01"), []byte("abcd"), 0644))
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/deferred/0/0/01"), []byte("abc"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/deferred/0/0/01"), []byte("abc"), 0644))
require.NoError(t, ioutil.WriteFile(filepath.FromSlash(td+"/deferred/F/F/F1"), []byte("abc"), 0644)) require.NoError(t, os.WriteFile(filepath.FromSlash(td+"/deferred/F/F/F1"), []byte("abc"), 0644))
p := Postfix{ p := Postfix{
QueueDirectory: td, QueueDirectory: td,

View File

@ -3,7 +3,7 @@ package postgresql_extensible
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"strings" "strings"
"time" "time"
@ -147,7 +147,7 @@ func ReadQueryFromFile(filePath string) (string, error) {
} }
defer file.Close() defer file.Close()
query, err := ioutil.ReadAll(file) query, err := io.ReadAll(file)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -6,7 +6,6 @@ package processes
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
@ -192,7 +191,7 @@ func (p *Processes) gatherFromProc(fields map[string]interface{}) error {
} }
func readProcFile(filename string) ([]byte, error) { func readProcFile(filename string) ([]byte, error) {
data, err := ioutil.ReadFile(filename) data, err := os.ReadFile(filename)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil, nil return nil, nil

View File

@ -2,7 +2,7 @@ package procstat
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -43,7 +43,7 @@ func (pg *NativeFinder) UID(user string) ([]PID, error) {
//PidFile returns the pid from the pid file given. //PidFile returns the pid from the pid file given.
func (pg *NativeFinder) PidFile(path string) ([]PID, error) { func (pg *NativeFinder) PidFile(path string) ([]PID, error) {
var pids []PID var pids []PID
pidString, err := ioutil.ReadFile(path) pidString, err := os.ReadFile(path)
if err != nil { if err != nil {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err) path, err)

View File

@ -2,7 +2,7 @@ package procstat
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
@ -25,7 +25,7 @@ func NewPgrep() (PIDFinder, error) {
func (pg *Pgrep) PidFile(path string) ([]PID, error) { func (pg *Pgrep) PidFile(path string) ([]PID, error) {
var pids []PID var pids []PID
pidString, err := ioutil.ReadFile(path) pidString, err := os.ReadFile(path)
if err != nil { if err != nil {
return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", return pids, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'",
path, err) path, err)

Some files were not shown because too many files have changed in this diff Show More