raidutils.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package raid
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "strings"
  8. )
  9. // Get the next avaible RAID array name
  10. func GetNextAvailableMDDevice() (string, error) {
  11. for i := 0; i < 100; i++ {
  12. mdDevice := fmt.Sprintf("/dev/md%d", i)
  13. if _, err := os.Stat(mdDevice); os.IsNotExist(err) {
  14. return mdDevice, nil
  15. }
  16. }
  17. return "", fmt.Errorf("no available /dev/mdX devices found")
  18. }
  19. // DANGER: Wipe the whole disk given the disk path
  20. func (m *Manager) WipeDisk(diskPath string) error {
  21. // Unmount the disk
  22. isMounted, _ := DeviceIsMounted(diskPath)
  23. if isMounted {
  24. umountCmd := exec.Command("sudo", "umount", diskPath)
  25. if err := umountCmd.Run(); err != nil {
  26. return fmt.Errorf("error unmounting disk %s: %v", diskPath, err)
  27. }
  28. }
  29. // Wipe all filesystem signatures on the entire disk
  30. wipeCmd := exec.Command("sudo", "wipefs", "--all", "--force", diskPath)
  31. if err := wipeCmd.Run(); err != nil {
  32. return fmt.Errorf("error wiping filesystem signatures on %s: %v", diskPath, err)
  33. }
  34. return nil
  35. }
  36. // Check if a device is mounted given the path name, like /dev/sdc
  37. func DeviceIsMounted(devicePath string) (bool, error) {
  38. // Open the mountinfo file
  39. file, err := os.Open("/proc/mounts")
  40. if err != nil {
  41. return false, fmt.Errorf("error opening /proc/mounts: %v", err)
  42. }
  43. defer file.Close()
  44. // Scan the mountinfo file line by line
  45. scanner := bufio.NewScanner(file)
  46. for scanner.Scan() {
  47. line := scanner.Text()
  48. fields := strings.Fields(line)
  49. if len(fields) >= 2 && fields[0] == devicePath {
  50. // Device is mounted
  51. return true, nil
  52. }
  53. }
  54. // Device is not mounted
  55. return false, nil
  56. }