package raid import ( "errors" "fmt" "log" "os" "os/exec" "sort" "strconv" "strings" "imuslab.com/arozos/mod/utils" ) /* mdadm manager This script handles the interaction with mdadm */ // Storage Device meta was generated by lsblk type StorageDeviceMeta struct { Name string Size int64 RO bool DevType string MountPoint string } // RAIDDevice represents information about a RAID device. type RAIDMember struct { Name string Seq int } type RAIDDevice struct { Name string Status string Level string Members []*RAIDMember } // List all the storage device in the system, set minSize to 0 for no filter func (m *Manager) ListAllStorageDevices(minSize int64) ([]*StorageDeviceMeta, error) { cmd := exec.Command("sudo", "lsblk", "-b") output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("lsblk error: %v", err) } // Split the output into lines lines := strings.Split(string(output), "\n") var devices []*StorageDeviceMeta // Parse each line to extract device information for _, line := range lines[1:] { // Skip the header line fields := strings.Fields(line) if len(fields) < 7 { continue } size, err := strconv.ParseInt(fields[3], 10, 64) if err != nil { return nil, fmt.Errorf("error parsing device size: %v", err) } ro := fields[4] == "1" device := &StorageDeviceMeta{ Name: fields[0], Size: size, RO: ro, DevType: fields[5], MountPoint: fields[6], } // Filter devices based on minimum size if size >= minSize { devices = append(devices, device) } } return devices, nil } // Return the uuid of the disk by its path name (e.g. /dev/sda) func (m *Manager) GetDiskUUIDByPath(devicePath string) (string, error) { cmd := exec.Command("sudo", "blkid", devicePath) output, err := cmd.CombinedOutput() if err != nil { return "", fmt.Errorf("blkid error: %v", err) } // Parse the output to extract the UUID fields := strings.Fields(string(output)) for _, field := range fields { if strings.HasPrefix(field, "UUID=") { uuid := strings.TrimPrefix(field, "UUID=\"") uuid = strings.TrimSuffix(uuid, "\"") return uuid, nil } } return "", fmt.Errorf("UUID not found for device %s", devicePath) } // CreateRAIDDevice creates a RAID device using the mdadm command. func (m *Manager) CreateRAIDDevice(devName string, raidName string, raidLevel int, raidDeviceIds []string, spareDeviceIds []string) error { //Calculate the size of the raid devices raidDev := len(raidDeviceIds) spareDevice := len(spareDeviceIds) //Validate if raid level if !IsValidRAIDLevel("raid" + strconv.Itoa(raidLevel)) { return fmt.Errorf("invalid or unsupported raid level given: raid" + strconv.Itoa(raidLevel)) } //Validate the number of disk is enough for the raid if raidLevel == 0 && raidDev < 2 { return fmt.Errorf("not enough disks for raid0") } else if raidLevel == 1 && raidDev < 2 { return fmt.Errorf("not enough disks for raid1") } else if raidLevel == 5 && raidDev < 3 { return fmt.Errorf("not enough disk for raid5") } else if raidLevel == 6 && raidDev < 4 { return fmt.Errorf("not enough disk for raid6") } //Append /dev to the name if missing if !strings.HasPrefix(devName, "/dev/") { devName = "/dev/" + devName } if utils.FileExists(devName) { //RAID device already exists return errors.New(devName + " already been used") } // Concatenate RAID and spare device arrays allDeviceIds := append(raidDeviceIds, spareDeviceIds...) // Build the mdadm command cmd := exec.Command("bash", "-c", fmt.Sprintf("yes | sudo mdadm --create %s --name %s --level=%d --raid-devices=%d --spare-devices=%d %s", devName, raidName, raidLevel, raidDev, spareDevice, strings.Join(allDeviceIds, " "))) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { return fmt.Errorf("error running mdadm command: %v", err) } return nil } // GetRAIDDevicesFromProcMDStat retrieves information about RAID devices from /proc/mdstat. // if your RAID array is in auto-read-only mode, it is (usually) brand new func (m *Manager) GetRAIDDevicesFromProcMDStat() ([]RAIDDevice, error) { // Execute the cat command to read /proc/mdstat cmd := exec.Command("cat", "/proc/mdstat") // Run the command and capture its output output, err := cmd.Output() if err != nil { return nil, fmt.Errorf("error running cat command: %v", err) } // Convert the output to a string and split it into lines lines := strings.Split(string(output), "\n") // Initialize an empty slice to store RAID devices raidDevices := make([]RAIDDevice, 0) // Iterate over the lines, skipping the first line (Personalities) // Lines usually looks like this // md0 : active raid1 sdc[1] sdb[0] for _, line := range lines[1:] { // Skip empty lines if line == "" { continue } // Split the line by colon (:) parts := strings.SplitN(line, " : ", 2) if len(parts) != 2 { continue } // Extract device name and status deviceName := parts[0] // Split the members string by space to get individual member devices info := strings.Fields(parts[1]) if len(info) < 4 { //Malform output continue } deviceStatus := info[0] //Raid level usually appears at position 1 - 2, check both raidLevel := "" if strings.HasPrefix(info[1], "raid") { raidLevel = info[1] } else if strings.HasPrefix(info[2], "raid") { raidLevel = info[2] } //Get the members (disks) of the array members := []*RAIDMember{} for _, disk := range info[2:] { if !strings.HasPrefix(disk, "sd") { //Probably not a storage device continue } //In sda[0] format, we need to split out the number from the disk seq tmp := strings.Split(disk, "[") if len(tmp) != 2 { continue } //Convert the sequence to id seqInt, err := strconv.Atoi(strings.TrimSuffix(strings.TrimSpace(tmp[1]), "]")) if err != nil { //Not an integer? log.Println("[RAID] Unable to parse " + disk + " sequence ID") continue } member := RAIDMember{ Name: strings.TrimSpace(tmp[0]), Seq: seqInt, } members = append(members, &member) } //Sort the member disks sort.Slice(members[:], func(i, j int) bool { return members[i].Seq < members[j].Seq }) // Create a RAIDDevice struct and append it to the slice raidDevice := RAIDDevice{ Name: deviceName, Status: deviceStatus, Level: raidLevel, Members: members, } raidDevices = append(raidDevices, raidDevice) } return raidDevices, nil }