util_linux.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // +build linux
  2. package util
  3. import (
  4. "bufio"
  5. "bytes"
  6. "os"
  7. "os/exec"
  8. "strings"
  9. "syscall"
  10. "github.com/docker/docker/pkg/mount"
  11. "github.com/rancher/os/log"
  12. )
  13. func mountProc() error {
  14. if _, err := os.Stat("/proc/self/mountinfo"); os.IsNotExist(err) {
  15. if _, err := os.Stat("/proc"); os.IsNotExist(err) {
  16. if err = os.Mkdir("/proc", 0755); err != nil {
  17. return err
  18. }
  19. }
  20. if err := syscall.Mount("none", "/proc", "proc", 0, ""); err != nil {
  21. return err
  22. }
  23. }
  24. return nil
  25. }
  26. func Mount(device, directory, fsType, options string) error {
  27. if err := mountProc(); err != nil {
  28. return nil
  29. }
  30. if _, err := os.Stat(directory); os.IsNotExist(err) {
  31. err = os.MkdirAll(directory, 0755)
  32. if err != nil {
  33. return err
  34. }
  35. }
  36. return mount.Mount(device, directory, fsType, options)
  37. }
  38. func Unmount(target string) error {
  39. return mount.Unmount(target)
  40. }
  41. func Blkid(label string) (deviceName, deviceType string) {
  42. // Not all blkid's have `blkid -L label (see busybox/alpine)
  43. cmd := exec.Command("blkid")
  44. cmd.Stderr = os.Stderr
  45. out, err := cmd.Output()
  46. if err != nil {
  47. log.Errorf("Failed to run blkid: %s", err)
  48. return
  49. }
  50. r := bytes.NewReader(out)
  51. s := bufio.NewScanner(r)
  52. for s.Scan() {
  53. line := s.Text()
  54. //log.Debugf("blkid: %s", cmd, line)
  55. if !strings.Contains(line, `LABEL="`+label+`"`) {
  56. continue
  57. }
  58. d := strings.Split(line, ":")
  59. deviceName = d[0]
  60. s1 := strings.Split(line, `TYPE="`)
  61. s2 := strings.Split(s1[1], `"`)
  62. deviceType = s2[0]
  63. log.Debugf("blkid type of %s: %s", deviceName, deviceType)
  64. return
  65. }
  66. return
  67. }