Skip to content

Commit

Permalink
fix disk usage
Browse files Browse the repository at this point in the history
  • Loading branch information
saeedvaziry committed Apr 13, 2024
1 parent 3ee2d81 commit 4ec33e1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
6 changes: 3 additions & 3 deletions cmd/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ import (

type Payload struct {
Load float64 `json:"load"`
DiskTotal uint64 `json:"disk_total"`
DiskFree uint64 `json:"disk_free"`
DiskUsed uint64 `json:"disk_used"`
DiskTotal string `json:"disk_total"`
DiskFree string `json:"disk_free"`
DiskUsed string `json:"disk_used"`
MemoryTotal string `json:"memory_total"`
MemoryFree string `json:"memory_free"`
MemoryUsed string `json:"memory_used"`
Expand Down
35 changes: 26 additions & 9 deletions pkg/disk/disk.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ package disk

import (
"fmt"
"syscall"
"os/exec"
"strings"
)

type DiskInfo struct {
Total uint64
Free uint64
Used uint64
Total string
Free string
Used string
}

func GetDiskInfo() DiskInfo {
Expand All @@ -24,13 +25,29 @@ func GetDiskInfo() DiskInfo {

// DiskUsage returns the disk usage of the path in bytes
func diskUsage(path string) (usage DiskInfo, err error) {
fs := &syscall.Statfs_t{}
err = syscall.Statfs(path, fs)
// Run the df command to get disk information
cmd := exec.Command("df", "-BM", path) // Use -BM option to get sizes in megabytes
output, err := cmd.Output()
if err != nil {
fmt.Println("Error running df command:", err)
return
}
usage.Total = (fs.Blocks * uint64(fs.Bsize)) / (1024 * 1024)
usage.Free = (fs.Bfree * uint64(fs.Bsize)) / (1024 * 1024)
usage.Used = usage.Total - usage.Free

// Parse the output to get disk total, usage, and free
lines := strings.Split(string(output), "\n")
if len(lines) < 2 {
fmt.Println("Unexpected output from df command")
return
}

fields := strings.Fields(lines[1])
if len(fields) < 4 {
fmt.Println("Unexpected output format")
return
}

usage.Total = strings.Replace(fields[1], "M", "", 1)
usage.Used = strings.Replace(fields[2], "M", "", 1)
usage.Free = strings.Replace(fields[3], "M", "", 1)
return
}

0 comments on commit 4ec33e1

Please sign in to comment.