knobs_linux.go 1.4 KB

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