Files
rpi5-health/internal/uptime/linux_uptime.go
T

51 lines
1.0 KiB
Go

//go:build linux
package uptime
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func getLinuxUptime() (UptimeInformation, error) {
uptimeFile, err := os.Open("/proc/uptime")
if err != nil {
return UptimeInformation{}, fmt.Errorf("Could not find /proc/uptime. Are you sure you are on linux?")
}
defer uptimeFile.Close()
fileReader := bufio.NewScanner(uptimeFile)
var busyTime float64
fileReader.Scan()
if fileReader.Err() != nil {
return UptimeInformation{}, fmt.Errorf("Could not read /proc/uptime.")
}
data := fileReader.Text()
/*
* fields[0] Time spent busy/suspended
* fields[1] Time spent idling, it's combined from all CPU cores
*/
fields := strings.Split(data, " ")
busyTime, _ = strconv.ParseFloat(fields[0], 64)
return UptimeInformation{
Uptime: busyTime,
}, nil
}
func GetUptimeInformation() (UptimeInformation, error) {
info, err := getLinuxUptime()
if err != nil {
return UptimeInformation{}, fmt.Errorf("Could not read uptime info. Error: %v", err)
}
return info, nil
}