df.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package df
  2. import (
  3. "bytes"
  4. "errors"
  5. "os/exec"
  6. "strconv"
  7. "strings"
  8. )
  9. type DiskInfo struct {
  10. DevicePath string
  11. Blocks int64
  12. Used int64
  13. Available int64
  14. UsePercent int
  15. MountedOn string
  16. }
  17. // GetDiskUsageByPath retrieves disk usage information for a specific path.
  18. // e.g. "/dev/sda1" or "sda1" will return the disk usage for the partition mounted on "/dev/sda1".
  19. func GetDiskUsageByPath(path string) (*DiskInfo, error) {
  20. //Make sure the path has a prefix and a trailing slash
  21. if !strings.HasPrefix(path, "/dev/") {
  22. path = "/dev/" + path
  23. }
  24. path = strings.TrimSuffix(path, "/")
  25. diskUsages, err := GetDiskUsage()
  26. if err != nil {
  27. return nil, err
  28. }
  29. for _, diskInfo := range diskUsages {
  30. if strings.HasPrefix(diskInfo.DevicePath, path) {
  31. return &diskInfo, nil
  32. }
  33. }
  34. return nil, errors.New("disk usage not found for path: " + path)
  35. }
  36. // GetDiskUsage retrieves disk usage information for all mounted filesystems.
  37. func GetDiskUsage() ([]DiskInfo, error) {
  38. cmd := exec.Command("df", "-k")
  39. var out bytes.Buffer
  40. cmd.Stdout = &out
  41. err := cmd.Run()
  42. if err != nil {
  43. return nil, err
  44. }
  45. lines := strings.Split(out.String(), "\n")
  46. if len(lines) < 2 {
  47. return nil, nil
  48. }
  49. var diskInfos []DiskInfo
  50. for _, line := range lines[1:] {
  51. fields := strings.Fields(line)
  52. if len(fields) < 6 {
  53. continue
  54. }
  55. usePercent, err := strconv.Atoi(strings.TrimSuffix(fields[4], "%"))
  56. if err != nil {
  57. return nil, err
  58. }
  59. blocks, err := strconv.ParseInt(fields[1], 10, 64)
  60. if err != nil {
  61. return nil, err
  62. }
  63. used, err := strconv.ParseInt(fields[2], 10, 64)
  64. if err != nil {
  65. return nil, err
  66. }
  67. available, err := strconv.ParseInt(fields[3], 10, 64)
  68. if err != nil {
  69. return nil, err
  70. }
  71. diskInfos = append(diskInfos, DiskInfo{
  72. DevicePath: fields[0],
  73. Blocks: blocks,
  74. Used: used * 1024, // Convert to bytes from 1k blocks
  75. Available: available * 1024,
  76. UsePercent: usePercent,
  77. MountedOn: fields[5],
  78. })
  79. }
  80. return diskInfos, nil
  81. }