raid.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package raid
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "path/filepath"
  8. "imuslab.com/arozos/mod/apt"
  9. "imuslab.com/arozos/mod/utils"
  10. )
  11. /*
  12. RAID management package for handling RAID and Virtual Image Creation
  13. for Linux with mdadm installed
  14. */
  15. type Options struct {
  16. }
  17. type Manager struct {
  18. Usable bool //If Manager can be used. Return false if package missing or not found
  19. Options *Options
  20. }
  21. // Create a new raid manager
  22. func NewRaidManager(options *Options) (*Manager, error) {
  23. //Check if mdadm exists
  24. mdadmExists, err := apt.PackageExists("mdadm")
  25. if err != nil {
  26. mdadmExists = false
  27. }
  28. return &Manager{
  29. Usable: mdadmExists,
  30. Options: options,
  31. }, nil
  32. }
  33. // Create a virtual image partition at given path with given size
  34. func CreateVirtualPartition(imagePath string, totalSize int64) error {
  35. cmd := exec.Command("sudo", "dd", "if=/dev/zero", "of="+imagePath, "bs=4M", "count="+fmt.Sprintf("%dM", totalSize/(4*1024*1024)))
  36. cmd.Stdout = os.Stdout
  37. cmd.Stderr = os.Stderr
  38. err := cmd.Run()
  39. if err != nil {
  40. return fmt.Errorf("dd error: %v", err)
  41. }
  42. return nil
  43. }
  44. // Format the given image file
  45. func FormatVirtualPartition(imagePath string) error {
  46. //Check if image actually exists
  47. if !utils.FileExists(imagePath) {
  48. return errors.New("image file not exists")
  49. }
  50. if filepath.Ext(imagePath) != ".img" {
  51. return errors.New("given file is not an image path")
  52. }
  53. cmd := exec.Command("sudo", "mkfs.ext4", imagePath)
  54. cmd.Stdout = os.Stdout
  55. cmd.Stderr = os.Stderr
  56. err := cmd.Run()
  57. if err != nil {
  58. return fmt.Errorf("error running mkfs.ext4 command: %v", err)
  59. }
  60. return nil
  61. }