mdstat.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. // Copyright 2018 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package procfs
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "regexp"
  18. "strconv"
  19. "strings"
  20. )
  21. var (
  22. statusLineRE = regexp.MustCompile(`(\d+) blocks .*\[(\d+)/(\d+)\] \[[U_]+\]`)
  23. recoveryLineRE = regexp.MustCompile(`\((\d+)/\d+\)`)
  24. componentDeviceRE = regexp.MustCompile(`(.*)\[\d+\]`)
  25. )
  26. // MDStat holds info parsed from /proc/mdstat.
  27. type MDStat struct {
  28. // Name of the device.
  29. Name string
  30. // activity-state of the device.
  31. ActivityState string
  32. // Number of active disks.
  33. DisksActive int64
  34. // Total number of disks the device requires.
  35. DisksTotal int64
  36. // Number of failed disks.
  37. DisksFailed int64
  38. // Spare disks in the device.
  39. DisksSpare int64
  40. // Number of blocks the device holds.
  41. BlocksTotal int64
  42. // Number of blocks on the device that are in sync.
  43. BlocksSynced int64
  44. // Name of md component devices
  45. Devices []string
  46. }
  47. // MDStat parses an mdstat-file (/proc/mdstat) and returns a slice of
  48. // structs containing the relevant info. More information available here:
  49. // https://raid.wiki.kernel.org/index.php/Mdstat
  50. func (fs FS) MDStat() ([]MDStat, error) {
  51. data, err := ioutil.ReadFile(fs.proc.Path("mdstat"))
  52. if err != nil {
  53. return nil, err
  54. }
  55. mdstat, err := parseMDStat(data)
  56. if err != nil {
  57. return nil, fmt.Errorf("error parsing mdstat %q: %w", fs.proc.Path("mdstat"), err)
  58. }
  59. return mdstat, nil
  60. }
  61. // parseMDStat parses data from mdstat file (/proc/mdstat) and returns a slice of
  62. // structs containing the relevant info.
  63. func parseMDStat(mdStatData []byte) ([]MDStat, error) {
  64. mdStats := []MDStat{}
  65. lines := strings.Split(string(mdStatData), "\n")
  66. for i, line := range lines {
  67. if strings.TrimSpace(line) == "" || line[0] == ' ' ||
  68. strings.HasPrefix(line, "Personalities") ||
  69. strings.HasPrefix(line, "unused") {
  70. continue
  71. }
  72. deviceFields := strings.Fields(line)
  73. if len(deviceFields) < 3 {
  74. return nil, fmt.Errorf("not enough fields in mdline (expected at least 3): %s", line)
  75. }
  76. mdName := deviceFields[0] // mdx
  77. state := deviceFields[2] // active or inactive
  78. if len(lines) <= i+3 {
  79. return nil, fmt.Errorf("error parsing %q: too few lines for md device", mdName)
  80. }
  81. // Failed disks have the suffix (F) & Spare disks have the suffix (S).
  82. fail := int64(strings.Count(line, "(F)"))
  83. spare := int64(strings.Count(line, "(S)"))
  84. active, total, size, err := evalStatusLine(lines[i], lines[i+1])
  85. if err != nil {
  86. return nil, fmt.Errorf("error parsing md device lines: %w", err)
  87. }
  88. syncLineIdx := i + 2
  89. if strings.Contains(lines[i+2], "bitmap") { // skip bitmap line
  90. syncLineIdx++
  91. }
  92. // If device is syncing at the moment, get the number of currently
  93. // synced bytes, otherwise that number equals the size of the device.
  94. syncedBlocks := size
  95. recovering := strings.Contains(lines[syncLineIdx], "recovery")
  96. resyncing := strings.Contains(lines[syncLineIdx], "resync")
  97. checking := strings.Contains(lines[syncLineIdx], "check")
  98. // Append recovery and resyncing state info.
  99. if recovering || resyncing || checking {
  100. if recovering {
  101. state = "recovering"
  102. } else if checking {
  103. state = "checking"
  104. } else {
  105. state = "resyncing"
  106. }
  107. // Handle case when resync=PENDING or resync=DELAYED.
  108. if strings.Contains(lines[syncLineIdx], "PENDING") ||
  109. strings.Contains(lines[syncLineIdx], "DELAYED") {
  110. syncedBlocks = 0
  111. } else {
  112. syncedBlocks, err = evalRecoveryLine(lines[syncLineIdx])
  113. if err != nil {
  114. return nil, fmt.Errorf("error parsing sync line in md device %q: %w", mdName, err)
  115. }
  116. }
  117. }
  118. mdStats = append(mdStats, MDStat{
  119. Name: mdName,
  120. ActivityState: state,
  121. DisksActive: active,
  122. DisksFailed: fail,
  123. DisksSpare: spare,
  124. DisksTotal: total,
  125. BlocksTotal: size,
  126. BlocksSynced: syncedBlocks,
  127. Devices: evalComponentDevices(deviceFields),
  128. })
  129. }
  130. return mdStats, nil
  131. }
  132. func evalStatusLine(deviceLine, statusLine string) (active, total, size int64, err error) {
  133. sizeStr := strings.Fields(statusLine)[0]
  134. size, err = strconv.ParseInt(sizeStr, 10, 64)
  135. if err != nil {
  136. return 0, 0, 0, fmt.Errorf("unexpected statusLine %q: %w", statusLine, err)
  137. }
  138. if strings.Contains(deviceLine, "raid0") || strings.Contains(deviceLine, "linear") {
  139. // In the device deviceLine, only disks have a number associated with them in [].
  140. total = int64(strings.Count(deviceLine, "["))
  141. return total, total, size, nil
  142. }
  143. if strings.Contains(deviceLine, "inactive") {
  144. return 0, 0, size, nil
  145. }
  146. matches := statusLineRE.FindStringSubmatch(statusLine)
  147. if len(matches) != 4 {
  148. return 0, 0, 0, fmt.Errorf("couldn't find all the substring matches: %s", statusLine)
  149. }
  150. total, err = strconv.ParseInt(matches[2], 10, 64)
  151. if err != nil {
  152. return 0, 0, 0, fmt.Errorf("unexpected statusLine %q: %w", statusLine, err)
  153. }
  154. active, err = strconv.ParseInt(matches[3], 10, 64)
  155. if err != nil {
  156. return 0, 0, 0, fmt.Errorf("unexpected statusLine %q: %w", statusLine, err)
  157. }
  158. return active, total, size, nil
  159. }
  160. func evalRecoveryLine(recoveryLine string) (syncedBlocks int64, err error) {
  161. matches := recoveryLineRE.FindStringSubmatch(recoveryLine)
  162. if len(matches) != 2 {
  163. return 0, fmt.Errorf("unexpected recoveryLine: %s", recoveryLine)
  164. }
  165. syncedBlocks, err = strconv.ParseInt(matches[1], 10, 64)
  166. if err != nil {
  167. return 0, fmt.Errorf("error parsing int from recoveryLine %q: %w", recoveryLine, err)
  168. }
  169. return syncedBlocks, nil
  170. }
  171. func evalComponentDevices(deviceFields []string) []string {
  172. mdComponentDevices := make([]string, 0)
  173. if len(deviceFields) > 3 {
  174. for _, field := range deviceFields[4:] {
  175. match := componentDeviceRE.FindStringSubmatch(field)
  176. if match == nil {
  177. continue
  178. }
  179. mdComponentDevices = append(mdComponentDevices, match[1])
  180. }
  181. }
  182. return mdComponentDevices
  183. }