utils.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // +build linux
  2. package cgroups
  3. import (
  4. "bufio"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/docker/go-units"
  14. )
  15. const cgroupNamePrefix = "name="
  16. // https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt
  17. func FindCgroupMountpoint(subsystem string) (string, error) {
  18. // We are not using mount.GetMounts() because it's super-inefficient,
  19. // parsing it directly sped up x10 times because of not using Sscanf.
  20. // It was one of two major performance drawbacks in container start.
  21. f, err := os.Open("/proc/self/mountinfo")
  22. if err != nil {
  23. return "", err
  24. }
  25. defer f.Close()
  26. scanner := bufio.NewScanner(f)
  27. for scanner.Scan() {
  28. txt := scanner.Text()
  29. fields := strings.Split(txt, " ")
  30. for _, opt := range strings.Split(fields[len(fields)-1], ",") {
  31. if opt == subsystem {
  32. return fields[4], nil
  33. }
  34. }
  35. }
  36. if err := scanner.Err(); err != nil {
  37. return "", err
  38. }
  39. return "", NewNotFoundError(subsystem)
  40. }
  41. func FindCgroupMountpointAndRoot(subsystem string) (string, string, error) {
  42. f, err := os.Open("/proc/self/mountinfo")
  43. if err != nil {
  44. return "", "", err
  45. }
  46. defer f.Close()
  47. scanner := bufio.NewScanner(f)
  48. for scanner.Scan() {
  49. txt := scanner.Text()
  50. fields := strings.Split(txt, " ")
  51. for _, opt := range strings.Split(fields[len(fields)-1], ",") {
  52. if opt == subsystem {
  53. return fields[4], fields[3], nil
  54. }
  55. }
  56. }
  57. if err := scanner.Err(); err != nil {
  58. return "", "", err
  59. }
  60. return "", "", NewNotFoundError(subsystem)
  61. }
  62. func FindCgroupMountpointDir() (string, error) {
  63. f, err := os.Open("/proc/self/mountinfo")
  64. if err != nil {
  65. return "", err
  66. }
  67. defer f.Close()
  68. scanner := bufio.NewScanner(f)
  69. for scanner.Scan() {
  70. text := scanner.Text()
  71. fields := strings.Split(text, " ")
  72. // Safe as mountinfo encodes mountpoints with spaces as \040.
  73. index := strings.Index(text, " - ")
  74. postSeparatorFields := strings.Fields(text[index+3:])
  75. numPostFields := len(postSeparatorFields)
  76. // This is an error as we can't detect if the mount is for "cgroup"
  77. if numPostFields == 0 {
  78. return "", fmt.Errorf("Found no fields post '-' in %q", text)
  79. }
  80. if postSeparatorFields[0] == "cgroup" {
  81. // Check that the mount is properly formated.
  82. if numPostFields < 3 {
  83. return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
  84. }
  85. return filepath.Dir(fields[4]), nil
  86. }
  87. }
  88. if err := scanner.Err(); err != nil {
  89. return "", err
  90. }
  91. return "", NewNotFoundError("cgroup")
  92. }
  93. type Mount struct {
  94. Mountpoint string
  95. Root string
  96. Subsystems []string
  97. }
  98. func (m Mount) GetThisCgroupDir(cgroups map[string]string) (string, error) {
  99. if len(m.Subsystems) == 0 {
  100. return "", fmt.Errorf("no subsystem for mount")
  101. }
  102. return getControllerPath(m.Subsystems[0], cgroups)
  103. }
  104. func getCgroupMountsHelper(ss map[string]bool, mi io.Reader) ([]Mount, error) {
  105. res := make([]Mount, 0, len(ss))
  106. scanner := bufio.NewScanner(mi)
  107. for scanner.Scan() {
  108. txt := scanner.Text()
  109. sepIdx := strings.Index(txt, " - ")
  110. if sepIdx == -1 {
  111. return nil, fmt.Errorf("invalid mountinfo format")
  112. }
  113. if txt[sepIdx+3:sepIdx+9] != "cgroup" {
  114. continue
  115. }
  116. fields := strings.Split(txt, " ")
  117. m := Mount{
  118. Mountpoint: fields[4],
  119. Root: fields[3],
  120. }
  121. for _, opt := range strings.Split(fields[len(fields)-1], ",") {
  122. if strings.HasPrefix(opt, cgroupNamePrefix) {
  123. m.Subsystems = append(m.Subsystems, opt[len(cgroupNamePrefix):])
  124. }
  125. if ss[opt] {
  126. m.Subsystems = append(m.Subsystems, opt)
  127. }
  128. }
  129. res = append(res, m)
  130. }
  131. if err := scanner.Err(); err != nil {
  132. return nil, err
  133. }
  134. return res, nil
  135. }
  136. func GetCgroupMounts() ([]Mount, error) {
  137. f, err := os.Open("/proc/self/mountinfo")
  138. if err != nil {
  139. return nil, err
  140. }
  141. defer f.Close()
  142. all, err := GetAllSubsystems()
  143. if err != nil {
  144. return nil, err
  145. }
  146. allMap := make(map[string]bool)
  147. for _, s := range all {
  148. allMap[s] = true
  149. }
  150. return getCgroupMountsHelper(allMap, f)
  151. }
  152. // Returns all the cgroup subsystems supported by the kernel
  153. func GetAllSubsystems() ([]string, error) {
  154. f, err := os.Open("/proc/cgroups")
  155. if err != nil {
  156. return nil, err
  157. }
  158. defer f.Close()
  159. subsystems := []string{}
  160. s := bufio.NewScanner(f)
  161. for s.Scan() {
  162. if err := s.Err(); err != nil {
  163. return nil, err
  164. }
  165. text := s.Text()
  166. if text[0] != '#' {
  167. parts := strings.Fields(text)
  168. if len(parts) >= 4 && parts[3] != "0" {
  169. subsystems = append(subsystems, parts[0])
  170. }
  171. }
  172. }
  173. return subsystems, nil
  174. }
  175. // Returns the relative path to the cgroup docker is running in.
  176. func GetThisCgroupDir(subsystem string) (string, error) {
  177. cgroups, err := ParseCgroupFile("/proc/self/cgroup")
  178. if err != nil {
  179. return "", err
  180. }
  181. return getControllerPath(subsystem, cgroups)
  182. }
  183. func GetInitCgroupDir(subsystem string) (string, error) {
  184. cgroups, err := ParseCgroupFile("/proc/1/cgroup")
  185. if err != nil {
  186. return "", err
  187. }
  188. return getControllerPath(subsystem, cgroups)
  189. }
  190. func readProcsFile(dir string) ([]int, error) {
  191. f, err := os.Open(filepath.Join(dir, "cgroup.procs"))
  192. if err != nil {
  193. return nil, err
  194. }
  195. defer f.Close()
  196. var (
  197. s = bufio.NewScanner(f)
  198. out = []int{}
  199. )
  200. for s.Scan() {
  201. if t := s.Text(); t != "" {
  202. pid, err := strconv.Atoi(t)
  203. if err != nil {
  204. return nil, err
  205. }
  206. out = append(out, pid)
  207. }
  208. }
  209. return out, nil
  210. }
  211. func ParseCgroupFile(path string) (map[string]string, error) {
  212. f, err := os.Open(path)
  213. if err != nil {
  214. return nil, err
  215. }
  216. defer f.Close()
  217. s := bufio.NewScanner(f)
  218. cgroups := make(map[string]string)
  219. for s.Scan() {
  220. if err := s.Err(); err != nil {
  221. return nil, err
  222. }
  223. text := s.Text()
  224. parts := strings.Split(text, ":")
  225. for _, subs := range strings.Split(parts[1], ",") {
  226. cgroups[subs] = parts[2]
  227. }
  228. }
  229. return cgroups, nil
  230. }
  231. func getControllerPath(subsystem string, cgroups map[string]string) (string, error) {
  232. if p, ok := cgroups[subsystem]; ok {
  233. return p, nil
  234. }
  235. if p, ok := cgroups[cgroupNamePrefix+subsystem]; ok {
  236. return p, nil
  237. }
  238. return "", NewNotFoundError(subsystem)
  239. }
  240. func PathExists(path string) bool {
  241. if _, err := os.Stat(path); err != nil {
  242. return false
  243. }
  244. return true
  245. }
  246. func EnterPid(cgroupPaths map[string]string, pid int) error {
  247. for _, path := range cgroupPaths {
  248. if PathExists(path) {
  249. if err := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"),
  250. []byte(strconv.Itoa(pid)), 0700); err != nil {
  251. return err
  252. }
  253. }
  254. }
  255. return nil
  256. }
  257. // RemovePaths iterates over the provided paths removing them.
  258. // We trying to remove all paths five times with increasing delay between tries.
  259. // If after all there are not removed cgroups - appropriate error will be
  260. // returned.
  261. func RemovePaths(paths map[string]string) (err error) {
  262. delay := 10 * time.Millisecond
  263. for i := 0; i < 5; i++ {
  264. if i != 0 {
  265. time.Sleep(delay)
  266. delay *= 2
  267. }
  268. for s, p := range paths {
  269. os.RemoveAll(p)
  270. // TODO: here probably should be logging
  271. _, err := os.Stat(p)
  272. // We need this strange way of checking cgroups existence because
  273. // RemoveAll almost always returns error, even on already removed
  274. // cgroups
  275. if os.IsNotExist(err) {
  276. delete(paths, s)
  277. }
  278. }
  279. if len(paths) == 0 {
  280. return nil
  281. }
  282. }
  283. return fmt.Errorf("Failed to remove paths: %v", paths)
  284. }
  285. func GetHugePageSize() ([]string, error) {
  286. var pageSizes []string
  287. sizeList := []string{"B", "kB", "MB", "GB", "TB", "PB"}
  288. files, err := ioutil.ReadDir("/sys/kernel/mm/hugepages")
  289. if err != nil {
  290. return pageSizes, err
  291. }
  292. for _, st := range files {
  293. nameArray := strings.Split(st.Name(), "-")
  294. pageSize, err := units.RAMInBytes(nameArray[1])
  295. if err != nil {
  296. return []string{}, err
  297. }
  298. sizeString := units.CustomSize("%g%s", float64(pageSize), 1024.0, sizeList)
  299. pageSizes = append(pageSizes, sizeString)
  300. }
  301. return pageSizes, nil
  302. }
  303. // GetPids returns all pids, that were added to cgroup at path.
  304. func GetPids(path string) ([]int, error) {
  305. return readProcsFile(path)
  306. }
  307. // GetAllPids returns all pids, that were added to cgroup at path and to all its
  308. // subcgroups.
  309. func GetAllPids(path string) ([]int, error) {
  310. var pids []int
  311. // collect pids from all sub-cgroups
  312. err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error {
  313. dir, file := filepath.Split(p)
  314. if file != "cgroup.procs" {
  315. return nil
  316. }
  317. if iErr != nil {
  318. return iErr
  319. }
  320. cPids, err := readProcsFile(dir)
  321. if err != nil {
  322. return err
  323. }
  324. pids = append(pids, cPids...)
  325. return nil
  326. })
  327. return pids, err
  328. }