cgroup_validator.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. Copyright 2016 The Kubernetes 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 system
  14. import (
  15. "bufio"
  16. "os"
  17. "strings"
  18. "github.com/pkg/errors"
  19. )
  20. var _ Validator = &CgroupsValidator{}
  21. // CgroupsValidator validates cgroup configuration.
  22. type CgroupsValidator struct {
  23. Reporter Reporter
  24. }
  25. // Name is part of the system.Validator interface.
  26. func (c *CgroupsValidator) Name() string {
  27. return "cgroups"
  28. }
  29. const (
  30. cgroupsConfigPrefix = "CGROUPS_"
  31. )
  32. // Validate is part of the system.Validator interface.
  33. func (c *CgroupsValidator) Validate(spec SysSpec) (error, error) {
  34. subsystems, err := c.getCgroupSubsystems()
  35. if err != nil {
  36. return nil, errors.Wrap(err, "failed to get cgroup subsystems")
  37. }
  38. return nil, c.validateCgroupSubsystems(spec.Cgroups, subsystems)
  39. }
  40. func (c *CgroupsValidator) validateCgroupSubsystems(cgroupSpec, subsystems []string) error {
  41. missing := []string{}
  42. for _, cgroup := range cgroupSpec {
  43. found := false
  44. for _, subsystem := range subsystems {
  45. if cgroup == subsystem {
  46. found = true
  47. break
  48. }
  49. }
  50. item := cgroupsConfigPrefix + strings.ToUpper(cgroup)
  51. if found {
  52. c.Reporter.Report(item, "enabled", good)
  53. } else {
  54. c.Reporter.Report(item, "missing", bad)
  55. missing = append(missing, cgroup)
  56. }
  57. }
  58. if len(missing) > 0 {
  59. return errors.Errorf("missing cgroups: %s", strings.Join(missing, " "))
  60. }
  61. return nil
  62. }
  63. func (c *CgroupsValidator) getCgroupSubsystems() ([]string, error) {
  64. f, err := os.Open("/proc/cgroups")
  65. if err != nil {
  66. return nil, err
  67. }
  68. defer f.Close()
  69. subsystems := []string{}
  70. s := bufio.NewScanner(f)
  71. for s.Scan() {
  72. if err := s.Err(); err != nil {
  73. return nil, err
  74. }
  75. text := s.Text()
  76. if text[0] != '#' {
  77. parts := strings.Fields(text)
  78. if len(parts) >= 4 && parts[3] != "0" {
  79. subsystems = append(subsystems, parts[0])
  80. }
  81. }
  82. }
  83. return subsystems, nil
  84. }