Remove ioutil (#2438)

Signed-off-by: inosato <si17_21@yahoo.co.jp>
This commit is contained in:
inosato 2022-07-28 03:59:39 +09:00 committed by GitHub
parent 73dabdfe9e
commit 9ed32666cc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 36 additions and 39 deletions

View file

@ -19,7 +19,6 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
@ -76,21 +75,21 @@ func (c *bondingCollector) Update(ch chan<- prometheus.Metric) error {
func readBondingStats(root string) (status map[string][2]int, err error) { func readBondingStats(root string) (status map[string][2]int, err error) {
status = map[string][2]int{} status = map[string][2]int{}
masters, err := ioutil.ReadFile(filepath.Join(root, "bonding_masters")) masters, err := os.ReadFile(filepath.Join(root, "bonding_masters"))
if err != nil { if err != nil {
return nil, err return nil, err
} }
for _, master := range strings.Fields(string(masters)) { for _, master := range strings.Fields(string(masters)) {
slaves, err := ioutil.ReadFile(filepath.Join(root, master, "bonding", "slaves")) slaves, err := os.ReadFile(filepath.Join(root, master, "bonding", "slaves"))
if err != nil { if err != nil {
return nil, err return nil, err
} }
sstat := [2]int{0, 0} sstat := [2]int{0, 0}
for _, slave := range strings.Fields(string(slaves)) { for _, slave := range strings.Fields(string(slaves)) {
state, err := ioutil.ReadFile(filepath.Join(root, master, fmt.Sprintf("lower_%s", slave), "bonding_slave", "mii_status")) state, err := os.ReadFile(filepath.Join(root, master, fmt.Sprintf("lower_%s", slave), "bonding_slave", "mii_status"))
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
// some older? kernels use slave_ prefix // some older? kernels use slave_ prefix
state, err = ioutil.ReadFile(filepath.Join(root, master, fmt.Sprintf("slave_%s", slave), "bonding_slave", "mii_status")) state, err = os.ReadFile(filepath.Join(root, master, fmt.Sprintf("slave_%s", slave), "bonding_slave", "mii_status"))
} }
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -19,7 +19,7 @@ package collector
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"strconv" "strconv"
@ -73,7 +73,7 @@ func parseFileFDStats(filename string) (map[string]string, error) {
} }
defer file.Close() defer file.Close()
content, err := ioutil.ReadAll(file) content, err := io.ReadAll(file)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -14,14 +14,14 @@
package collector package collector
import ( import (
"io/ioutil" "os"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
) )
func readUintFromFile(path string) (uint64, error) { func readUintFromFile(path string) (uint64, error) {
data, err := ioutil.ReadFile(path) data, err := os.ReadFile(path)
if err != nil { if err != nil {
return 0, err return 0, err
} }

View file

@ -18,7 +18,6 @@ package collector
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -78,7 +77,7 @@ func addValueFile(data map[string]map[string]string, sensor string, prop string,
data[sensor][prop] = value data[sensor][prop] = value
} }
// sysReadFile is a simplified ioutil.ReadFile that invokes syscall.Read directly. // sysReadFile is a simplified os.ReadFile that invokes syscall.Read directly.
func sysReadFile(file string) ([]byte, error) { func sysReadFile(file string) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
@ -87,7 +86,7 @@ func sysReadFile(file string) ([]byte, error) {
defer f.Close() defer f.Close()
// On some machines, hwmon drivers are broken and return EAGAIN. This causes // On some machines, hwmon drivers are broken and return EAGAIN. This causes
// Go's ioutil.ReadFile implementation to poll forever. // Go's os.ReadFile implementation to poll forever.
// //
// Since we either want to read data or bail immediately, do the simplest // Since we either want to read data or bail immediately, do the simplest
// possible read using system call directly. // possible read using system call directly.
@ -128,7 +127,7 @@ func explodeSensorFilename(filename string) (ok bool, sensorType string, sensorN
} }
func collectSensorData(dir string, data map[string]map[string]string) error { func collectSensorData(dir string, data map[string]map[string]string) error {
sensorFiles, dirError := ioutil.ReadDir(dir) sensorFiles, dirError := os.ReadDir(dir)
if dirError != nil { if dirError != nil {
return dirError return dirError
} }
@ -374,7 +373,7 @@ func (c *hwMonCollector) hwmonName(dir string) (string, error) {
} }
// preference 2: is there a name file // preference 2: is there a name file
sysnameRaw, nameErr := ioutil.ReadFile(filepath.Join(dir, "name")) sysnameRaw, nameErr := os.ReadFile(filepath.Join(dir, "name"))
if nameErr == nil && string(sysnameRaw) != "" { if nameErr == nil && string(sysnameRaw) != "" {
cleanName := cleanMetricName(string(sysnameRaw)) cleanName := cleanMetricName(string(sysnameRaw))
if cleanName != "" { if cleanName != "" {
@ -402,7 +401,7 @@ func (c *hwMonCollector) hwmonName(dir string) (string, error) {
// hwmonHumanReadableChipName is similar to the methods in hwmonName, but with // hwmonHumanReadableChipName is similar to the methods in hwmonName, but with
// different precedences -- we can allow duplicates here. // different precedences -- we can allow duplicates here.
func (c *hwMonCollector) hwmonHumanReadableChipName(dir string) (string, error) { func (c *hwMonCollector) hwmonHumanReadableChipName(dir string) (string, error) {
sysnameRaw, nameErr := ioutil.ReadFile(filepath.Join(dir, "name")) sysnameRaw, nameErr := os.ReadFile(filepath.Join(dir, "name"))
if nameErr != nil { if nameErr != nil {
return "", nameErr return "", nameErr
} }
@ -423,7 +422,7 @@ func (c *hwMonCollector) Update(ch chan<- prometheus.Metric) error {
hwmonPathName := filepath.Join(sysFilePath("class"), "hwmon") hwmonPathName := filepath.Join(sysFilePath("class"), "hwmon")
hwmonFiles, err := ioutil.ReadDir(hwmonPathName) hwmonFiles, err := os.ReadDir(hwmonPathName)
if err != nil { if err != nil {
if errors.Is(err, os.ErrNotExist) { if errors.Is(err, os.ErrNotExist) {
level.Debug(c.logger).Log("msg", "hwmon collector metrics are not available for this system") level.Debug(c.logger).Log("msg", "hwmon collector metrics are not available for this system")
@ -435,15 +434,16 @@ func (c *hwMonCollector) Update(ch chan<- prometheus.Metric) error {
for _, hwDir := range hwmonFiles { for _, hwDir := range hwmonFiles {
hwmonXPathName := filepath.Join(hwmonPathName, hwDir.Name()) hwmonXPathName := filepath.Join(hwmonPathName, hwDir.Name())
fileInfo, _ := os.Lstat(hwmonXPathName)
if hwDir.Mode()&os.ModeSymlink > 0 { if fileInfo.Mode()&os.ModeSymlink > 0 {
hwDir, err = os.Stat(hwmonXPathName) fileInfo, err = os.Stat(hwmonXPathName)
if err != nil { if err != nil {
continue continue
} }
} }
if !hwDir.IsDir() { if !fileInfo.IsDir() {
continue continue
} }

View file

@ -16,9 +16,9 @@ package collector
import ( import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"strings" "strings"
"testing" "testing"
@ -189,7 +189,7 @@ func TestIPVSCollectorResponse(t *testing.T) {
rw := httptest.NewRecorder() rw := httptest.NewRecorder()
promhttp.InstrumentMetricHandler(registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{})).ServeHTTP(rw, &http.Request{}) promhttp.InstrumentMetricHandler(registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{})).ServeHTTP(rw, &http.Request{})
wantMetrics, err := ioutil.ReadFile(test.metricsFile) wantMetrics, err := os.ReadFile(test.metricsFile)
if err != nil { if err != nil {
t.Fatalf("unable to read input test file %s: %s", test.metricsFile, err) t.Fatalf("unable to read input test file %s: %s", test.metricsFile, err)
} }

View file

@ -18,14 +18,14 @@ package collector
import ( import (
"fmt" "fmt"
"io/ioutil" "os"
"strconv" "strconv"
"strings" "strings"
) )
// Read loadavg from /proc. // Read loadavg from /proc.
func getLoad() (loads []float64, err error) { func getLoad() (loads []float64, err error) {
data, err := ioutil.ReadFile(procFilePath("loadavg")) data, err := os.ReadFile(procFilePath("loadavg"))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -17,7 +17,7 @@
package collector package collector
import ( import (
"io/ioutil" "os"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -29,7 +29,7 @@ import (
) )
func canTestPerf(t *testing.T) { func canTestPerf(t *testing.T) {
paranoidBytes, err := ioutil.ReadFile("/proc/sys/kernel/perf_event_paranoid") paranoidBytes, err := os.ReadFile("/proc/sys/kernel/perf_event_paranoid")
if err != nil { if err != nil {
t.Skip("Procfs not mounted, skipping perf tests") t.Skip("Procfs not mounted, skipping perf tests")
} }

View file

@ -19,7 +19,7 @@ package collector
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "os"
"path/filepath" "path/filepath"
"github.com/ema/qdisc" "github.com/ema/qdisc"
@ -100,7 +100,7 @@ func NewQdiscStatCollector(logger log.Logger) (Collector, error) {
func testQdiscGet(fixtures string) ([]qdisc.QdiscInfo, error) { func testQdiscGet(fixtures string) ([]qdisc.QdiscInfo, error) {
var res []qdisc.QdiscInfo var res []qdisc.QdiscInfo
b, err := ioutil.ReadFile(filepath.Join(fixtures, "results.json")) b, err := os.ReadFile(filepath.Join(fixtures, "results.json"))
if err != nil { if err != nil {
return res, err return res, err
} }

View file

@ -18,7 +18,6 @@ package collector
import ( import (
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"sort" "sort"
@ -196,13 +195,13 @@ func (c *textFileCollector) Update(ch chan<- prometheus.Metric) error {
paths, err := filepath.Glob(c.path) paths, err := filepath.Glob(c.path)
if err != nil || len(paths) == 0 { if err != nil || len(paths) == 0 {
// not glob or not accessible path either way assume single // not glob or not accessible path either way assume single
// directory and let ioutil.ReadDir handle it // directory and let os.ReadDir handle it
paths = []string{c.path} paths = []string{c.path}
} }
mtimes := make(map[string]time.Time) mtimes := make(map[string]time.Time)
for _, path := range paths { for _, path := range paths {
files, err := ioutil.ReadDir(path) files, err := os.ReadDir(path)
if err != nil && path != "" { if err != nil && path != "" {
errored = true errored = true
level.Error(c.logger).Log("msg", "failed to read textfile collector directory", "path", path, "err", err) level.Error(c.logger).Log("msg", "failed to read textfile collector directory", "path", path, "err", err)

View file

@ -15,9 +15,9 @@ package collector
import ( import (
"fmt" "fmt"
"io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os"
"testing" "testing"
"github.com/go-kit/log" "github.com/go-kit/log"
@ -120,7 +120,7 @@ func TestTextfileCollector(t *testing.T) {
promhttp.HandlerFor(registry, promhttp.HandlerOpts{}).ServeHTTP(rw, &http.Request{}) promhttp.HandlerFor(registry, promhttp.HandlerOpts{}).ServeHTTP(rw, &http.Request{})
got := string(rw.Body.String()) got := string(rw.Body.String())
want, err := ioutil.ReadFile(test.out) want, err := os.ReadFile(test.out)
if err != nil { if err != nil {
t.Fatalf("%d. error reading fixture file %s: %s", i, test.out, err) t.Fatalf("%d. error reading fixture file %s: %s", i, test.out, err)
} }

View file

@ -20,7 +20,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
@ -366,7 +365,7 @@ type mockWifiStater struct {
} }
func (s *mockWifiStater) unmarshalJSONFile(filename string, v interface{}) error { func (s *mockWifiStater) unmarshalJSONFile(filename string, v interface{}) error {
b, err := ioutil.ReadFile(filepath.Join(s.fixtures, filename)) b, err := os.ReadFile(filepath.Join(s.fixtures, filename))
if err != nil { if err != nil {
return err return err
} }

View file

@ -15,7 +15,7 @@ package main
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
@ -84,17 +84,17 @@ func TestHandlingOfDuplicatedMetrics(t *testing.T) {
t.Skipf("node_exporter binary not available, try to run `make build` first: %s", err) t.Skipf("node_exporter binary not available, try to run `make build` first: %s", err)
} }
dir, err := ioutil.TempDir("", "node-exporter") dir, err := os.MkdirTemp("", "node-exporter")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(dir) defer os.RemoveAll(dir)
content := []byte("dummy_metric 1\n") content := []byte("dummy_metric 1\n")
if err := ioutil.WriteFile(filepath.Join(dir, "a.prom"), content, 0600); err != nil { if err := os.WriteFile(filepath.Join(dir, "a.prom"), content, 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := ioutil.WriteFile(filepath.Join(dir, "b.prom"), content, 0600); err != nil { if err := os.WriteFile(filepath.Join(dir, "b.prom"), content, 0600); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -113,7 +113,7 @@ func queryExporter(address string) error {
if err != nil { if err != nil {
return err return err
} }
b, err := ioutil.ReadAll(resp.Body) b, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return err return err
} }