mdadm.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package raid
  2. import (
  3. "errors"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/exec"
  8. "path/filepath"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "imuslab.com/arozos/mod/utils"
  13. )
  14. /*
  15. mdadm manager
  16. This script handles the interaction with mdadm
  17. */
  18. // RAIDDevice represents information about a RAID device.
  19. type RAIDMember struct {
  20. Name string //sdX
  21. Seq int //Sequence in RAID arary
  22. Failed bool //If details output with (F) tag this will set to true
  23. }
  24. type RAIDDevice struct {
  25. Name string
  26. Status string
  27. Level string
  28. Members []*RAIDMember
  29. }
  30. // Return the uuid of the disk by its path name (e.g. /dev/sda)
  31. func (m *Manager) GetDiskUUIDByPath(devicePath string) (string, error) {
  32. cmd := exec.Command("sudo", "blkid", devicePath)
  33. output, err := cmd.CombinedOutput()
  34. if err != nil {
  35. return "", fmt.Errorf("blkid error: %v", err)
  36. }
  37. // Parse the output to extract the UUID
  38. fields := strings.Fields(string(output))
  39. for _, field := range fields {
  40. if strings.HasPrefix(field, "UUID=") {
  41. uuid := strings.TrimPrefix(field, "UUID=\"")
  42. uuid = strings.TrimSuffix(uuid, "\"")
  43. return uuid, nil
  44. }
  45. }
  46. return "", fmt.Errorf("UUID not found for device %s", devicePath)
  47. }
  48. // CreateRAIDDevice creates a RAID device using the mdadm command.
  49. func (m *Manager) CreateRAIDDevice(devName string, raidName string, raidLevel int, raidDeviceIds []string, spareDeviceIds []string) error {
  50. //Calculate the size of the raid devices
  51. raidDev := len(raidDeviceIds)
  52. spareDevice := len(spareDeviceIds)
  53. //Validate if raid level
  54. if !IsValidRAIDLevel("raid" + strconv.Itoa(raidLevel)) {
  55. return fmt.Errorf("invalid or unsupported raid level given: raid" + strconv.Itoa(raidLevel))
  56. }
  57. //Validate the number of disk is enough for the raid
  58. if raidLevel == 0 && raidDev < 2 {
  59. return fmt.Errorf("not enough disks for raid0")
  60. } else if raidLevel == 1 && raidDev < 2 {
  61. return fmt.Errorf("not enough disks for raid1")
  62. } else if raidLevel == 5 && raidDev < 3 {
  63. return fmt.Errorf("not enough disk for raid5")
  64. } else if raidLevel == 6 && raidDev < 4 {
  65. return fmt.Errorf("not enough disk for raid6")
  66. }
  67. //Append /dev to the name if missing
  68. if !strings.HasPrefix(devName, "/dev/") {
  69. devName = "/dev/" + devName
  70. }
  71. if utils.FileExists(devName) {
  72. //RAID device already exists
  73. return errors.New(devName + " already been used")
  74. }
  75. // Concatenate RAID and spare device arrays
  76. allDeviceIds := append(raidDeviceIds, spareDeviceIds...)
  77. // Build the mdadm command
  78. cmd := exec.Command("bash", "-c", fmt.Sprintf("yes | sudo mdadm --create %s --name %s --level=%d --raid-devices=%d --spare-devices=%d %s",
  79. devName, raidName, raidLevel, raidDev, spareDevice, strings.Join(allDeviceIds, " ")))
  80. cmd.Stdout = os.Stdout
  81. cmd.Stderr = os.Stderr
  82. err := cmd.Run()
  83. if err != nil {
  84. return fmt.Errorf("error running mdadm command: %v", err)
  85. }
  86. return nil
  87. }
  88. // GetRAIDDevicesFromProcMDStat retrieves information about RAID devices from /proc/mdstat.
  89. // if your RAID array is in auto-read-only mode, it is (usually) brand new
  90. func (m *Manager) GetRAIDDevicesFromProcMDStat() ([]RAIDDevice, error) {
  91. // Execute the cat command to read /proc/mdstat
  92. cmd := exec.Command("cat", "/proc/mdstat")
  93. // Run the command and capture its output
  94. output, err := cmd.Output()
  95. if err != nil {
  96. return nil, fmt.Errorf("error running cat command: %v", err)
  97. }
  98. // Convert the output to a string and split it into lines
  99. lines := strings.Split(string(output), "\n")
  100. // Initialize an empty slice to store RAID devices
  101. raidDevices := make([]RAIDDevice, 0)
  102. // Iterate over the lines, skipping the first line (Personalities)
  103. // Lines usually looks like this
  104. // md0 : active raid1 sdc[1] sdb[0]
  105. for _, line := range lines[1:] {
  106. // Skip empty lines
  107. if line == "" {
  108. continue
  109. }
  110. // Split the line by colon (:)
  111. parts := strings.SplitN(line, " : ", 2)
  112. if len(parts) != 2 {
  113. continue
  114. }
  115. // Extract device name and status
  116. deviceName := parts[0]
  117. // Split the members string by space to get individual member devices
  118. info := strings.Fields(parts[1])
  119. if len(info) < 2 {
  120. //Malform output
  121. continue
  122. }
  123. deviceStatus := info[0]
  124. //Raid level usually appears at position 1 - 2, check both
  125. raidLevel := ""
  126. if strings.HasPrefix(info[1], "raid") {
  127. raidLevel = info[1]
  128. } else if strings.HasPrefix(info[2], "raid") {
  129. raidLevel = info[2]
  130. }
  131. //Get the members (disks) of the array
  132. members := []*RAIDMember{}
  133. for _, disk := range info[2:] {
  134. if !strings.HasPrefix(disk, "sd") {
  135. //Probably not a storage device
  136. continue
  137. }
  138. //In sda[0] format, we need to split out the number from the disk seq
  139. tmp := strings.Split(disk, "[")
  140. if len(tmp) != 2 {
  141. continue
  142. }
  143. //Convert the sequence to id
  144. diskFailed := false
  145. if strings.HasSuffix(strings.TrimSpace(tmp[1]), "(F)") {
  146. //Trim off the Fail label
  147. diskFailed = true
  148. tmp[1] = strings.TrimSuffix(strings.TrimSpace(tmp[1]), "(F)")
  149. }
  150. seqInt, err := strconv.Atoi(strings.TrimSuffix(strings.TrimSpace(tmp[1]), "]"))
  151. if err != nil {
  152. //Not an integer?
  153. log.Println("[RAID] Unable to parse " + disk + " sequence ID")
  154. continue
  155. }
  156. member := RAIDMember{
  157. Name: strings.TrimSpace(tmp[0]),
  158. Seq: seqInt,
  159. Failed: diskFailed,
  160. }
  161. members = append(members, &member)
  162. }
  163. //Sort the member disks
  164. sort.Slice(members[:], func(i, j int) bool {
  165. return members[i].Seq < members[j].Seq
  166. })
  167. // Create a RAIDDevice struct and append it to the slice
  168. raidDevice := RAIDDevice{
  169. Name: deviceName,
  170. Status: deviceStatus,
  171. Level: raidLevel,
  172. Members: members,
  173. }
  174. raidDevices = append(raidDevices, raidDevice)
  175. }
  176. return raidDevices, nil
  177. }
  178. // Check if a disk is failed in given array
  179. func (m *Manager) DiskIsFailed(mdDevice, diskPath string) (bool, error) {
  180. raidDevices, err := m.GetRAIDDeviceByDevicePath(mdDevice)
  181. if err != nil {
  182. return false, err
  183. }
  184. diskName := filepath.Base(diskPath)
  185. for _, disk := range raidDevices.Members {
  186. if disk.Name == diskName {
  187. return disk.Failed, nil
  188. }
  189. }
  190. return false, errors.New("target disk not found in this array")
  191. }
  192. // FailDisk label a disk as failed
  193. func (m *Manager) FailDisk(mdDevice, diskPath string) error {
  194. //mdadm commands require full path
  195. if !strings.HasPrefix(diskPath, "/dev/") {
  196. diskPath = filepath.Join("/dev/", diskPath)
  197. }
  198. if !strings.HasPrefix(mdDevice, "/dev/") {
  199. mdDevice = filepath.Join("/dev/", mdDevice)
  200. }
  201. cmd := exec.Command("sudo", "mdadm", mdDevice, "--fail", diskPath)
  202. if err := cmd.Run(); err != nil {
  203. return fmt.Errorf("failed to fail disk: %v", err)
  204. }
  205. return nil
  206. }
  207. // RemoveDisk removes a failed disk from the specified RAID array using mdadm.
  208. // must be failed before remove
  209. func (m *Manager) RemoveDisk(mdDevice, diskPath string) error {
  210. //mdadm commands require full path
  211. if !strings.HasPrefix(diskPath, "/dev/") {
  212. diskPath = filepath.Join("/dev/", diskPath)
  213. }
  214. if !strings.HasPrefix(mdDevice, "/dev/") {
  215. mdDevice = filepath.Join("/dev/", mdDevice)
  216. }
  217. cmd := exec.Command("sudo", "mdadm", mdDevice, "--remove", diskPath)
  218. if err := cmd.Run(); err != nil {
  219. return fmt.Errorf("failed to remove disk: %v", err)
  220. }
  221. return nil
  222. }
  223. // Add disk to a given RAID array, must be unmounted and not in-use
  224. func (m *Manager) AddDisk(mdDevice, diskPath string) error {
  225. //mdadm commands require full path
  226. if !strings.HasPrefix(diskPath, "/dev/") {
  227. diskPath = filepath.Join("/dev/", diskPath)
  228. }
  229. if !strings.HasPrefix(mdDevice, "/dev/") {
  230. mdDevice = filepath.Join("/dev/", mdDevice)
  231. }
  232. cmd := exec.Command("sudo", "mdadm", mdDevice, "--add", diskPath)
  233. if err := cmd.Run(); err != nil {
  234. return fmt.Errorf("failed to add disk: %v", err)
  235. }
  236. return nil
  237. }