-
Notifications
You must be signed in to change notification settings - Fork 3
/
uptime.go
115 lines (90 loc) · 2.32 KB
/
uptime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package systatus
import (
"encoding/json"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"github.com/rs/zerolog/log"
)
type UptimeHandlerOpts struct {
Middlewares []func(next http.HandlerFunc) http.HandlerFunc
}
type UptimeResponse struct {
Systime string `json:"systime"`
Uptime float64 `json:"uptime"`
}
func handleUptime(opts UptimeHandlerOpts) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
res := UptimeResponse{
Systime: time.Now().Format(time.RFC3339),
}
var err error
log.Debug().Msgf("Handling uptime on %s machine", runtime.GOOS)
switch runtime.GOOS {
case "windows":
res.Uptime, err = getWinUptime()
break
case "darwin":
res.Uptime, err = getMacOSUptime()
break
default:
res.Uptime, err = getUptime()
}
if err != nil {
log.Err(err).Msg("Could not execute uptime on this host")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(res)
if err != nil {
log.Err(err).Msg("Failed to encode response")
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
func getWinUptime() (float64, error) {
log.Warn().Msg("If FastBoot is enabled, uptime on Windows may be tracked incorrectly")
cmdoutput, err := exec.Command("powershell", "-Command", "(get-date) – (gcim Win32_OperatingSystem).LastBootUpTime").Output()
if err != nil {
return 0, err
}
splitCmd := strings.Split(strings.ReplaceAll(string(cmdoutput), "\r\n", "\n"), "\n")
ms := strings.Split(splitCmd[10], ":")[1]
uptime, err := strconv.ParseFloat(ms, 64)
if err != nil {
return 0, err
}
return uptime, nil
}
func getMacOSUptime() (float64, error) {
cmd := "sysctl -n kern.boottime | cut -c9-18"
output, err := exec.Command("bash", "-c", cmd).CombinedOutput()
if err != nil {
return 0, err
}
data := strings.TrimSpace(string(output))
uptime, err := strconv.ParseFloat(data, 64)
if err != nil {
return 0, err
}
return uptime, nil
}
func getUptime() (float64, error) {
buf, err := os.ReadFile("/proc/uptime")
if err != nil {
return 0, err
}
data := strings.Split(string(buf), " ")[0]
seconds, err := strconv.ParseFloat(data, 64)
if err != nil {
return 0, err
}
uptime := seconds * 1000
return uptime, nil
}