diskfs.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package diskfs
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "regexp"
  12. "strings"
  13. "imuslab.com/arozos/mod/utils"
  14. )
  15. /*
  16. diskfs.go
  17. This module handle file system creation and formatting
  18. */
  19. // Storage Device meta was generated by lsblk
  20. // Partitions like sdX0
  21. type PartitionMeta struct {
  22. Name string `json:"name"`
  23. MajMin string `json:"maj:min"`
  24. Rm bool `json:"rm"`
  25. Size int64 `json:"size"`
  26. Ro bool `json:"ro"`
  27. Type string `json:"type"`
  28. Mountpoint string `json:"mountpoint"`
  29. }
  30. // Block device, usually disk or rom, like sdX
  31. type BlockDeviceMeta struct {
  32. Name string `json:"name"`
  33. MajMin string `json:"maj:min"`
  34. Rm bool `json:"rm"`
  35. Size int64 `json:"size"`
  36. Ro bool `json:"ro"`
  37. Type string `json:"type"`
  38. Mountpoint string `json:"mountpoint"`
  39. Children []PartitionMeta `json:"children,omitempty"`
  40. }
  41. // A collection of information for lsblk output
  42. type StorageDevicesMeta struct {
  43. Blockdevices []BlockDeviceMeta `json:"blockdevices"`
  44. }
  45. // Check if the file format driver is installed on this host
  46. // if a format is supported, mkfs.(format) should be symlinked under /sbin
  47. func FormatPackageInstalled(fsType string) bool {
  48. return utils.FileExists("/sbin/mkfs." + fsType)
  49. }
  50. // Create file system, support ntfs, ext4 and fat32 only
  51. func FormatStorageDevice(fsType string, devicePath string) error {
  52. // Check if the filesystem type is supported
  53. switch fsType {
  54. case "ext4":
  55. // Format the device with the specified filesystem type
  56. cmd := exec.Command("sudo", "mkfs."+fsType, devicePath)
  57. output, err := cmd.CombinedOutput()
  58. if err != nil {
  59. return errors.New("unable to format device: " + string(output))
  60. }
  61. return nil
  62. case "vfat", "fat", "fat32":
  63. //Check if mkfs.fat exists
  64. if !FormatPackageInstalled("vfat") {
  65. return errors.New("unable to format device as fat (vfat). dosfstools not installed?")
  66. }
  67. // Format the device with the specified filesystem type
  68. cmd := exec.Command("sudo", "mkfs.vfat", devicePath)
  69. output, err := cmd.CombinedOutput()
  70. if err != nil {
  71. return errors.New("unable to format device: " + string(output))
  72. }
  73. return nil
  74. case "ntfs":
  75. //Check if ntfs-3g exists
  76. if !FormatPackageInstalled("ntfs") {
  77. return errors.New("unable to format device as ntfs: ntfs-3g not installed?")
  78. }
  79. //Format the drive
  80. cmd := exec.Command("sudo", "mkfs.ntfs", devicePath)
  81. output, err := cmd.CombinedOutput()
  82. if err != nil {
  83. return errors.New("unable to format device: " + string(output))
  84. }
  85. return nil
  86. default:
  87. return fmt.Errorf("unsupported filesystem type: %s", fsType)
  88. }
  89. }
  90. // List all the storage device in the system, set minSize to 0 for no filter
  91. func ListAllStorageDevices() (*StorageDevicesMeta, error) {
  92. cmd := exec.Command("sudo", "lsblk", "-b", "--json")
  93. output, err := cmd.CombinedOutput()
  94. if err != nil {
  95. return nil, fmt.Errorf("lsblk error: %v", err)
  96. }
  97. var devices StorageDevicesMeta
  98. err = json.Unmarshal([]byte(output), &devices)
  99. return &devices, err
  100. }
  101. // Get block device (e.g. /dev/sdX) info
  102. func GetBlockDeviceMeta(devicePath string) (*BlockDeviceMeta, error) {
  103. //Trim the /dev/ part of the device path
  104. deviceName := strings.TrimPrefix(devicePath, "/dev/")
  105. if len(deviceName) == 0 {
  106. return nil, errors.New("invalid device path given")
  107. }
  108. re := regexp.MustCompile(`\d+`)
  109. if re.MatchString(deviceName) {
  110. //This is a partition
  111. return nil, errors.New("given device path is a partition not a block device")
  112. }
  113. storageMeta, err := ListAllStorageDevices()
  114. if err != nil {
  115. return nil, err
  116. }
  117. for _, blockdevice := range storageMeta.Blockdevices {
  118. if blockdevice.Name == deviceName {
  119. return &blockdevice, nil
  120. }
  121. }
  122. return nil, errors.New("target block device not found")
  123. }
  124. // Get partition information (e.g. /dev/sdX1)
  125. func GetPartitionMeta(devicePath string) (*PartitionMeta, error) {
  126. //Trim the /dev/ part of the device path
  127. deviceName := strings.TrimPrefix(devicePath, "/dev/")
  128. if len(deviceName) == 0 {
  129. return nil, errors.New("invalid device path given")
  130. }
  131. re := regexp.MustCompile(`\d+`)
  132. if !re.MatchString(deviceName) {
  133. //This is a partition
  134. return nil, errors.New("given device path is a block device not a partition")
  135. }
  136. storageMeta, err := ListAllStorageDevices()
  137. if err != nil {
  138. return nil, err
  139. }
  140. for _, blockdevice := range storageMeta.Blockdevices {
  141. if strings.Contains(deviceName, blockdevice.Name) {
  142. //Matching block device. Check for if there are a matching child
  143. for _, childPartition := range blockdevice.Children {
  144. if childPartition.Name == deviceName {
  145. return &childPartition, nil
  146. }
  147. }
  148. }
  149. }
  150. return nil, errors.New("target partition not found")
  151. }
  152. // Check if a device is mounted given the path name, like /dev/sdc
  153. func DeviceIsMounted(devicePath string) (bool, error) {
  154. // Open the mountinfo file
  155. file, err := os.Open("/proc/mounts")
  156. if err != nil {
  157. return false, fmt.Errorf("error opening /proc/mounts: %v", err)
  158. }
  159. defer file.Close()
  160. if !strings.HasPrefix(devicePath, "/dev/") {
  161. devicePath = filepath.Join("/dev/", devicePath)
  162. }
  163. // Scan the mountinfo file line by line
  164. scanner := bufio.NewScanner(file)
  165. for scanner.Scan() {
  166. line := scanner.Text()
  167. fields := strings.Fields(line)
  168. if strings.EqualFold(strings.TrimSpace(fields[0]), devicePath) {
  169. // Device is mounted
  170. return true, nil
  171. }
  172. }
  173. // Device is not mounted
  174. return false, nil
  175. }
  176. // UnmountDevice unmounts the specified device.
  177. // Remember to use full path (e.g. /dev/md0) in the devicePath
  178. func UnmountDevice(devicePath string) error {
  179. // Construct the bash command to unmount the device
  180. cmd := exec.Command("sudo", "bash", "-c", fmt.Sprintf("umount -l %s", devicePath))
  181. // Run the command
  182. output, err := cmd.CombinedOutput()
  183. if err != nil {
  184. log.Println("[RAID] Unable to unmount device: " + string(output))
  185. return fmt.Errorf("error unmounting device: %v", err)
  186. }
  187. return nil
  188. }
  189. // Force Version of Unmount (dangerous)
  190. // Remember to use full path (e.g. /dev/md0) in the devicePath
  191. func ForceUnmountDevice(devicePath string) error {
  192. // Construct the bash command to unmount the device
  193. cmd := exec.Command("sudo", "bash", "-c", fmt.Sprintf("umount -l %s", devicePath))
  194. // Run the command
  195. err := cmd.Run()
  196. if err != nil {
  197. return fmt.Errorf("error unmounting device: %v", err)
  198. }
  199. return nil
  200. }
  201. // DANGER: Wipe the whole disk given the disk path
  202. func WipeDisk(diskPath string) error {
  203. // Unmount the disk
  204. isMounted, _ := DeviceIsMounted(diskPath)
  205. if isMounted {
  206. umountCmd := exec.Command("sudo", "umount", diskPath)
  207. if err := umountCmd.Run(); err != nil {
  208. return fmt.Errorf("error unmounting disk %s: %v", diskPath, err)
  209. }
  210. }
  211. // Wipe all filesystem signatures on the entire disk
  212. wipeCmd := exec.Command("sudo", "wipefs", "--all", "--force", diskPath)
  213. if err := wipeCmd.Run(); err != nil {
  214. return fmt.Errorf("error wiping filesystem signatures on %s: %v", diskPath, err)
  215. }
  216. return nil
  217. }