12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package raid
- import (
- "bufio"
- "errors"
- "fmt"
- "os"
- "os/exec"
- "strings"
- )
- // Get the next avaible RAID array name
- func GetNextAvailableMDDevice() (string, error) {
- for i := 0; i < 100; i++ {
- mdDevice := fmt.Sprintf("/dev/md%d", i)
- if _, err := os.Stat(mdDevice); os.IsNotExist(err) {
- return mdDevice, nil
- }
- }
- return "", fmt.Errorf("no available /dev/mdX devices found")
- }
- // DANGER: Wipe the whole disk given the disk path
- func (m *Manager) WipeDisk(diskPath string) error {
- // Unmount the disk
- isMounted, _ := DeviceIsMounted(diskPath)
- if isMounted {
- umountCmd := exec.Command("sudo", "umount", diskPath)
- if err := umountCmd.Run(); err != nil {
- return fmt.Errorf("error unmounting disk %s: %v", diskPath, err)
- }
- }
- // Wipe all filesystem signatures on the entire disk
- wipeCmd := exec.Command("sudo", "wipefs", "--all", "--force", diskPath)
- if err := wipeCmd.Run(); err != nil {
- return fmt.Errorf("error wiping filesystem signatures on %s: %v", diskPath, err)
- }
- return nil
- }
- // ClearSuperblock clears the superblock of the specified disk.
- func (m *Manager) ClearSuperblock(devicePath string) error {
- isMounted, err := DeviceIsMounted(devicePath)
- if err != nil {
- return errors.New("unable to validate if the device is unmounted: " + err.Error())
- }
- if isMounted {
- return errors.New("target device is mounted. Make sure it is unmounted before clearing")
- }
- cmd := exec.Command("sudo", "mdadm", "--zero-superblock", devicePath)
- err = cmd.Run()
- if err != nil {
- return fmt.Errorf("error clearing superblock: %v", err)
- }
- return nil
- }
- // Check if a device is mounted given the path name, like /dev/sdc
- func DeviceIsMounted(devicePath string) (bool, error) {
- // Open the mountinfo file
- file, err := os.Open("/proc/mounts")
- if err != nil {
- return false, fmt.Errorf("error opening /proc/mounts: %v", err)
- }
- defer file.Close()
- // Scan the mountinfo file line by line
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := scanner.Text()
- fields := strings.Fields(line)
- if len(fields) >= 2 && fields[0] == devicePath {
- // Device is mounted
- return true, nil
- }
- }
- // Device is not mounted
- return false, nil
- }
|