Skip to content

Commit

Permalink
Read /dev/kmsg in non-block mode
Browse files Browse the repository at this point in the history
  • Loading branch information
ArchangelSDY committed Mar 24, 2023
1 parent 1e5254d commit 7d386bb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
28 changes: 27 additions & 1 deletion pkg/checkers/oom/oom.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package oom

import (
"bufio"
"errors"
"fmt"
"io"
"os"
"regexp"
"strings"
"syscall"

"github.com/Azure/kdebug/pkg/base"
)
Expand Down Expand Up @@ -83,15 +86,38 @@ func (c *OOMChecker) checkOOM(ctx *base.CheckContext) (*base.CheckResult, error)
}
return result, nil
}

type nonBlockReader struct {
fd int
}

func (r *nonBlockReader) Read(buf []byte) (n int, err error) {
n, err = syscall.Read(r.fd, buf)
if err != nil {
if errors.Is(err, syscall.EAGAIN) {
return 0, io.EOF
}
}
if n == 0 && err == nil {
return 0, io.EOF
}
return n, err
}

func (c *OOMChecker) getAndParseOOMLog() ([]string, error) {
file, err := os.Open(c.kernLogPath)
if err != nil {
return nil, err
}
defer file.Close()

fd := int(file.Fd())
if err = syscall.SetNonblock(fd, true); err != nil {
return nil, fmt.Errorf("Fail to read in non-block mode: %s", err)
}

var oomInfos []string
scanner := bufio.NewScanner(file)
scanner := bufio.NewScanner(&nonBlockReader{fd})
for scanner.Scan() {
tmp := scanner.Text()
//todo: more sophisticated OOM context
Expand Down
5 changes: 4 additions & 1 deletion pkg/checkers/oom/oom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,12 @@ func TestCheckOOMLogWhenOOM(t *testing.T) {
if err != nil {
t.Errorf("Create tmp file error:%v", err)
}
result, _ := check.Check(&base.CheckContext{
result, err := check.Check(&base.CheckContext{
Environment: environment,
})
if err != nil {
t.Errorf("Expect no error but got: %s", err)
}
if len(result) != 1 {
t.Errorf("Get unexpected OOM result length %v", len(result))
}
Expand Down

0 comments on commit 7d386bb

Please sign in to comment.