file.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package cgroups
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "github.com/sirupsen/logrus"
  12. "golang.org/x/sys/unix"
  13. )
  14. // OpenFile opens a cgroup file in a given dir with given flags.
  15. // It is supposed to be used for cgroup files only, and returns
  16. // an error if the file is not a cgroup file.
  17. //
  18. // Arguments dir and file are joined together to form an absolute path
  19. // to a file being opened.
  20. func OpenFile(dir, file string, flags int) (*os.File, error) {
  21. if dir == "" {
  22. return nil, fmt.Errorf("no directory specified for %s", file)
  23. }
  24. return openFile(dir, file, flags)
  25. }
  26. // ReadFile reads data from a cgroup file in dir.
  27. // It is supposed to be used for cgroup files only.
  28. func ReadFile(dir, file string) (string, error) {
  29. fd, err := OpenFile(dir, file, unix.O_RDONLY)
  30. if err != nil {
  31. return "", err
  32. }
  33. defer fd.Close()
  34. var buf bytes.Buffer
  35. _, err = buf.ReadFrom(fd)
  36. return buf.String(), err
  37. }
  38. // WriteFile writes data to a cgroup file in dir.
  39. // It is supposed to be used for cgroup files only.
  40. func WriteFile(dir, file, data string) error {
  41. fd, err := OpenFile(dir, file, unix.O_WRONLY)
  42. if err != nil {
  43. return err
  44. }
  45. defer fd.Close()
  46. if err := retryingWriteFile(fd, data); err != nil {
  47. // Having data in the error message helps in debugging.
  48. return fmt.Errorf("failed to write %q: %w", data, err)
  49. }
  50. return nil
  51. }
  52. func retryingWriteFile(fd *os.File, data string) error {
  53. for {
  54. _, err := fd.Write([]byte(data))
  55. if errors.Is(err, unix.EINTR) {
  56. logrus.Infof("interrupted while writing %s to %s", data, fd.Name())
  57. continue
  58. }
  59. return err
  60. }
  61. }
  62. const (
  63. cgroupfsDir = "/sys/fs/cgroup"
  64. cgroupfsPrefix = cgroupfsDir + "/"
  65. )
  66. var (
  67. // TestMode is set to true by unit tests that need "fake" cgroupfs.
  68. TestMode bool
  69. cgroupFd int = -1
  70. prepOnce sync.Once
  71. prepErr error
  72. resolveFlags uint64
  73. )
  74. func prepareOpenat2() error {
  75. prepOnce.Do(func() {
  76. fd, err := unix.Openat2(-1, cgroupfsDir, &unix.OpenHow{
  77. Flags: unix.O_DIRECTORY | unix.O_PATH,
  78. })
  79. if err != nil {
  80. prepErr = &os.PathError{Op: "openat2", Path: cgroupfsDir, Err: err}
  81. if err != unix.ENOSYS { //nolint:errorlint // unix errors are bare
  82. logrus.Warnf("falling back to securejoin: %s", prepErr)
  83. } else {
  84. logrus.Debug("openat2 not available, falling back to securejoin")
  85. }
  86. return
  87. }
  88. var st unix.Statfs_t
  89. if err = unix.Fstatfs(fd, &st); err != nil {
  90. prepErr = &os.PathError{Op: "statfs", Path: cgroupfsDir, Err: err}
  91. logrus.Warnf("falling back to securejoin: %s", prepErr)
  92. return
  93. }
  94. cgroupFd = fd
  95. resolveFlags = unix.RESOLVE_BENEATH | unix.RESOLVE_NO_MAGICLINKS
  96. if st.Type == unix.CGROUP2_SUPER_MAGIC {
  97. // cgroupv2 has a single mountpoint and no "cpu,cpuacct" symlinks
  98. resolveFlags |= unix.RESOLVE_NO_XDEV | unix.RESOLVE_NO_SYMLINKS
  99. }
  100. })
  101. return prepErr
  102. }
  103. func openFile(dir, file string, flags int) (*os.File, error) {
  104. mode := os.FileMode(0)
  105. if TestMode && flags&os.O_WRONLY != 0 {
  106. // "emulate" cgroup fs for unit tests
  107. flags |= os.O_TRUNC | os.O_CREATE
  108. mode = 0o600
  109. }
  110. path := path.Join(dir, file)
  111. if prepareOpenat2() != nil {
  112. return openFallback(path, flags, mode)
  113. }
  114. relPath := strings.TrimPrefix(path, cgroupfsPrefix)
  115. if len(relPath) == len(path) { // non-standard path, old system?
  116. return openFallback(path, flags, mode)
  117. }
  118. fd, err := unix.Openat2(cgroupFd, relPath,
  119. &unix.OpenHow{
  120. Resolve: resolveFlags,
  121. Flags: uint64(flags) | unix.O_CLOEXEC,
  122. Mode: uint64(mode),
  123. })
  124. if err != nil {
  125. err = &os.PathError{Op: "openat2", Path: path, Err: err}
  126. // Check if cgroupFd is still opened to cgroupfsDir
  127. // (happens when this package is incorrectly used
  128. // across the chroot/pivot_root/mntns boundary, or
  129. // when /sys/fs/cgroup is remounted).
  130. //
  131. // TODO: if such usage will ever be common, amend this
  132. // to reopen cgroupFd and retry openat2.
  133. fdStr := strconv.Itoa(cgroupFd)
  134. fdDest, _ := os.Readlink("/proc/self/fd/" + fdStr)
  135. if fdDest != cgroupfsDir {
  136. // Wrap the error so it is clear that cgroupFd
  137. // is opened to an unexpected/wrong directory.
  138. err = fmt.Errorf("cgroupFd %s unexpectedly opened to %s != %s: %w",
  139. fdStr, fdDest, cgroupfsDir, err)
  140. }
  141. return nil, err
  142. }
  143. return os.NewFile(uintptr(fd), path), nil
  144. }
  145. var errNotCgroupfs = errors.New("not a cgroup file")
  146. // Can be changed by unit tests.
  147. var openFallback = openAndCheck
  148. // openAndCheck is used when openat2(2) is not available. It checks the opened
  149. // file is on cgroupfs, returning an error otherwise.
  150. func openAndCheck(path string, flags int, mode os.FileMode) (*os.File, error) {
  151. fd, err := os.OpenFile(path, flags, mode)
  152. if err != nil {
  153. return nil, err
  154. }
  155. if TestMode {
  156. return fd, nil
  157. }
  158. // Check this is a cgroupfs file.
  159. var st unix.Statfs_t
  160. if err := unix.Fstatfs(int(fd.Fd()), &st); err != nil {
  161. _ = fd.Close()
  162. return nil, &os.PathError{Op: "statfs", Path: path, Err: err}
  163. }
  164. if st.Type != unix.CGROUP_SUPER_MAGIC && st.Type != unix.CGROUP2_SUPER_MAGIC {
  165. _ = fd.Close()
  166. return nil, &os.PathError{Op: "open", Path: path, Err: errNotCgroupfs}
  167. }
  168. return fd, nil
  169. }