oom_unix.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // +build !windows
  2. /*
  3. Copyright The containerd Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package sys
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "github.com/opencontainers/runc/libcontainer/system"
  22. )
  23. // OOMScoreMaxKillable is the maximum score keeping the process killable by the oom killer
  24. const OOMScoreMaxKillable = -999
  25. // SetOOMScore sets the oom score for the provided pid
  26. func SetOOMScore(pid, score int) error {
  27. path := fmt.Sprintf("/proc/%d/oom_score_adj", pid)
  28. f, err := os.OpenFile(path, os.O_WRONLY, 0)
  29. if err != nil {
  30. return err
  31. }
  32. defer f.Close()
  33. if _, err = f.WriteString(strconv.Itoa(score)); err != nil {
  34. if os.IsPermission(err) && (system.RunningInUserNS() || RunningUnprivileged()) {
  35. return nil
  36. }
  37. return err
  38. }
  39. return nil
  40. }
  41. // GetOOMScoreAdj gets the oom score for a process
  42. func GetOOMScoreAdj(pid int) (int, error) {
  43. path := fmt.Sprintf("/proc/%d/oom_score_adj", pid)
  44. data, err := ioutil.ReadFile(path)
  45. if err != nil {
  46. return 0, err
  47. }
  48. return strconv.Atoi(strings.TrimSpace(string(data)))
  49. }