sysctl.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. Copyright 2015 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 sysctl
  14. import (
  15. "io/ioutil"
  16. "path"
  17. "strconv"
  18. "strings"
  19. )
  20. const (
  21. sysctlBase = "/proc/sys"
  22. VmOvercommitMemory = "vm/overcommit_memory"
  23. VmPanicOnOOM = "vm/panic_on_oom"
  24. KernelPanic = "kernel/panic"
  25. KernelPanicOnOops = "kernel/panic_on_oops"
  26. RootMaxKeys = "kernel/keys/root_maxkeys"
  27. RootMaxBytes = "kernel/keys/root_maxbytes"
  28. VmOvercommitMemoryAlways = 1 // kernel performs no memory over-commit handling
  29. VmPanicOnOOMInvokeOOMKiller = 0 // kernel calls the oom_killer function when OOM occurs
  30. KernelPanicOnOopsAlways = 1 // kernel panics on kernel oops
  31. KernelPanicRebootTimeout = 10 // seconds after a panic for the kernel to reboot
  32. RootMaxKeysSetting = 1000000 // Needed since docker creates a new key per container
  33. RootMaxBytesSetting = RootMaxKeysSetting * 25 // allocate 25 bytes per key * number of MaxKeys
  34. )
  35. // An injectable interface for running sysctl commands.
  36. type Interface interface {
  37. // GetSysctl returns the value for the specified sysctl setting
  38. GetSysctl(sysctl string) (int, error)
  39. // SetSysctl modifies the specified sysctl flag to the new value
  40. SetSysctl(sysctl string, newVal int) error
  41. }
  42. // New returns a new Interface for accessing sysctl
  43. func New() Interface {
  44. return &procSysctl{}
  45. }
  46. // procSysctl implements Interface by reading and writing files under /proc/sys
  47. type procSysctl struct {
  48. }
  49. // GetSysctl returns the value for the specified sysctl setting
  50. func (_ *procSysctl) GetSysctl(sysctl string) (int, error) {
  51. data, err := ioutil.ReadFile(path.Join(sysctlBase, sysctl))
  52. if err != nil {
  53. return -1, err
  54. }
  55. val, err := strconv.Atoi(strings.Trim(string(data), " \n"))
  56. if err != nil {
  57. return -1, err
  58. }
  59. return val, nil
  60. }
  61. // SetSysctl modifies the specified sysctl flag to the new value
  62. func (_ *procSysctl) SetSysctl(sysctl string, newVal int) error {
  63. return ioutil.WriteFile(path.Join(sysctlBase, sysctl), []byte(strconv.Itoa(newVal)), 0640)
  64. }