paths.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright The containerd Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cgroup2
  14. import (
  15. "fmt"
  16. "path/filepath"
  17. "strings"
  18. )
  19. // NestedGroupPath will nest the cgroups based on the calling processes cgroup
  20. // placing its child processes inside its own path
  21. func NestedGroupPath(suffix string) (string, error) {
  22. path, err := parseCgroupFile("/proc/self/cgroup")
  23. if err != nil {
  24. return "", err
  25. }
  26. return filepath.Join(path, suffix), nil
  27. }
  28. // PidGroupPath will return the correct cgroup paths for an existing process running inside a cgroup
  29. // This is commonly used for the Load function to restore an existing container
  30. func PidGroupPath(pid int) (string, error) {
  31. p := fmt.Sprintf("/proc/%d/cgroup", pid)
  32. return parseCgroupFile(p)
  33. }
  34. // VerifyGroupPath verifies the format of group path string g.
  35. // The format is same as the third field in /proc/PID/cgroup.
  36. // e.g. "/user.slice/user-1001.slice/session-1.scope"
  37. //
  38. // g must be a "clean" absolute path starts with "/", and must not contain "/sys/fs/cgroup" prefix.
  39. //
  40. // VerifyGroupPath doesn't verify whether g actually exists on the system.
  41. func VerifyGroupPath(g string) error {
  42. if !strings.HasPrefix(g, "/") {
  43. return ErrInvalidGroupPath
  44. }
  45. if filepath.Clean(g) != g {
  46. return ErrInvalidGroupPath
  47. }
  48. if strings.HasPrefix(g, "/sys/fs/cgroup") {
  49. return ErrInvalidGroupPath
  50. }
  51. return nil
  52. }