mount.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package mount
  2. import (
  3. "time"
  4. )
  5. func GetMounts() ([]*MountInfo, error) {
  6. return parseMountTable()
  7. }
  8. // Looks at /proc/self/mountinfo to determine of the specified
  9. // mountpoint has been mounted
  10. func Mounted(mountpoint string) (bool, error) {
  11. entries, err := parseMountTable()
  12. if err != nil {
  13. return false, err
  14. }
  15. // Search the table for the mountpoint
  16. for _, e := range entries {
  17. if e.Mountpoint == mountpoint {
  18. return true, nil
  19. }
  20. }
  21. return false, nil
  22. }
  23. // Mount the specified options at the target path
  24. // Options must be specified as fstab style
  25. func Mount(device, target, mType, options string) error {
  26. if mounted, err := Mounted(target); err != nil || mounted {
  27. return err
  28. }
  29. flag, data := parseOptions(options)
  30. if err := mount(device, target, mType, uintptr(flag), data); err != nil {
  31. return err
  32. }
  33. return nil
  34. }
  35. // Unmount the target only if it is mounted
  36. func Unmount(target string) (err error) {
  37. if mounted, err := Mounted(target); err != nil || !mounted {
  38. return err
  39. }
  40. // Simple retry logic for unmount
  41. for i := 0; i < 10; i++ {
  42. if err = unmount(target, 0); err == nil {
  43. return nil
  44. }
  45. time.Sleep(100 * time.Millisecond)
  46. }
  47. return
  48. }