Skip to content

Commit 4ec33e1

Browse files
committed
fix disk usage
1 parent 3ee2d81 commit 4ec33e1

2 files changed

Lines changed: 29 additions & 12 deletions

File tree

cmd/agent.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@ import (
1515

1616
type Payload struct {
1717
Load float64 `json:"load"`
18-
DiskTotal uint64 `json:"disk_total"`
19-
DiskFree uint64 `json:"disk_free"`
20-
DiskUsed uint64 `json:"disk_used"`
18+
DiskTotal string `json:"disk_total"`
19+
DiskFree string `json:"disk_free"`
20+
DiskUsed string `json:"disk_used"`
2121
MemoryTotal string `json:"memory_total"`
2222
MemoryFree string `json:"memory_free"`
2323
MemoryUsed string `json:"memory_used"`

pkg/disk/disk.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ package disk
22

33
import (
44
"fmt"
5-
"syscall"
5+
"os/exec"
6+
"strings"
67
)
78

89
type DiskInfo struct {
9-
Total uint64
10-
Free uint64
11-
Used uint64
10+
Total string
11+
Free string
12+
Used string
1213
}
1314

1415
func GetDiskInfo() DiskInfo {
@@ -24,13 +25,29 @@ func GetDiskInfo() DiskInfo {
2425

2526
// DiskUsage returns the disk usage of the path in bytes
2627
func diskUsage(path string) (usage DiskInfo, err error) {
27-
fs := &syscall.Statfs_t{}
28-
err = syscall.Statfs(path, fs)
28+
// Run the df command to get disk information
29+
cmd := exec.Command("df", "-BM", path) // Use -BM option to get sizes in megabytes
30+
output, err := cmd.Output()
2931
if err != nil {
32+
fmt.Println("Error running df command:", err)
3033
return
3134
}
32-
usage.Total = (fs.Blocks * uint64(fs.Bsize)) / (1024 * 1024)
33-
usage.Free = (fs.Bfree * uint64(fs.Bsize)) / (1024 * 1024)
34-
usage.Used = usage.Total - usage.Free
35+
36+
// Parse the output to get disk total, usage, and free
37+
lines := strings.Split(string(output), "\n")
38+
if len(lines) < 2 {
39+
fmt.Println("Unexpected output from df command")
40+
return
41+
}
42+
43+
fields := strings.Fields(lines[1])
44+
if len(fields) < 4 {
45+
fmt.Println("Unexpected output format")
46+
return
47+
}
48+
49+
usage.Total = strings.Replace(fields[1], "M", "", 1)
50+
usage.Used = strings.Replace(fields[2], "M", "", 1)
51+
usage.Free = strings.Replace(fields[3], "M", "", 1)
3552
return
3653
}

0 commit comments

Comments
 (0)