| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package host |
| 18 |
|
| 19 |
import ( |
| 20 |
"bufio" |
| 21 |
"fmt" |
| 22 |
"os" |
| 23 |
"strconv" |
| 24 |
"strings" |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
func BootTime() (int64, error) { |
| 30 |
if bootTime != nil { |
| 31 |
return *bootTime, nil |
| 32 |
} |
| 33 |
|
| 34 |
f, err := os.Open("/proc/stat") |
| 35 |
if err != nil { |
| 36 |
return 0, err |
| 37 |
} |
| 38 |
|
| 39 |
btimeStr := "" |
| 40 |
scanner := bufio.NewScanner(f) |
| 41 |
for scanner.Scan() { |
| 42 |
fields := strings.Fields(scanner.Text()) |
| 43 |
if len(fields) < 2 { |
| 44 |
continue |
| 45 |
} |
| 46 |
if fields[0] == "btime" { |
| 47 |
btimeStr = fields[1] |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
if len(btimeStr) == 0 { |
| 52 |
return 0, fmt.Errorf("couldn't extract boot time from /proc/stat") |
| 53 |
} |
| 54 |
|
| 55 |
btimeSec, err := strconv.ParseInt(btimeStr, 10, 64) |
| 56 |
if err != nil { |
| 57 |
return 0, fmt.Errorf("error parsing boot time from /proc/stat: %w", err) |
| 58 |
} |
| 59 |
bootTime = &btimeSec |
| 60 |
return btimeSec, nil |
| 61 |
} |