/
perform-checks.go
426 lines (364 loc) · 12.5 KB
/
perform-checks.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package handlers
import (
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"strings"
"time"
certificateutils "github.com/dominic-wassef/gopher-runner/internal/certificateUtils"
"github.com/dominic-wassef/gopher-runner/internal/channeldata"
"github.com/dominic-wassef/gopher-runner/internal/helpers"
"github.com/dominic-wassef/gopher-runner/internal/models"
"github.com/dominic-wassef/gopher-runner/internal/sms"
"github.com/go-chi/chi/v5"
)
const (
// HTTP is the unencrypted web service check
HTTP = 1
// HTTPS is the encrypted web service check
HTTPS = 2
// SSLCertificate is ssl certificate check
SSLCertificate = 3
)
// jsonResp describes the JSON response sent back to client
type jsonResp struct {
OK bool `json:"ok"`
Message string `json:"message"`
ServiceID int `json:"service_id"`
HostServiceID int `json:"host_service_id"`
HostID int `json:"host_id"`
OldStatus string `json:"old_status"`
NewStatus string `json:"new_status"`
LastCheck time.Time `json:"last_check"`
}
// ScheduledCheck performs a scheduled check on a host service by id
func (repo *DBRepo) ScheduledCheck(hostServiceID int) {
hs, err := repo.DB.GetHostServiceByID(hostServiceID)
if err != nil {
log.Println(err)
return
}
h, err := repo.DB.GetHostByID(hs.HostID)
if err != nil {
log.Println(err)
return
}
// tests the service
newStatus, msg := repo.testServiceForHost(h, hs)
if newStatus != hs.Status {
repo.updateHostServiceStatusCount(h, hs, newStatus, msg)
}
}
func (repo *DBRepo) updateHostServiceStatusCount(h models.Host, hs models.HostService, newStatus, msg string) {
// update host service record in db with status and last check
hs.Status = newStatus
hs.LastMessage = msg
hs.LastCheck = time.Now()
err := repo.DB.UpdateHostService(hs)
if err != nil {
log.Println(err)
return
}
pending, healthy, warning, problem, err := repo.DB.GetAllServiceStatusCounts()
if err != nil {
log.Println(err)
return
}
data := make(map[string]string)
data["healthy_count"] = strconv.Itoa(healthy)
data["pending_count"] = strconv.Itoa(pending)
data["problem_count"] = strconv.Itoa(problem)
data["warning_count"] = strconv.Itoa(warning)
repo.broadcastMessage("public-channel", "host-service-count-changed", data)
}
func (repo *DBRepo) broadcastMessage(channel, messageType string, data map[string]string) {
err := app.WsClient.Trigger(channel, messageType, data)
if err != nil {
log.Println(err)
}
}
// TestCheck manually tests a host service and sends JSON response
func (repo *DBRepo) TestCheck(w http.ResponseWriter, r *http.Request) {
hostServiceID, _ := strconv.Atoi(chi.URLParam(r, "id"))
oldStatus := chi.URLParam(r, "oldStatus")
okay := true
// get host service
hs, err := repo.DB.GetHostServiceByID(hostServiceID)
if err != nil {
log.Println(err)
okay = false
}
// get host
h, err := repo.DB.GetHostByID(hs.HostID)
if err != nil {
log.Println(err)
okay = false
}
// test the service
newStatus, msg := repo.testServiceForHost(h, hs)
// save event
event := models.Event{
EventType: newStatus,
HostServiceID: hs.ID,
HostID: h.ID,
ServiceName: hs.Service.ServiceName,
HostName: hs.HostName,
Message: msg,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
err = repo.DB.InsertEvent(event)
if err != nil {
log.Println(err)
}
// broadcast service status changed event
if newStatus != hs.Status {
repo.pushStatusChangedEvent(h, hs, newStatus)
}
// update the host service in the database with status (if changed) and last check
hs.Status = newStatus
hs.LastMessage = msg
hs.LastCheck = time.Now()
hs.UpdatedAt = time.Now()
err = repo.DB.UpdateHostService(hs)
if err != nil {
log.Println(err)
okay = false
}
var resp jsonResp
// create json
if okay {
resp = jsonResp{
OK: true,
Message: msg,
ServiceID: hs.ServiceID,
HostServiceID: hs.ID,
HostID: hs.HostID,
OldStatus: oldStatus,
NewStatus: newStatus,
LastCheck: time.Now(),
}
} else {
resp.OK = false
resp.Message = "Something went wrong"
}
// send json to client
out, _ := json.MarshalIndent(resp, "", " ")
w.Header().Set("Content-Type", "application/json")
w.Write(out)
}
// testServiceForHost tests a service for a host
func (repo *DBRepo) testServiceForHost(h models.Host, hs models.HostService) (string, string) {
var msg, newStatus string
switch hs.ServiceID {
case HTTP:
msg, newStatus = testHTTPForHost(h.URL)
break
case HTTPS:
msg, newStatus = testHTTPSForHost(h.URL)
break
case SSLCertificate:
msg, newStatus = testSSLForHost(h.URL)
break
}
// broadcast to clients if appropriate
if hs.Status != newStatus {
repo.pushStatusChangedEvent(h, hs, newStatus)
// save event
event := models.Event{
EventType: newStatus,
HostServiceID: hs.ID,
HostID: h.ID,
ServiceName: hs.Service.ServiceName,
HostName: hs.HostName,
Message: msg,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
err := repo.DB.InsertEvent(event)
if err != nil {
log.Println(err)
}
// send email/sms if appropriate
if repo.App.PreferenceMap["notify_via_email"] == "1" {
if hs.Status != "pending" {
mm := channeldata.MailData{
ToName: repo.App.PreferenceMap["notify_name"],
ToAddress: repo.App.PreferenceMap["notify_email"],
}
// populate content for mail
if newStatus == "healthy" {
mm.Subject = fmt.Sprintf("Healthy: service %s on %s", hs.Service.ServiceName, hs.HostName)
mm.Content = template.HTML(fmt.Sprintf(`<p>Service %s on %s reported healthy status</p>
<p><strong>Message received: %s</p>`, hs.Service.ServiceName, hs.HostName, msg))
mm.Link = template.HTML(fmt.Sprintf(`<p>%s</p>`, h.URL))
} else if newStatus == "problem" {
mm.Subject = fmt.Sprintf("Problem: service %s on %s", hs.Service.ServiceName, hs.HostName)
mm.Content = template.HTML(fmt.Sprintf(`<p>Service %s on %s reported problem</p>
<p><strong>Message received: %s</p>`, hs.Service.ServiceName, hs.HostName, msg))
mm.Link = template.HTML(fmt.Sprintf(`<p>%s</p>`, h.URL))
} else if newStatus == "warning" {
mm.Subject = fmt.Sprintf("Warning: service %s on %s", hs.Service.ServiceName, hs.HostName)
mm.Content = template.HTML(fmt.Sprintf(`<p>Service %s on %s reported a warning</p>
<p><strong>Message received: %s</p>`, hs.Service.ServiceName, hs.HostName, msg))
mm.Link = template.HTML(fmt.Sprintf(`<p>%s</p>`, h.URL))
}
helpers.SendEmail(mm)
}
}
// send sms
if repo.App.PreferenceMap["notify_via_sms"] == "1" {
to := repo.App.PreferenceMap["sms_notify_number"]
msgMessage := ""
if newStatus == "healthy" {
msgMessage = fmt.Sprintf("Service %s on %s is healthy", hs.Service.ServiceName, hs.HostName)
} else if newStatus == "problem" {
msgMessage = fmt.Sprintf("Service %s on %s reports a problem: %s", hs.Service.ServiceName, hs.HostName, msg)
} else if newStatus == "warning" {
msgMessage = fmt.Sprintf("Service %s on %s reports a warning: %s", hs.Service.ServiceName, hs.HostName, msg)
}
err := sms.SendTextTwilio(to, msgMessage, repo.App)
if err != nil {
log.Println("Error sending sms in perform-checks.go", err)
}
}
}
repo.pushScheduleChangedEvent(hs, newStatus)
return newStatus, msg
}
func (repo *DBRepo) pushStatusChangedEvent(h models.Host, hs models.HostService, newStatus string) {
data := make(map[string]string)
data["host_id"] = strconv.Itoa(hs.HostID)
data["host_service_id"] = strconv.Itoa(hs.ID)
data["host_name"] = h.HostName
data["service_name"] = hs.Service.ServiceName
data["icon"] = hs.Service.Icon
data["status"] = newStatus
data["message"] = fmt.Sprintf("%s on %s reports %s", hs.Service.ServiceName, h.HostName, newStatus)
data["last_check"] = time.Now().Format("2006-01-02 3:04:06 PM")
repo.broadcastMessage("public-channel", "host-service-status-changed", data)
}
func (repo *DBRepo) pushScheduleChangedEvent(hs models.HostService, newStatus string) {
// broadcast schedule-changed-event
yearOne := time.Date(0001, 1, 1, 0, 0, 0, 1, time.UTC)
data := make(map[string]string)
data["host_service_id"] = strconv.Itoa(hs.ID)
data["service_id"] = strconv.Itoa(hs.ServiceID)
data["host_id"] = strconv.Itoa(hs.HostID)
if app.Scheduler.Entry(repo.App.MonitorMap[hs.ID]).Next.After(yearOne) {
data["next_run"] = repo.App.Scheduler.Entry(repo.App.MonitorMap[hs.ID]).Next.Format("2006-01-02 3:04:05 PM")
} else {
data["next_run"] = "Pending..."
}
data["last_run"] = time.Now().Format("2006-01-02 3:04:05 PM")
data["host"] = hs.HostName
data["service"] = hs.Service.ServiceName
data["schedule"] = fmt.Sprintf("@every %d%s", hs.ScheduleNumber, hs.ScheduleUnit)
data["status"] = newStatus
data["host_name"] = hs.HostName
data["icon"] = hs.Service.Icon
repo.broadcastMessage("public-channel", "schedule-changed-event", data)
}
// testHTTPForHost tests HTTP service
func testHTTPForHost(url string) (string, string) {
if strings.HasSuffix(url, "/") {
url = strings.TrimSuffix(url, "/")
}
url = strings.Replace(url, "https://", "http://", -1)
resp, err := http.Get(url)
if err != nil {
return fmt.Sprintf("%s - %s", url, "error connecting"), "problem"
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Sprintf("%s - %s", url, resp.Status), "problem"
}
return fmt.Sprintf("%s - %s", url, resp.Status), "healthy"
}
// testHTTPForHost tests HTTP service
func testHTTPSForHost(url string) (string, string) {
if strings.HasSuffix(url, "/") {
url = strings.TrimSuffix(url, "/")
}
url = strings.Replace(url, "http://", "https://", -1)
resp, err := http.Get(url)
if err != nil {
return fmt.Sprintf("%s - %s", url, "error connecting"), "problem"
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Sprintf("%s - %s", url, resp.Status), "problem"
}
return fmt.Sprintf("%s - %s", url, resp.Status), "healthy"
}
func scanHost(hostname string, certDetailsChannel chan certificateutils.CertificateDetails, errorsChannel chan error) {
res, err := certificateutils.GetCertificateDetails(hostname, 10)
if err != nil {
errorsChannel <- err
} else {
certDetailsChannel <- res
}
}
func testSSLForHost(url string) (string, string) {
if strings.HasPrefix(url, "https://") {
url = strings.Replace(url, "https://", "", -1)
}
if strings.HasPrefix(url, "https://") {
url = strings.Replace(url, "http://", "", -1)
}
var certDetailsChannel chan certificateutils.CertificateDetails
var errorsChannel chan error
certDetailsChannel = make(chan certificateutils.CertificateDetails, 1)
errorsChannel = make(chan error, 1)
var msg, newStatus string
scanHost(url, certDetailsChannel, errorsChannel)
for i, certDetailsInQueue := 0, len(certDetailsChannel); i < certDetailsInQueue; i++ {
certDetails := <-certDetailsChannel
certificateutils.CheckExpirationStatus(&certDetails, 30)
if certDetails.ExpiringSoon {
if certDetails.DaysUntilExpiration < 7 {
msg = certDetails.Hostname + " expiring in " + strconv.Itoa(certDetails.DaysUntilExpiration) + " days"
newStatus = "problem"
} else {
msg = certDetails.Hostname + " expiring in " + strconv.Itoa(certDetails.DaysUntilExpiration) + " days"
newStatus = "warning"
}
} else {
msg = certDetails.Hostname + " expiring in " + strconv.Itoa(certDetails.DaysUntilExpiration) + " days"
newStatus = "healthy"
}
}
return msg, newStatus
}
func (repo *DBRepo) addToMonitorMap(hs models.HostService) {
if repo.App.PreferenceMap["monitoring_live"] == "1" {
var j job
j.HostServiceID = hs.ID
scheduleID, err := repo.App.Scheduler.AddJob(fmt.Sprintf("@every %d%s", hs.ScheduleNumber, hs.ScheduleUnit), j)
if err != nil {
log.Println(err)
return
}
repo.App.MonitorMap[hs.ID] = scheduleID
data := make(map[string]string)
data["message"] = "scheduling"
data["host_service_id"] = strconv.Itoa(hs.ID)
data["next_run"] = "Pending..."
data["service"] = hs.Service.ServiceName
data["host"] = hs.HostName
data["last_run"] = hs.LastCheck.Format("2006-01-02 3:04:05 PM")
data["schedule"] = fmt.Sprintf("@every %d%s", hs.ScheduleNumber, hs.ScheduleUnit)
repo.broadcastMessage("public-channel", "schedule-changed-event", data)
}
}
func (repo *DBRepo) removeFromMonitorMap(hs models.HostService) {
if repo.App.PreferenceMap["monitoring_live"] == "1" {
repo.App.Scheduler.Remove(repo.App.MonitorMap[hs.ID])
data := make(map[string]string)
data["host_service_id"] = strconv.Itoa(hs.ID)
repo.broadcastMessage("public-channel", "schedule-item-removed-event", data)
}
}