knobs_linux.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package kernel
  2. import (
  3. "context"
  4. "os"
  5. "path"
  6. "strings"
  7. "github.com/containerd/log"
  8. )
  9. // writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
  10. // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
  11. func writeSystemProperty(key, value string) error {
  12. keyPath := strings.ReplaceAll(key, ".", "/")
  13. return os.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0o644)
  14. }
  15. // readSystemProperty reads the value from the path under /proc/sys and returns it
  16. func readSystemProperty(key string) (string, error) {
  17. keyPath := strings.ReplaceAll(key, ".", "/")
  18. value, err := os.ReadFile(path.Join("/proc/sys", keyPath))
  19. if err != nil {
  20. return "", err
  21. }
  22. return strings.TrimSpace(string(value)), nil
  23. }
  24. // ApplyOSTweaks applies the configuration values passed as arguments
  25. func ApplyOSTweaks(osConfig map[string]*OSValue) {
  26. for k, v := range osConfig {
  27. // read the existing property from disk
  28. oldv, err := readSystemProperty(k)
  29. if err != nil {
  30. log.G(context.TODO()).WithError(err).Errorf("error reading the kernel parameter %s", k)
  31. continue
  32. }
  33. if propertyIsValid(oldv, v.Value, v.CheckFn) {
  34. // write new prop value to disk
  35. if err := writeSystemProperty(k, v.Value); err != nil {
  36. log.G(context.TODO()).WithError(err).Errorf("error setting the kernel parameter %s = %s, (leaving as %s)", k, v.Value, oldv)
  37. continue
  38. }
  39. log.G(context.TODO()).Debugf("updated kernel parameter %s = %s (was %s)", k, v.Value, oldv)
  40. }
  41. }
  42. }