From 7d386bb5aff0d880ecc0d0356436f3c83e5fb528 Mon Sep 17 00:00:00 2001 From: Dayang Shen Date: Sat, 25 Mar 2023 00:10:34 +0800 Subject: [PATCH] Read /dev/kmsg in non-block mode --- pkg/checkers/oom/oom.go | 28 +++++++++++++++++++++++++++- pkg/checkers/oom/oom_test.go | 5 ++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/pkg/checkers/oom/oom.go b/pkg/checkers/oom/oom.go index 4d51b84..0263ca8 100644 --- a/pkg/checkers/oom/oom.go +++ b/pkg/checkers/oom/oom.go @@ -2,10 +2,13 @@ package oom import ( "bufio" + "errors" "fmt" + "io" "os" "regexp" "strings" + "syscall" "github.com/Azure/kdebug/pkg/base" ) @@ -83,6 +86,24 @@ 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 { @@ -90,8 +111,13 @@ func (c *OOMChecker) getAndParseOOMLog() ([]string, error) { } 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 diff --git a/pkg/checkers/oom/oom_test.go b/pkg/checkers/oom/oom_test.go index bdf7067..a138e21 100644 --- a/pkg/checkers/oom/oom_test.go +++ b/pkg/checkers/oom/oom_test.go @@ -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)) }