Debian Codegraph @

internal/host/host.go

raw symbols SCIP
1 // Copyright 2018 psgo authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package host extracts data from the host, such as the system's boot time or
16 // the tick rate of the system clock.
17 package host
18
19 import (
20 "bufio"
21 "fmt"
22 "os"
23 "strconv"
24 "strings"
25 )
26
27 // BootTime parses /proc/uptime returns the boot time in seconds since the
28 // Epoch, 1970-01-01 00:00:00 +0000 (UTC).
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 }