disklb.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package diskfs
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os/exec"
  6. "strings"
  7. )
  8. type BlockDeviceModelInfo struct {
  9. Name string `json:"name"`
  10. Size string `json:"size"`
  11. Model string `json:"model"`
  12. Children []BlockDeviceModelInfo `json:"children"`
  13. }
  14. // Get disk model name by disk name (sdX, not /dev/sdX), return the model name (if any) and expected size (not actual)
  15. // return device labeled size, model and error if any
  16. func GetDiskModelByName(name string) (string, string, error) {
  17. cmd := exec.Command("sudo", "lsblk", "--json", "-o", "NAME,SIZE,MODEL")
  18. output, err := cmd.Output()
  19. if err != nil {
  20. return "", "", fmt.Errorf("error running lsblk: %v", err)
  21. }
  22. var blockDevices struct {
  23. BlockDevices []BlockDeviceModelInfo `json:"blockdevices"`
  24. }
  25. if err := json.Unmarshal(output, &blockDevices); err != nil {
  26. return "", "", fmt.Errorf("error parsing lsblk output: %v", err)
  27. }
  28. return findDiskInfo(blockDevices.BlockDevices, name)
  29. }
  30. func findDiskInfo(blockDevices []BlockDeviceModelInfo, name string) (string, string, error) {
  31. for _, device := range blockDevices {
  32. if device.Name == name {
  33. return device.Size, device.Model, nil
  34. }
  35. if strings.HasPrefix(name, device.Name) {
  36. return findDiskInfo(device.Children, name)
  37. }
  38. }
  39. return "", "", fmt.Errorf("disk not found: %s", name)
  40. }