github.com/containerd/containerd@v22.0.0-20200918172823-438c87b8e050+incompatible/sys/oom_unix_test.go (about) 1 // +build !windows 2 3 /* 4 Copyright The containerd Authors. 5 6 Licensed under the Apache License, Version 2.0 (the "License"); 7 you may not use this file except in compliance with the License. 8 You may obtain a copy of the License at 9 10 http://www.apache.org/licenses/LICENSE-2.0 11 12 Unless required by applicable law or agreed to in writing, software 13 distributed under the License is distributed on an "AS IS" BASIS, 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 See the License for the specific language governing permissions and 16 limitations under the License. 17 */ 18 19 package sys 20 21 import ( 22 "errors" 23 "os" 24 "os/exec" 25 "testing" 26 "time" 27 28 "gotest.tools/v3/assert" 29 is "gotest.tools/v3/assert/cmp" 30 ) 31 32 func TestSetPositiveOomScoreAdjustment(t *testing.T) { 33 adjustment, err := adjustOom(123) 34 if err != nil { 35 t.Error(err) 36 return 37 } 38 assert.Check(t, is.Equal(adjustment, 123)) 39 } 40 41 func TestSetNegativeOomScoreAdjustmentWhenPrivileged(t *testing.T) { 42 if RunningUnprivileged() { 43 t.Skip("Needs to be run as root") 44 return 45 } 46 47 adjustment, err := adjustOom(-123) 48 if err != nil { 49 t.Error(err) 50 return 51 } 52 assert.Check(t, is.Equal(adjustment, -123)) 53 } 54 55 func TestSetNegativeOomScoreAdjustmentWhenUnprivilegedHasNoEffect(t *testing.T) { 56 if RunningPrivileged() { 57 t.Skip("Needs to be run as non-root") 58 return 59 } 60 61 adjustment, err := adjustOom(-123) 62 if err != nil { 63 t.Error(err) 64 return 65 } 66 assert.Check(t, is.Equal(adjustment, 0)) 67 } 68 69 func adjustOom(adjustment int) (int, error) { 70 cmd := exec.Command("sleep", "100") 71 if err := cmd.Start(); err != nil { 72 return 0, err 73 } 74 75 defer cmd.Process.Kill() 76 77 pid, err := waitForPid(cmd.Process) 78 if err != nil { 79 return 0, err 80 } 81 82 if err := SetOOMScore(pid, adjustment); err != nil { 83 return 0, err 84 } 85 86 return GetOOMScoreAdj(pid) 87 } 88 89 func waitForPid(process *os.Process) (int, error) { 90 c := make(chan int, 1) 91 go func() { 92 for { 93 pid := process.Pid 94 if pid != 0 { 95 c <- pid 96 } 97 } 98 }() 99 100 select { 101 case pid := <-c: 102 return pid, nil 103 case <-time.After(10 * time.Second): 104 return 0, errors.New("process did not start in 10 seconds") 105 } 106 }