sysctl.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. VmOvercommitMemoryAlways = 1 // kernel performs no memory over-commit handling
  27. VmPanicOnOOMInvokeOOMKiller = 0 // kernel calls the oom_killer function when OOM occurs
  28. KernelPanicOnOopsAlways = 1 // kernel panics on kernel oops
  29. KernelPanicRebootTimeout = 10 // seconds after a panic for the kernel to reboot
  30. )
  31. // An injectable interface for running sysctl commands.
  32. type Interface interface {
  33. // GetSysctl returns the value for the specified sysctl setting
  34. GetSysctl(sysctl string) (int, error)
  35. // SetSysctl modifies the specified sysctl flag to the new value
  36. SetSysctl(sysctl string, newVal int) error
  37. }
  38. // New returns a new Interface for accessing sysctl
  39. func New() Interface {
  40. return &procSysctl{}
  41. }
  42. // procSysctl implements Interface by reading and writing files under /proc/sys
  43. type procSysctl struct {
  44. }
  45. // GetSysctl returns the value for the specified sysctl setting
  46. func (_ *procSysctl) GetSysctl(sysctl string) (int, error) {
  47. data, err := ioutil.ReadFile(path.Join(sysctlBase, sysctl))
  48. if err != nil {
  49. return -1, err
  50. }
  51. val, err := strconv.Atoi(strings.Trim(string(data), " \n"))
  52. if err != nil {
  53. return -1, err
  54. }
  55. return val, nil
  56. }
  57. // SetSysctl modifies the specified sysctl flag to the new value
  58. func (_ *procSysctl) SetSysctl(sysctl string, newVal int) error {
  59. return ioutil.WriteFile(path.Join(sysctlBase, sysctl), []byte(strconv.Itoa(newVal)), 0640)
  60. }