-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathuptime.go
176 lines (150 loc) · 3.91 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
"imuslab.com/utm/pkg/utils"
)
func UptimeMonitorInit() error {
log.Println("-- Uptime Monitor Started --")
if !utils.FileExists(configFilepath) {
log.Println("config.json not found. Template created.")
template := Config{
Targets: []*Target{&exampleTarget},
Interval: 60,
}
js, _ := json.MarshalIndent(template, "", " ")
os.WriteFile(configFilepath, js, 0775)
os.Exit(0)
}
c, err := os.ReadFile(configFilepath)
if err != nil {
return (err)
}
parsedConfig := Config{}
err = json.Unmarshal(c, &parsedConfig)
if err != nil {
return (err)
}
usingConfig = &parsedConfig
//Start the endpoint listener
ticker := time.NewTicker(time.Duration(usingConfig.Interval) * time.Second)
done := make(chan bool)
go func() {
//Start the uptime check once first before entering loop
log.Println("Started initial uptime check. Might take a while before any results is shown on the web UI")
ExecuteUptimeCheck()
log.Println("Initial uptime check completed")
for {
select {
case <-done:
return
case t := <-ticker.C:
log.Println("Uptime updated - ", t.Unix())
ExecuteUptimeCheck()
}
}
}()
return nil
}
func ExecuteUptimeCheck() {
for _, target := range usingConfig.Targets {
//For each target to check online, do the following
var thisRecord Record
if target.Protocol == "http" || target.Protocol == "https" {
log.Println("Updating uptime status for " + target.Name)
online, laterncy, statusCode := getWebsiteStatusWithLatency(target.URL)
thisRecord = Record{
Timestamp: time.Now().Unix(),
ID: target.ID,
Name: target.Name,
URL: target.URL,
Protocol: target.Protocol,
Online: online,
StatusCode: statusCode,
Latency: laterncy,
}
//fmt.Println(thisRecord)
} else {
log.Println("Unknown protocol: " + target.Protocol + ". Skipping")
continue
}
thisRecords, ok := onlineStatusLog[target.ID]
if !ok {
//First record. Create the array
onlineStatusLog[target.ID] = []*Record{&thisRecord}
} else {
//Append to the previous record
thisRecords = append(thisRecords, &thisRecord)
//Check if the record is longer than the logged record. If yes, clear out the old records
if len(thisRecords) > usingConfig.RecordsInJson {
thisRecords = thisRecords[1:]
}
onlineStatusLog[target.ID] = thisRecords
}
}
//Write the results to a json file
if usingConfig.LogToFile {
//Log to file
js, _ := json.MarshalIndent(onlineStatusLog, "", " ")
os.WriteFile(logFilepath, js, 0775)
}
}
/*
Web Interface Handler
*/
func HandleUptimeLogRead(w http.ResponseWriter, r *http.Request) {
id, _ := utils.GetPara(r, "id")
if id == "" {
js, _ := json.Marshal(onlineStatusLog)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
} else {
//Check if that id exists
log, ok := onlineStatusLog[id]
if !ok {
http.NotFound(w, r)
return
}
js, _ := json.MarshalIndent(log, "", " ")
w.Header().Set("Content-Type", "application/json")
w.Write(js)
}
}
/*
Utilities
*/
// Get website stauts with latency given URL, return is conn succ and its latency and status code
func getWebsiteStatusWithLatency(url string) (bool, int64, int) {
start := time.Now().UnixNano() / int64(time.Millisecond)
statusCode, err := getWebsiteStatus(url)
end := time.Now().UnixNano() / int64(time.Millisecond)
if err != nil {
log.Println(err.Error())
return false, 0, 0
} else {
diff := end - start
succ := false
if statusCode >= 200 && statusCode < 300 {
//OK
succ = true
} else if statusCode >= 300 && statusCode < 400 {
//Redirection code
succ = true
} else {
succ = false
}
return succ, diff, statusCode
}
}
func getWebsiteStatus(url string) (int, error) {
resp, err := http.Get(url)
if err != nil {
return 0, err
}
status_code := resp.StatusCode
resp.Body.Close()
return status_code, nil
}