diskinfo.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package diskinfo
  2. import (
  3. "errors"
  4. "os"
  5. "strings"
  6. "imuslab.com/bokofs/bokofsd/mod/diskinfo/blkid"
  7. "imuslab.com/bokofs/bokofsd/mod/diskinfo/lsblk"
  8. )
  9. // Get a disk by its device path, accept both /dev/sda and sda
  10. func NewBlockFromDevicePath(devpath string) (*Block, error) {
  11. if !strings.HasPrefix(devpath, "/dev/") {
  12. devpath = "/dev/" + devpath
  13. }
  14. if _, err := os.Stat(devpath); errors.Is(err, os.ErrNotExist) {
  15. return nil, errors.New("device path does not exist")
  16. }
  17. //Create a new disk object
  18. thisDisk := &Block{
  19. Path: devpath,
  20. }
  21. //Try to get the block device info
  22. err := thisDisk.UpdateProperties()
  23. if err != nil {
  24. return nil, err
  25. }
  26. return thisDisk, nil
  27. }
  28. // UpdateProperties updates the properties of the disk.
  29. func (d *Block) UpdateProperties() error {
  30. //Try to get the block device info
  31. blockDeviceInfo, err := lsblk.GetBlockDeviceInfoFromDevicePath(d.Path)
  32. if err != nil {
  33. return err
  34. }
  35. // Update the disk properties
  36. d.Name = blockDeviceInfo.Name
  37. d.Size = blockDeviceInfo.Size
  38. d.BlockType = blockDeviceInfo.Type
  39. //d.MountPoint = blockDeviceInfo.MountPoint
  40. if d.BlockType == "disk" {
  41. //This block is a disk not a partition. There is no partition ID info
  42. //So we can skip the blkid call
  43. return nil
  44. }
  45. // Get the partition ID
  46. diskIdInfo, err := blkid.GetPartitionIDFromDevicePath(d.Path)
  47. if err != nil {
  48. return err
  49. }
  50. // Update the disk properties with ID info
  51. d.UUID = diskIdInfo.UUID
  52. d.FsType = diskIdInfo.Type
  53. d.BlockSize = diskIdInfo.BlockSize
  54. return nil
  55. }