From 771edc246c7b300cf97d31e710c3ba2975898140 Mon Sep 17 00:00:00 2001 From: yseto Date: Wed, 31 Aug 2022 18:09:08 +0900 Subject: [PATCH 1/8] replace ioutil --- command/command_test.go | 5 ++--- config/config.go | 3 +-- config/config_test.go | 9 ++++----- do_init.go | 5 ++--- do_init_test.go | 5 ++--- mackerel/check_test.go | 4 ++-- main_test.go | 19 +++++++++---------- metadata/metadata.go | 5 ++--- metrics/linux/disk.go | 4 ++-- pidfile/pid_darwin.go | 8 ++++---- pidfile/pid_unix.go | 3 +-- pidfile/pidfile.go | 3 +-- pidfile/pidfile_test.go | 7 +++---- spec/cloud.go | 15 +++++++-------- spec/isec2_linux.go | 4 ++-- spec/isec2_linux_test.go | 3 +-- spec/linux/block_device.go | 7 +++---- start_test.go | 3 +-- wix/replace/replace_windows.go | 5 ++--- 19 files changed, 51 insertions(+), 66 deletions(-) diff --git a/command/command_test.go b/command/command_test.go index fc2b8edb2..b25f32165 100644 --- a/command/command_test.go +++ b/command/command_test.go @@ -3,7 +3,6 @@ package command import ( "encoding/json" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -90,7 +89,7 @@ func newMockAPIServer(t *testing.T) (config.Config, map[string]func(*http.Reques fmt.Fprint(w, string(respJSON)) })) - root, err := ioutil.TempDir("", "mackerel-agent-test") + root, err := os.MkdirTemp("", "mackerel-agent-test") if err != nil { t.Fatal(err) } @@ -176,7 +175,7 @@ func TestPrepareWithCreateWithFail(t *testing.T) { func TestPrepareWithUpdate(t *testing.T) { conf, mockHandlers, ts, deferFunc := newMockAPIServer(t) defer deferFunc() - tempDir, _ := ioutil.TempDir("", "") + tempDir, _ := os.MkdirTemp("", "") conf.Root = tempDir conf.SaveHostID("xxx12345678901") diff --git a/config/config.go b/config/config.go index 77e58432d..87e88e696 100644 --- a/config/config.go +++ b/config/config.go @@ -2,7 +2,6 @@ package config import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -582,7 +581,7 @@ func (s FileSystemHostIDStorage) HostIDFile() string { // LoadHostID loads the current host ID from the mackerel-agent's id file. func (s FileSystemHostIDStorage) LoadHostID() (string, error) { - content, err := ioutil.ReadFile(s.HostIDFile()) + content, err := os.ReadFile(s.HostIDFile()) if err != nil { return "", err } diff --git a/config/config_test.go b/config/config_test.go index 636ae20b2..cc69b0aec 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -2,7 +2,6 @@ package config import ( "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -582,7 +581,7 @@ var tomlQuotedReplacer = strings.NewReplacer( ) func TestLoadConfigFileInclude(t *testing.T) { - configDir, err := ioutil.TempDir("", "mackerel-config-test") + configDir, err := os.MkdirTemp("", "mackerel-config-test") assertNoError(t, err) defer os.RemoveAll(configDir) @@ -639,7 +638,7 @@ command = "bar" } func TestLoadConfigFileIncludeOverwritten(t *testing.T) { - configDir, err := ioutil.TempDir("", "mackerel-config-test") + configDir, err := os.MkdirTemp("", "mackerel-config-test") assertNoError(t, err) defer os.RemoveAll(configDir) @@ -680,7 +679,7 @@ verbose = true } func TestFileSystemHostIDStorage(t *testing.T) { - root, err := ioutil.TempDir("", "mackerel-agent-test") + root, err := os.MkdirTemp("", "mackerel-agent-test") if err != nil { t.Fatal(err) } @@ -880,7 +879,7 @@ env = { "SAMPLE_KEY1" = " foo bar ", "SAMPLE_KEY2" = " baz qux " } } func newTempFileWithContent(content string) (*os.File, error) { - tmpf, err := ioutil.TempFile("", "mackerel-config-test") + tmpf, err := os.CreateTemp("", "mackerel-config-test") if err != nil { return nil, err } diff --git a/do_init.go b/do_init.go index 26db84f16..7de246880 100644 --- a/do_init.go +++ b/do_init.go @@ -3,7 +3,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "os" "path/filepath" @@ -47,13 +46,13 @@ func doInitialize(fs *flag.FlagSet, argv []string) error { } contents := []byte(fmt.Sprintf("apikey = %q\n", *apikey)) if confExists { - cBytes, err := ioutil.ReadFile(*conffile) + cBytes, err := os.ReadFile(*conffile) if err != nil { return err } contents = append(contents, cBytes...) } - return ioutil.WriteFile(*conffile, contents, 0644) + return os.WriteFile(*conffile, contents, 0644) } type apikeyAlreadySetError string diff --git a/do_init_test.go b/do_init_test.go index 598f8a7ae..9780a4939 100644 --- a/do_init_test.go +++ b/do_init_test.go @@ -2,7 +2,6 @@ package main import ( "flag" - "io/ioutil" "os" "path/filepath" "strings" @@ -17,7 +16,7 @@ func TestDoInitialize(t *testing.T) { } } - root, err := ioutil.TempDir("", "mackerel-config-test") + root, err := os.MkdirTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary dir for test") } @@ -41,7 +40,7 @@ func TestDoInitialize(t *testing.T) { if err != nil { t.Errorf("err should be nil but: %s", err) } - content, _ := ioutil.ReadFile(conffile) + content, _ := os.ReadFile(conffile) if string(content) != `apikey = "hoge"`+"\n" { t.Errorf("somthing went wrong: %s", string(content)) } diff --git a/mackerel/check_test.go b/mackerel/check_test.go index 0d97d971f..18e1ee8ce 100644 --- a/mackerel/check_test.go +++ b/mackerel/check_test.go @@ -3,7 +3,7 @@ package mackerel import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "reflect" @@ -22,7 +22,7 @@ func TestReportCheckMonitors(t *testing.T) { t.Error("request method should be POST but :", req.Method) } - body, _ := ioutil.ReadAll(req.Body) + body, _ := io.ReadAll(req.Body) content := string(body) type testrepo struct { Source map[string]string `json:"source"` diff --git a/main_test.go b/main_test.go index 9792e14b1..256e46c58 100644 --- a/main_test.go +++ b/main_test.go @@ -3,7 +3,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "math" "os" "os/signal" @@ -18,7 +17,7 @@ import ( func TestParseFlags(t *testing.T) { // prepare dummy config - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") @@ -60,7 +59,7 @@ diagnostic=false func TestDetectForce(t *testing.T) { // prepare dummy config - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") } @@ -90,7 +89,7 @@ func TestDetectForce(t *testing.T) { } func TestResolveConfigForRetire(t *testing.T) { - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") } @@ -123,7 +122,7 @@ func TestResolveConfigForRetire(t *testing.T) { } func TestCreateAndRemovePidFile(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") if err != nil { t.Errorf("failed to create tmpfile, %s", err) } @@ -141,7 +140,7 @@ func TestCreateAndRemovePidFile(t *testing.T) { } pidfile.Remove(fpath) - ioutil.WriteFile(fpath, []byte(fmt.Sprint(math.MaxInt32)), 0644) + os.WriteFile(fpath, []byte(fmt.Sprint(math.MaxInt32)), 0644) if err := pidfile.Create(fpath); err != nil { t.Errorf("old pid file should be ignored and new pid file should be created but, %s", err) } @@ -204,7 +203,7 @@ func TestNotifyUpdateFileDelete(t *testing.T) { signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGHUP) go signalHandler(c, app, termCh) - f, err := ioutil.TempFile("", "mackerel-agent.test.*") + f, err := os.CreateTemp("", "mackerel-agent.test.*") if err != nil { t.Fatalf("can't create a temporary file: %v", err) } @@ -266,7 +265,7 @@ func TestConfigProxy(t *testing.T) { func TestConfigTestOK(t *testing.T) { // prepare dummy config - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") } @@ -286,7 +285,7 @@ func TestConfigTestOK(t *testing.T) { func TestConfigTestNotFound(t *testing.T) { // prepare dummy config - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") } @@ -306,7 +305,7 @@ func TestConfigTestNotFound(t *testing.T) { func TestConfigTestInvalidFormat(t *testing.T) { // prepare dummy config - confFile, err := ioutil.TempFile("", "mackerel-config-test") + confFile, err := os.CreateTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary config file for test") } diff --git a/metadata/metadata.go b/metadata/metadata.go index 9a4879789..aa2b9f056 100644 --- a/metadata/metadata.go +++ b/metadata/metadata.go @@ -3,7 +3,6 @@ package metadata import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -59,7 +58,7 @@ func (g *Generator) IsChanged(metadata interface{}) bool { // LoadFromFile loads the previous metadata from file func (g *Generator) LoadFromFile() { - data, err := ioutil.ReadFile(g.Cachefile) + data, err := os.ReadFile(g.Cachefile) if err != nil { // maybe initial state return } @@ -100,7 +99,7 @@ func (g *Generator) Clear() error { // writeFileAtomically writes contents to the file atomically func writeFileAtomically(f string, contents []byte) error { // MUST be located on same disk partition - tmpf, err := ioutil.TempFile(filepath.Dir(f), "tmp") + tmpf, err := os.CreateTemp(filepath.Dir(f), "tmp") if err != nil { return err } diff --git a/metrics/linux/disk.go b/metrics/linux/disk.go index 33ea7d593..53b06ff6f 100644 --- a/metrics/linux/disk.go +++ b/metrics/linux/disk.go @@ -7,7 +7,7 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" + "os" "regexp" "strconv" "strings" @@ -87,7 +87,7 @@ func (g *DiskGenerator) Generate() (metrics.Values, error) { } func (g *DiskGenerator) collectDiskstatValues() (metrics.Values, error) { - out, err := ioutil.ReadFile("/proc/diskstats") + out, err := os.ReadFile("/proc/diskstats") if err != nil { diskLogger.Errorf("Failed (skip these metrics): %s", err) return nil, err diff --git a/pidfile/pid_darwin.go b/pidfile/pid_darwin.go index 5dfe2350d..c9632e368 100644 --- a/pidfile/pid_darwin.go +++ b/pidfile/pid_darwin.go @@ -3,7 +3,7 @@ package pidfile import ( "bytes" "fmt" - "io/ioutil" + "io" "os/exec" "path/filepath" "strings" @@ -11,8 +11,8 @@ import ( func existsPid(pid int) bool { cmd := exec.Command("/usr/sbin/lsof", "-p", fmt.Sprint(pid)) - cmd.Stdout = ioutil.Discard - cmd.Stderr = ioutil.Discard + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard err := cmd.Run() return err == nil @@ -23,7 +23,7 @@ func getCmdName(pid int) string { var stdout bytes.Buffer cmd.Stdout = &stdout - cmd.Stderr = ioutil.Discard + cmd.Stderr = io.Discard err := cmd.Run() if err != nil { diff --git a/pidfile/pid_unix.go b/pidfile/pid_unix.go index 2e54549f0..cae8f71a6 100644 --- a/pidfile/pid_unix.go +++ b/pidfile/pid_unix.go @@ -5,7 +5,6 @@ package pidfile import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -17,7 +16,7 @@ func existsPid(pid int) bool { } func getCmdName(pid int) string { - cnt, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) + cnt, err := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", pid)) if err != nil { return "" } diff --git a/pidfile/pidfile.go b/pidfile/pidfile.go index 35ea1b78c..0ad78ae8e 100644 --- a/pidfile/pidfile.go +++ b/pidfile/pidfile.go @@ -2,7 +2,6 @@ package pidfile import ( "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -17,7 +16,7 @@ func Create(pidfile string) error { if pidfile == "" { return nil } - if pidString, err := ioutil.ReadFile(pidfile); err == nil { + if pidString, err := os.ReadFile(pidfile); err == nil { if pid, err := strconv.Atoi(string(pidString)); err == nil { if pid == os.Getpid() { return nil diff --git a/pidfile/pidfile_test.go b/pidfile/pidfile_test.go index a1d4d0ff2..76ef73ec9 100644 --- a/pidfile/pidfile_test.go +++ b/pidfile/pidfile_test.go @@ -4,7 +4,6 @@ package pidfile import ( - "io/ioutil" "os" "path/filepath" "strconv" @@ -17,7 +16,7 @@ func TestCreate(t *testing.T) { t.Errorf("err should be nil but: %v", err) } - dir, err := ioutil.TempDir("", "mackerel-agent-test-pidfile") + dir, err := os.MkdirTemp("", "mackerel-agent-test-pidfile") if err != nil { t.Fatalf("failed to create tempdir") } @@ -27,7 +26,7 @@ func TestCreate(t *testing.T) { if err != nil { t.Errorf("err should be nil but: %v", err) } - pidString, _ := ioutil.ReadFile(pidfile) + pidString, _ := os.ReadFile(pidfile) pid, _ := strconv.Atoi(string(pidString)) if pid != os.Getpid() { t.Errorf("contents of pidfile does not match pid. content: %d, pid: %d", pid, os.Getpid()) @@ -44,7 +43,7 @@ func TestRemove(t *testing.T) { if err != nil { t.Errorf("err should be nil but: %v", err) } - dir, err := ioutil.TempDir("", "mackerel-agent-test-pidfile") + dir, err := os.MkdirTemp("", "mackerel-agent-test-pidfile") if err != nil { t.Fatalf("failed to create tempdir") } diff --git a/spec/cloud.go b/spec/cloud.go index d3af2a506..be1e421ea 100644 --- a/spec/cloud.go +++ b/spec/cloud.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "strconv" @@ -184,7 +183,7 @@ func (g *EC2Generator) hasMetadataService(ctx context.Context) (bool, error) { return false, nil } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } @@ -228,7 +227,7 @@ func (g *EC2Generator) refreshToken(ctx context.Context) string { return "" } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "" } @@ -288,7 +287,7 @@ func (g *EC2Generator) getMetadata(cl *http.Client, key string) (string, error) return "", nil } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { cloudLogger.Errorf("Results of requesting metadata cannot be read: '%s'", err) return "", err @@ -317,7 +316,7 @@ func (g *EC2Generator) SuggestCustomIdentifier() (string, error) { io.Copy(io.Discard, resp.Body) return fmt.Errorf("failed to request instance-id. response code: %d", resp.StatusCode) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("results of requesting instance-id cannot be read: '%s'", err) } @@ -354,7 +353,7 @@ func requestGCEMeta(ctx context.Context) ([]byte, error) { io.Copy(io.Discard, resp.Body) return nil, fmt.Errorf("failed to request gce meta. response code: %d", resp.StatusCode) } - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } // IsGCE checks current environment is GCE or not @@ -510,7 +509,7 @@ func retrieveAzureVMMetadata(metadataMap map[string]string, baseURL string, urlS defer resp.Body.Close() if resp.StatusCode == 200 { - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { cloudLogger.Errorf("Results of requesting metadata cannot be read: '%s'", err) break @@ -545,7 +544,7 @@ func (g *AzureVMGenerator) SuggestCustomIdentifier() (string, error) { io.Copy(io.Discard, resp.Body) return fmt.Errorf("failed to request vmId. response code: %d", resp.StatusCode) } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("results of requesting vmId cannot be read: '%s'", err) } diff --git a/spec/isec2_linux.go b/spec/isec2_linux.go index bec60beb4..b165cd76d 100644 --- a/spec/isec2_linux.go +++ b/spec/isec2_linux.go @@ -6,7 +6,7 @@ import ( "encoding/binary" "encoding/hex" "fmt" - "io/ioutil" + "os" "strings" "time" @@ -27,7 +27,7 @@ func (g *EC2Generator) isEC2(ctx context.Context) bool { func (g *EC2Generator) isEC2WithSpecifiedUUIDFiles(ctx context.Context, uuidFiles []string) bool { looksLikeEC2 := false for _, u := range uuidFiles { - data, err := ioutil.ReadFile(u) + data, err := os.ReadFile(u) if err != nil { continue } diff --git a/spec/isec2_linux_test.go b/spec/isec2_linux_test.go index 0730798db..26f95bdc3 100644 --- a/spec/isec2_linux_test.go +++ b/spec/isec2_linux_test.go @@ -2,7 +2,6 @@ package spec import ( "context" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -97,7 +96,7 @@ func TestIsEC2(t *testing.T) { uuidFiles := make([]string, 0, 2) for _, exist := range tc.existsUUIDFiles { - tf, err := ioutil.TempFile("", "") + tf, err := os.CreateTemp("", "") if err != nil { t.Errorf("should not raise error: %s", err) } diff --git a/spec/linux/block_device.go b/spec/linux/block_device.go index 047b8d92a..865f8c557 100644 --- a/spec/linux/block_device.go +++ b/spec/linux/block_device.go @@ -4,7 +4,6 @@ package linux import ( - "io/ioutil" "os" "path" "strings" @@ -21,7 +20,7 @@ var blockDeviceLogger = logging.GetLogger("spec.block_device") // Generate generate metric values func (g *BlockDeviceGenerator) Generate() (interface{}, error) { - fileInfos, err := ioutil.ReadDir("/sys/block") + fileInfos, err := os.ReadDir("/sys/block") if err != nil { // /sys/block is unavailable on some PaaS (Heroku, for example) if os.IsNotExist(err) { @@ -41,7 +40,7 @@ func (g *BlockDeviceGenerator) Generate() (interface{}, error) { for _, key := range []string{"size", "removable"} { filename := path.Join("/sys/block", deviceName, key) if _, err := os.Stat(filename); err == nil { - bytes, err := ioutil.ReadFile(filename) + bytes, err := os.ReadFile(filename) if err != nil { blockDeviceLogger.Errorf("Failed (skip this spec): %s", err) return nil, err @@ -53,7 +52,7 @@ func (g *BlockDeviceGenerator) Generate() (interface{}, error) { for _, key := range []string{"model", "rev", "state", "timeout", "vendor"} { filename := path.Join("/sys/block", deviceName, "device", key) if _, err := os.Stat(filename); err == nil { - bytes, err := ioutil.ReadFile(filename) + bytes, err := os.ReadFile(filename) if err != nil { blockDeviceLogger.Errorf("Failed (skip this spec): %s", err) return nil, err diff --git a/start_test.go b/start_test.go index e03e343e1..5706806e0 100644 --- a/start_test.go +++ b/start_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -61,7 +60,7 @@ func TestStart(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - root, err := ioutil.TempDir("", "mackerel-config-test") + root, err := os.MkdirTemp("", "mackerel-config-test") if err != nil { t.Fatalf("Could not create temporary dir for test") } diff --git a/wix/replace/replace_windows.go b/wix/replace/replace_windows.go index 14dc85bc8..04aabc71e 100644 --- a/wix/replace/replace_windows.go +++ b/wix/replace/replace_windows.go @@ -21,7 +21,6 @@ package main import ( "io" - "io/ioutil" "log" "os" "path/filepath" @@ -65,7 +64,7 @@ func main() { } out: - content, err := ioutil.ReadFile(inFile) + content, err := os.ReadFile(inFile) if err != nil { log.Fatal(err) } @@ -73,7 +72,7 @@ out: _, err = os.Stat(outFile) outFileIsExists := err == nil if !(outFileIsExists) { - err = ioutil.WriteFile(outFile, []byte(strings.Replace(string(content), oldStr, newStr, -1)), 0644) + err = os.WriteFile(outFile, []byte(strings.Replace(string(content), oldStr, newStr, -1)), 0644) if err != nil { log.Fatal(err) } From 2965ec17616d72661de6f8980b6f072a12357d09 Mon Sep 17 00:00:00 2001 From: yseto Date: Thu, 1 Sep 2022 12:07:28 +0900 Subject: [PATCH 2/8] fix edition name. should use !strings.Contains(osname, edition) instead (S1003) --- spec/windows/kernel.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/windows/kernel.go b/spec/windows/kernel.go index 3685667cf..93a9b0725 100644 --- a/spec/windows/kernel.go +++ b/spec/windows/kernel.go @@ -46,7 +46,7 @@ func (g *KernelGenerator) Generate() (interface{}, error) { return nil, err } - if edition != "" && strings.Index(osname, edition) == -1 { + if edition != "" && !strings.Contains(osname, edition) { osname += " (" + edition + ")" } From 048ddcedfea707057f025cf9406ed147aad9a7d6 Mon Sep 17 00:00:00 2001 From: yseto Date: Thu, 1 Sep 2022 12:06:08 +0900 Subject: [PATCH 3/8] fix error error strings should not be capitalized (ST1005) --- metrics/windows/disk.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metrics/windows/disk.go b/metrics/windows/disk.go index e99ba7e48..9e409f900 100644 --- a/metrics/windows/disk.go +++ b/metrics/windows/disk.go @@ -70,7 +70,7 @@ func (g *DiskGenerator) queryWmiWithTimeout() ([]win32PerfFormattedDataPerfDiskP }() select { case <-time.After(queryWmiTimeout): - return nil, errors.New("Timeouted while retrieving disk metrics") + return nil, errors.New("timeouted while retrieving disk metrics") case err := <-errCh: return nil, err case records := <-recordsCh: From ffda16a22bd2eb52d9581de3713ec96398e9b791 Mon Sep 17 00:00:00 2001 From: yseto Date: Wed, 31 Aug 2022 18:55:33 +0900 Subject: [PATCH 4/8] added error check --- spec/darwin/cpu.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/spec/darwin/cpu.go b/spec/darwin/cpu.go index d6e7f0199..18e410eac 100644 --- a/spec/darwin/cpu.go +++ b/spec/darwin/cpu.go @@ -88,6 +88,10 @@ func (g *CPUGenerator) getCPUCount() (*int, error) { // - flags func (g *CPUGenerator) Generate() (interface{}, error) { cpuInfoBytes, err := exec.Command("sysctl", "machdep.cpu").Output() + if err != nil { + cpuLogger.Errorf("Failed: %s", err) + return nil, err + } cpuInfo, err := g.parseSysCtlBytes(cpuInfoBytes) if err != nil { cpuLogger.Errorf("Failed: %s", err) From 9eb4280f89ecd6125ae97a9214c91db82b56d60b Mon Sep 17 00:00:00 2001 From: yseto Date: Wed, 31 Aug 2022 18:52:17 +0900 Subject: [PATCH 5/8] fix lint should replace this if statement with an unconditional strings.TrimSuffix (S1017) --- metrics/freebsd/memory.go | 5 +---- metrics/netbsd/memory.go | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/metrics/freebsd/memory.go b/metrics/freebsd/memory.go index 0b57af331..8b9c0d5a8 100644 --- a/metrics/freebsd/memory.go +++ b/metrics/freebsd/memory.go @@ -43,10 +43,7 @@ func (g *MemoryGenerator) Generate() (metrics.Values, error) { for i := 1; i < len(fields); i += 2 { v, err := getValue(fields[i]) if err == nil { - k := fields[i+1] - if strings.HasSuffix(k, ",") { - k = k[0 : len(k)-1] - } + k := strings.TrimSuffix(fields[i+1], ",") switch k { case "Cache": ret["memory.cached"] = v diff --git a/metrics/netbsd/memory.go b/metrics/netbsd/memory.go index ac331f4ea..78b7c8adb 100644 --- a/metrics/netbsd/memory.go +++ b/metrics/netbsd/memory.go @@ -43,10 +43,7 @@ func (g *MemoryGenerator) Generate() (metrics.Values, error) { for i := 1; i < len(fields); i += 2 { v, err := getValue(fields[i]) if err == nil { - k := fields[i+1] - if strings.HasSuffix(k, ",") { - k = k[0 : len(k)-1] - } + k := strings.TrimSuffix(fields[i+1], ",") switch k { case "Act": ret["memory.act"] = v From 611ce2cb0088c169e04034116990a5478e8033b6 Mon Sep 17 00:00:00 2001 From: yseto Date: Wed, 31 Aug 2022 18:24:28 +0900 Subject: [PATCH 6/8] to be simple condition should omit comparison to bool constant, can be simplified to ... (S1002) --- config/config.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/config/config.go b/config/config.go index 77e58432d..59269cd08 100644 --- a/config/config.go +++ b/config/config.go @@ -436,10 +436,10 @@ func LoadConfig(conffile string) (*Config, error) { if config.Pidfile == "" { config.Pidfile = DefaultConfig.Pidfile } - if config.Verbose == false { + if !config.Verbose { config.Verbose = DefaultConfig.Verbose } - if config.Diagnostic == false { + if !config.Diagnostic { config.Diagnostic = DefaultConfig.Diagnostic } @@ -522,7 +522,7 @@ func includeConfigFile(config *Config, include string) error { // If included config does not have "roles" key, // use the previous roles configuration value. - if meta.IsDefined("roles") == false { + if !meta.IsDefined("roles") { config.Roles = rolesSaved } From a746259eb8cddc787258786d7ccff24821a40a27 Mon Sep 17 00:00:00 2001 From: yseto Date: Wed, 31 Aug 2022 18:21:22 +0900 Subject: [PATCH 7/8] use time.Since agent/generator.go:45:20: should use time.Since instead of time.Now().Sub (S1012) --- agent/generator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent/generator.go b/agent/generator.go index d6f3423db..f84ba0238 100644 --- a/agent/generator.go +++ b/agent/generator.go @@ -42,7 +42,7 @@ func generateValues(generators []metrics.Generator) []*metrics.ValuesCustomIdent startedAt := time.Now() values, err := g.Generate() - if seconds := (time.Now().Sub(startedAt) / time.Second); seconds > 120 { + if seconds := (time.Since(startedAt) / time.Second); seconds > 120 { logger.Warningf("%T.Generate() take a long time (%d seconds)", g, seconds) } if err != nil { From 927da9148e22c88a8c21d04fc7c73a852d063f62 Mon Sep 17 00:00:00 2001 From: yseto Date: Fri, 2 Sep 2022 17:08:27 +0900 Subject: [PATCH 8/8] use t.TempDir() --- command/command_test.go | 11 ++--------- config/config_test.go | 16 ++++------------ do_init_test.go | 6 +----- pidfile/pidfile_test.go | 12 ++---------- start_test.go | 7 +------ 5 files changed, 10 insertions(+), 42 deletions(-) diff --git a/command/command_test.go b/command/command_test.go index b25f32165..c0769971e 100644 --- a/command/command_test.go +++ b/command/command_test.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" "net/http/httptest" - "os" "sort" "sync" "testing" @@ -89,11 +88,7 @@ func newMockAPIServer(t *testing.T) (config.Config, map[string]func(*http.Reques fmt.Fprint(w, string(respJSON)) })) - root, err := os.MkdirTemp("", "mackerel-agent-test") - if err != nil { - t.Fatal(err) - } - + root := t.TempDir() conf := config.Config{ Apibase: ts.URL, Root: root, @@ -101,7 +96,6 @@ func newMockAPIServer(t *testing.T) (config.Config, map[string]func(*http.Reques return conf, mockHandlers, ts, func() { ts.Close() - os.RemoveAll(root) } } @@ -175,8 +169,7 @@ func TestPrepareWithCreateWithFail(t *testing.T) { func TestPrepareWithUpdate(t *testing.T) { conf, mockHandlers, ts, deferFunc := newMockAPIServer(t) defer deferFunc() - tempDir, _ := os.MkdirTemp("", "") - conf.Root = tempDir + conf.Root = t.TempDir() conf.SaveHostID("xxx12345678901") mockHandlers["PUT /api/v0/hosts/xxx12345678901"] = func(req *http.Request) (int, jsonObject) { diff --git a/config/config_test.go b/config/config_test.go index cc69b0aec..d298fe4be 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -581,9 +581,7 @@ var tomlQuotedReplacer = strings.NewReplacer( ) func TestLoadConfigFileInclude(t *testing.T) { - configDir, err := os.MkdirTemp("", "mackerel-config-test") - assertNoError(t, err) - defer os.RemoveAll(configDir) + configDir := t.TempDir() includedFile, err := os.Create(filepath.Join(configDir, "sub1.conf")) assertNoError(t, err) @@ -638,9 +636,7 @@ command = "bar" } func TestLoadConfigFileIncludeOverwritten(t *testing.T) { - configDir, err := os.MkdirTemp("", "mackerel-config-test") - assertNoError(t, err) - defer os.RemoveAll(configDir) + configDir := t.TempDir() includedFile, err := os.Create(filepath.Join(configDir, "sub2.conf")) assertNoError(t, err) @@ -679,14 +675,10 @@ verbose = true } func TestFileSystemHostIDStorage(t *testing.T) { - root, err := os.MkdirTemp("", "mackerel-agent-test") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(root) + root := t.TempDir() s := FileSystemHostIDStorage{Root: root} - err = s.SaveHostID("test-host-id") + err := s.SaveHostID("test-host-id") assertNoError(t, err) hostID, err := s.LoadHostID() diff --git a/do_init_test.go b/do_init_test.go index 9780a4939..02e426b24 100644 --- a/do_init_test.go +++ b/do_init_test.go @@ -16,11 +16,7 @@ func TestDoInitialize(t *testing.T) { } } - root, err := os.MkdirTemp("", "mackerel-config-test") - if err != nil { - t.Fatalf("Could not create temporary dir for test") - } - defer os.RemoveAll(root) + root := t.TempDir() { // not exist config file directory diff --git a/pidfile/pidfile_test.go b/pidfile/pidfile_test.go index 76ef73ec9..fa3f89b96 100644 --- a/pidfile/pidfile_test.go +++ b/pidfile/pidfile_test.go @@ -16,11 +16,7 @@ func TestCreate(t *testing.T) { t.Errorf("err should be nil but: %v", err) } - dir, err := os.MkdirTemp("", "mackerel-agent-test-pidfile") - if err != nil { - t.Fatalf("failed to create tempdir") - } - defer os.RemoveAll(dir) + dir := t.TempDir() pidfile := filepath.Join(dir, "pidfile") err = Create(pidfile) if err != nil { @@ -43,11 +39,7 @@ func TestRemove(t *testing.T) { if err != nil { t.Errorf("err should be nil but: %v", err) } - dir, err := os.MkdirTemp("", "mackerel-agent-test-pidfile") - if err != nil { - t.Fatalf("failed to create tempdir") - } - defer os.RemoveAll(dir) + dir := t.TempDir() pidfile := filepath.Join(dir, "pidfile") err = Create(pidfile) if err != nil { diff --git a/start_test.go b/start_test.go index 5706806e0..88557fd35 100644 --- a/start_test.go +++ b/start_test.go @@ -60,12 +60,7 @@ func TestStart(t *testing.T) { ts := httptest.NewServer(mux) defer ts.Close() - root, err := os.MkdirTemp("", "mackerel-config-test") - if err != nil { - t.Fatalf("Could not create temporary dir for test") - } - defer os.RemoveAll(root) - + root := t.TempDir() confFile, err := os.Create(filepath.Join(root, "mackerel-agent.conf")) if err != nil { t.Fatalf("Could not create temporary file for test")