recover from hwmon linux read file panic #3108

Signed-off-by: joey <zchengjoey@gmail.com>
This commit is contained in:
joey 2024-09-06 10:02:20 +08:00
parent b9d0932179
commit c170c0d088
No known key found for this signature in database
GPG key ID: B5AE69C27B241A78

View file

@ -18,6 +18,7 @@ package collector
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
@ -91,19 +92,29 @@ func addValueFile(data map[string]map[string]string, sensor string, prop string,
}
// sysReadFile is a simplified os.ReadFile that invokes syscall.Read directly.
func sysReadFile(file string) ([]byte, error) {
func sysReadFile(file string) (b []byte, err error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
defer func() {
if r := recover(); r != nil {
level.Error(log.NewNopLogger()).Log("msg", "recovered from panic", "err", r)
if rErr, ok := r.(error); ok {
err = rErr
} else {
err = fmt.Errorf("%v", r)
}
}
}()
// On some machines, hwmon drivers are broken and return EAGAIN. This causes
// Go's os.ReadFile implementation to poll forever.
//
// Since we either want to read data or bail immediately, do the simplest
// possible read using system call directly.
b := make([]byte, 128)
b = make([]byte, 128)
n, err := unix.Read(int(f.Fd()), b)
if err != nil {
return nil, err