-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
1403 lines (1260 loc) · 34.7 KB
/
main.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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"context"
_ "embed"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"math"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"text/template"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
"gopkg.in/yaml.v2"
)
// Config stores the variables for runtime configuration.
type Config struct {
Debug bool
LogSize int
HostName string
Web struct {
Host string
Port int
}
Alert struct {
Telegram struct {
Token string
Chat int64
}
Gotify struct {
Token string
Server string
}
Exec string
MQTT struct {
Server string
Port int
User string
Password string
Topic string
}
}
Monitor struct {
MQTT struct {
Server string
Port int
User string
Password string
History int
StandardTimeout float64
Targets []struct {
Topic string
Name string
Timeout int
}
}
Ping struct {
Interval int
Threshold int
Targets []struct {
Name string
Address string
Interval int
Threshold int
}
}
HTTP struct {
Interval int
Timeout int
Threshold int
Targets []struct {
Name string
Address string
Value string
Interval int
Timeout int
Threshold int
}
}
Exec struct {
Interval int
Timeout int
Threshold int
Targets []struct {
Name string
Command string
Interval int
Timeout int
Threshold int
}
}
}
}
// TimedEntry stores a string with timestamp.
type TimedEntry struct {
Timestamp time.Time
Value string
}
// MQTTTopic stores status information on a MQTT topic.
type MQTTMonitorData struct {
Name string
FirstSeen time.Time
LastSeen time.Time
LastError time.Time
LastPayload string
History []TimedEntry
AvgTransmit float64 `json:"-"`
Timeout float64 `json:"-"`
CustomTimeout float64
Status int32
Samples int64
Alerts int64
Deleted bool
}
type PingMonitorData struct {
Name string
LastOK time.Time
LastError time.Time
LastErrorStart time.Time
Status int32
TotalOK int64
TotalError int64
Errors int
Timestamp time.Time
Interval int
Threshold int
}
type HTTPMonitorData struct {
Name string
LastOK time.Time
LastError time.Time
LastErrorStart time.Time
Value string
LastValue string
LastErrorValue string
Status int32
TotalOK int64
TotalError int64
Errors int
Timestamp time.Time
Interval int
Timeout int
Threshold int
}
type ExecMonitorData struct {
Name string
LastOK time.Time
LastError time.Time
LastErrorStart time.Time
Status int32
TotalOK int64
TotalError int64
Errors int
Timestamp time.Time
Interval int
Timeout int
Threshold int
}
// MonitorData stores the actual status data of the monitoring process.
type MonitorData struct {
MQTT map[string]*MQTTMonitorData
Ping map[string]*PingMonitorData
HTTP map[string]*HTTPMonitorData
Exec map[string]*ExecMonitorData
sync.RWMutex `json:"-"`
}
// Data struct for serving main web page.
type PageData struct {
MonitorData *MonitorData
Timestamp time.Time
Uptime time.Time
Config *Config
LogHistory *[]TimedEntry
Fullversion *string
}
// Data struct of JSON payload for MQTT alerts.
type MQTTAlertPayload struct {
SensorType string `json:"type"`
SensorName string `json:"name"`
Status string `json:"status"`
Since time.Time `json:"since"`
Err string `json:"error"`
Msg string `json:"message"`
}
// Data struct of JSON payload for api/stats.
type StatsData struct {
OkCount int `json:"ok"`
ErrCount int `json:"error"`
}
var (
version string
build string
commit string
fullversion string
config *Config
configFile string
configLock = new(sync.RWMutex)
logHistory []TimedEntry
logLock = new(sync.RWMutex)
tgbot *tgbotapi.BotAPI
monitorData = MonitorData{
MQTT: make(map[string]*MQTTMonitorData),
Ping: make(map[string]*PingMonitorData),
HTTP: make(map[string]*HTTPMonitorData),
Exec: make(map[string]*ExecMonitorData)}
uptime = time.Now()
monitorMqttClient mqtt.Client
alertMqttClient mqtt.Client
//go:embed templates/index.html
index_template string
)
const (
// MAXLOGSIZE defines the maximum lenght of the log history maintained (can be overridden in config)
MAXLOGSIZE = 1000
// Default hostname
HOSTNAME = "janitor"
// Status flags for monitoring.
STATUS_OK = 0
STATUS_WARN = 1
STATUS_ERROR = 2
)
func main() {
fullversion = fmt.Sprintf("Janitor %s (build date %s, %s)", version, build, commit)
// load initial config
if len(os.Args) != 2 {
fmt.Println(fullversion)
fmt.Println("Usage: " + os.Args[0] + " <configfile>")
os.Exit(1)
}
configFile = os.Args[1]
loadConfig()
// start monitoring loop
monitoringLoop()
// launch web server
log(fmt.Sprintf("Launching web server at %s:%d", getConfig().Web.Host, getConfig().Web.Port))
http.HandleFunc("/", serveIndex)
http.HandleFunc("/reload_config", reloadConfig)
http.HandleFunc("/delete", deleteWebItem)
http.HandleFunc("/config", configWebItem)
http.HandleFunc("/api/stats", serveAPIStats)
http.HandleFunc("/api/data", serveAPIData)
http.HandleFunc("/api/metrics", serveAPIMetrics)
panic(http.ListenAndServe(fmt.Sprintf("%s:%d", getConfig().Web.Host, getConfig().Web.Port), nil))
}
// Set defaults for configuration values.
func setDefaults(c *Config) {
if c.HostName == "" {
hostname, err := os.Hostname()
if err != nil {
hostname = HOSTNAME
}
c.HostName = hostname
}
if c.LogSize == 0 {
c.LogSize = MAXLOGSIZE
}
if c.Web.Port == 0 {
c.Web.Port = 8080
}
if c.Monitor.MQTT.History == 0 {
c.Monitor.MQTT.History = 10
}
if c.Monitor.MQTT.Port == 0 {
c.Monitor.MQTT.Port = 1883
}
if c.Monitor.MQTT.StandardTimeout == 0 {
c.Monitor.MQTT.StandardTimeout = 1.5
}
if c.Monitor.Ping.Interval == 0 {
c.Monitor.Ping.Interval = 60
}
if c.Monitor.Ping.Threshold == 0 {
c.Monitor.Ping.Threshold = 2
}
if c.Monitor.HTTP.Interval == 0 {
c.Monitor.HTTP.Interval = 60
}
if c.Monitor.HTTP.Timeout == 0 {
c.Monitor.HTTP.Timeout = 5000
}
if c.Monitor.HTTP.Threshold == 0 {
c.Monitor.HTTP.Threshold = 2
}
if c.Monitor.Exec.Interval == 0 {
c.Monitor.Exec.Interval = 60
}
if c.Monitor.Exec.Timeout == 0 {
c.Monitor.Exec.Timeout = 5000
}
if c.Monitor.Exec.Threshold == 0 {
c.Monitor.Exec.Threshold = 2
}
if c.Alert.MQTT.Port == 0 {
c.Alert.MQTT.Port = 1883
}
}
// Loads or reloads the configuration and initializes MQTT and Telegram connections accordingly.
func loadConfig() {
// set up initial config for logging and others to work
if config == nil {
config = new(Config)
setDefaults(config)
}
log("Starting " + fullversion)
// (re)populate config struct from file
yamlFile, err := os.ReadFile(configFile)
if err != nil {
log("Unable to load config: " + err.Error())
return
}
newconfig := new(Config)
err = yaml.Unmarshal(yamlFile, &newconfig)
if err != nil {
log("Unable to load config: " + err.Error())
}
setDefaults(newconfig)
configLock.Lock()
config = newconfig
configLock.Unlock()
debug("Loaded config: " + fmt.Sprintf("%+v", getConfig()))
// update monitor targets based on new configuration
monitorData.Lock()
// remove deleted MQTT targets
for k := range monitorData.MQTT {
if monitorData.MQTT[k].Deleted {
delete(monitorData.MQTT, k)
}
}
// update monitored ping hosts
for _, target := range getConfig().Monitor.Ping.Targets {
e, ok := monitorData.Ping[target.Address]
if !ok {
monitorData.Ping[target.Address] = &PingMonitorData{}
e = monitorData.Ping[target.Address]
}
e.Name = target.Name
if target.Interval != 0 {
e.Interval = target.Interval
} else if e.Interval == 0 {
e.Interval = getConfig().Monitor.Ping.Interval
}
if target.Threshold != 0 {
e.Threshold = target.Threshold
} else if e.Threshold == 0 {
e.Threshold = getConfig().Monitor.Ping.Threshold
}
monitorData.Ping[target.Address] = e
}
// remove deleted ping hosts from monitoring
for k := range monitorData.Ping {
found := false
for _, c := range getConfig().Monitor.Ping.Targets {
if k == c.Address {
found = true
break
}
}
if !found {
delete(monitorData.Ping, k)
}
}
// update monitored http hosts
for _, target := range getConfig().Monitor.HTTP.Targets {
e, ok := monitorData.HTTP[target.Address]
if !ok {
monitorData.HTTP[target.Address] = &HTTPMonitorData{}
e = monitorData.HTTP[target.Address]
}
e.Name = target.Name
if target.Interval != 0 {
e.Interval = target.Interval
} else if e.Interval == 0 {
e.Interval = getConfig().Monitor.HTTP.Interval
}
if target.Timeout != 0 {
e.Timeout = target.Timeout
} else if e.Timeout == 0 {
e.Timeout = getConfig().Monitor.HTTP.Timeout
}
if target.Threshold != 0 {
e.Threshold = target.Threshold
} else if e.Threshold == 0 {
e.Threshold = getConfig().Monitor.HTTP.Threshold
}
e.Value = target.Value
monitorData.HTTP[target.Address] = e
}
// remove deleted http hosts from monitoring
for k := range monitorData.HTTP {
found := false
for _, c := range getConfig().Monitor.HTTP.Targets {
if k == c.Address {
found = true
break
}
}
if !found {
delete(monitorData.HTTP, k)
}
}
// update monitored exec targets
for _, target := range getConfig().Monitor.Exec.Targets {
e, ok := monitorData.Exec[target.Command]
if !ok {
monitorData.Exec[target.Command] = &ExecMonitorData{}
e = monitorData.Exec[target.Command]
}
e.Name = target.Name
if target.Interval != 0 {
e.Interval = target.Interval
} else if e.Interval == 0 {
e.Interval = getConfig().Monitor.Exec.Interval
}
if target.Timeout != 0 {
e.Timeout = target.Timeout
} else if e.Timeout == 0 {
e.Timeout = getConfig().Monitor.Exec.Timeout
}
if target.Threshold != 0 {
e.Threshold = target.Threshold
} else if e.Threshold == 0 {
e.Threshold = getConfig().Monitor.Exec.Threshold
}
monitorData.Exec[target.Command] = e
}
// remove deleted exec targets from monitoring
for k := range monitorData.Exec {
found := false
for _, c := range getConfig().Monitor.Exec.Targets {
if k == c.Command {
found = true
break
}
}
if !found {
delete(monitorData.Exec, k)
}
}
monitorData.Unlock()
// connect MQTT if configured
if getConfig().Monitor.MQTT.Server != "" {
if monitorMqttClient != nil && monitorMqttClient.IsConnected() {
monitorMqttClient.Disconnect(1)
debug("Disconnected from MQTT (monitoring)")
}
connectMqtt()
}
// connect Telegram if configured
if getConfig().Alert.Telegram.Token != "" && getConfig().Alert.Telegram.Chat != 0 {
connectTelegram()
}
// connect MQTT alert topic if configured
if getConfig().Alert.MQTT.Server != "" && getConfig().Alert.MQTT.Topic != "" {
if alertMqttClient != nil && alertMqttClient.IsConnected() {
alertMqttClient.Disconnect(1)
debug("Disconnected from MQTT (alerting)")
}
connectMqttAlert()
}
}
func connectTelegram() {
var err error
tgbot, err = tgbotapi.NewBotAPI(getConfig().Alert.Telegram.Token)
if err != nil {
log("Unable to connect to Telegram: " + err.Error())
}
log("Connected to telegram bot")
}
func connectMqtt() {
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("%s:%d", getConfig().Monitor.MQTT.Server, getConfig().Monitor.MQTT.Port))
opts.SetUsername(getConfig().Monitor.MQTT.User)
opts.SetPassword(getConfig().Monitor.MQTT.Password)
opts.OnConnect = func(c mqtt.Client) {
topics := make(map[string]byte)
for _, t := range getConfig().Monitor.MQTT.Targets {
topics[t.Topic] = byte(0)
}
// deduplicate MQTT topics (remove specific topics that are included in wildcard topics)
for t := range topics {
if strings.Contains(t, "#") {
for tt := range topics {
if matchMQTTTopic(t, tt) && t != tt {
delete(topics, tt)
debug(fmt.Sprintf("Deleting %s from MQTT subscription (included in %s)", tt, t))
}
}
}
}
t := make([]string, 0)
for i := range topics {
t = append(t, i)
}
if token := c.SubscribeMultiple(topics, onMessageReceived); token.Wait() && token.Error() != nil {
log("Unable to subscribe to MQTT: " + token.Error().Error())
} else {
log("Subscribed to MQTT topics: " + strings.Join(t, ", "))
}
}
monitorMqttClient = mqtt.NewClient(opts)
if token := monitorMqttClient.Connect(); token.Wait() && token.Error() != nil {
log("Unable to connect to MQTT for monitoring: " + token.Error().Error())
} else {
log("Connected to MQTT server for monitoring at " + opts.Servers[0].String())
}
}
func connectMqttAlert() {
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("%s:%d", getConfig().Alert.MQTT.Server, getConfig().Alert.MQTT.Port))
opts.SetUsername(getConfig().Monitor.MQTT.User)
opts.SetPassword(getConfig().Monitor.MQTT.Password)
alertMqttClient = mqtt.NewClient(opts)
if token := alertMqttClient.Connect(); token.Wait() && token.Error() != nil {
log("Unable to connect to MQTT for alerting: " + token.Error().Error())
} else {
log("Connected to MQTT server for alerting at " + opts.Servers[0].String())
}
}
// finds a custom name in the configuration for a given topic
func findTopicName(topic string) string {
for _, t := range getConfig().Monitor.MQTT.Targets {
if t.Topic == topic && t.Name != "" {
return t.Name
}
}
return topic
}
// Receives an MQTT message and updates status accordingly.
func onMessageReceived(client mqtt.Client, message mqtt.Message) {
debug("MQTT: " + message.Topic() + ": " + string(message.Payload()))
monitorData.Lock()
defer monitorData.Unlock()
e, ok := monitorData.MQTT[message.Topic()]
if !ok {
monitorData.MQTT[message.Topic()] = &MQTTMonitorData{}
e = monitorData.MQTT[message.Topic()]
e.Name = findTopicName(message.Topic())
}
if e.Deleted {
return
}
e.History = append(e.History, TimedEntry{time.Now(), string(message.Payload())})
if len(e.History) > getConfig().Monitor.MQTT.History {
e.History = e.History[1:]
}
var total float64 = 0
for i, v := range e.History {
if i > 0 {
total += v.Timestamp.Sub(e.History[i-1].Timestamp).Seconds()
}
}
e.AvgTransmit = total / float64(len(e.History)-1)
if e.FirstSeen.IsZero() {
e.FirstSeen = time.Now()
}
e.LastSeen = time.Now()
e.LastPayload = string(message.Payload())
e.Samples++
}
// Launch infinite loops for monitoring and alerting.
func monitoringLoop() {
debug("Entering monitoring loop")
go func() {
for {
evaluateMQTT()
time.Sleep(time.Second)
}
}()
go func() {
for {
checkPing()
time.Sleep(time.Second)
}
}()
go func() {
for {
checkHTTP()
time.Sleep(time.Second)
}
}()
go func() {
for {
checkExec()
time.Sleep(time.Second)
}
}()
}
// Periodically evaluate MQTT monitoring targets and issue alerts/recoveries as needed.
func evaluateMQTT() {
// Attempt MQTT connection if configured but not connected
if getConfig().Monitor.MQTT.Server != "" {
if monitorMqttClient == nil || !monitorMqttClient.IsConnected() {
connectMqtt()
}
}
monitorData.Lock()
defer monitorData.Unlock()
for topic, v := range monitorData.MQTT {
if v.Deleted {
continue
}
elapsed := time.Since(v.LastSeen).Seconds()
var timeout float64
// use overridden timeout if specified
if v.CustomTimeout > 0 {
timeout = v.CustomTimeout
} else {
// use configured timeout otherwise (general, specific)
timeout = v.AvgTransmit * getConfig().Monitor.MQTT.StandardTimeout
for _, t := range getConfig().Monitor.MQTT.Targets {
if matchMQTTTopic(t.Topic, topic) && t.Timeout > 0 {
timeout = float64(t.Timeout)
break
}
}
}
// Store calculated timeout for showing on web
v.Timeout = timeout
// no custom timeout is configured, AvgTransmit is not yet established (NaN) -> skip
if math.IsNaN(timeout) {
continue
}
if elapsed > timeout {
if v.Status != STATUS_ERROR {
alert("MQTT", v.Name, STATUS_ERROR, v.LastSeen, fmt.Sprintf("timeout %.2fs", timeout))
v.LastError = time.Now()
v.Alerts++
}
v.Status = STATUS_ERROR
} else if v.AvgTransmit > 0 && elapsed > v.AvgTransmit {
v.Status = STATUS_WARN
} else {
if v.Status == STATUS_ERROR {
alert("MQTT", v.Name, STATUS_OK, v.LastError, "")
}
v.Status = STATUS_OK
}
monitorData.MQTT[topic] = v
}
}
// Matches and MQTT topic 'subject' to a topic pattern 'pattern', potentially containing wildcard ('#' / '+').
// Based on https://github.com/RangerMauve/mqtt-pattern
// Returns true if matches, false if not.
func matchMQTTTopic(pattern string, subject string) bool {
sl := strings.Split(subject, "/")
pl := strings.Split(pattern, "/")
slen := len(sl)
plen := len(pl)
lasti := plen - 1
for i := range pl {
if len(pl[i]) == 0 && len(sl[i]) == 0 {
continue
}
if len(pl[i]) == 0 {
continue
}
if len(sl[i]) == 0 && pl[i][0] != '#' {
return false
}
if pl[i][0] == '#' {
return i == lasti
}
if pl[i][0] != '+' && pl[i] != sl[i] {
return false
}
}
return plen == slen
}
// Periodically iterate through ping targets and perform check if required.
func checkPing() {
monitorData.RLock()
defer monitorData.RUnlock()
for address, e := range monitorData.Ping {
ts := e.Timestamp
// proceed only if last check (regardless of outcome) was before now minus the configured interval
if ts.Add(time.Duration(e.Interval) * time.Second).Before(time.Now()) {
monitorData.RUnlock()
r := ping(address)
debug(fmt.Sprintf("Pinging %s: %t", address, r))
monitorData.Lock()
e.Timestamp = time.Now()
if r {
e.TotalOK++
e.LastOK = time.Now()
e.Errors = 0
if e.Status == STATUS_ERROR {
alert("Ping", e.Name, STATUS_OK, e.LastErrorStart, "")
}
e.Status = STATUS_OK
} else {
e.Errors++
e.TotalError++
e.LastError = time.Now()
// First error will set STATUS_WARN, error will be triggered after the threshold
if e.Status == STATUS_OK {
e.Status = STATUS_WARN
}
if e.Status == STATUS_WARN && e.Errors >= e.Threshold {
alert("Ping", e.Name, STATUS_ERROR, e.LastOK, "")
e.Status = STATUS_ERROR
e.LastErrorStart = time.Now()
}
}
monitorData.Unlock()
monitorData.RLock()
}
}
}
// Periodically iterate through HTTP targets and perform check if required.
func checkHTTP() {
monitorData.RLock()
defer monitorData.RUnlock()
for address, e := range monitorData.HTTP {
ts := e.Timestamp
// proceed only if last check (regardless of outcome) was before now minus the configured interval
if ts.Add(time.Duration(e.Interval) * time.Second).Before(time.Now()) {
monitorData.RUnlock()
r, err, val := performHTTPCheck(address, e.Value, e.Timeout)
debug(fmt.Sprintf("HTTP request %s: %t %s", address, r, err))
monitorData.Lock()
e.Timestamp = time.Now()
if r {
e.TotalOK++
e.LastOK = time.Now()
e.LastValue = val
e.Errors = 0
if e.Status == STATUS_ERROR {
alert("HTTP", e.Name, STATUS_OK, e.LastErrorStart, "")
}
e.Status = STATUS_OK
} else {
e.Errors++
e.TotalError++
e.LastError = time.Now()
e.LastErrorValue = err
// First error will set STATUS_WARN, error will be triggered after the threshold
if e.Status == STATUS_OK {
e.Status = STATUS_WARN
}
if e.Status == STATUS_WARN && e.Errors >= e.Threshold {
alert("HTTP", e.Name, STATUS_ERROR, e.LastOK, err)
e.Status = STATUS_ERROR
e.LastErrorStart = time.Now()
}
}
monitorData.Unlock()
monitorData.RLock()
}
}
}
// Periodically iterate through exec targets and perform check if required.
func checkExec() {
monitorData.RLock()
defer monitorData.RUnlock()
for command, e := range monitorData.Exec {
ts := e.Timestamp
// proceed only if last check (regardless of outcome) was before now minus the configured interval
if ts.Add(time.Duration(e.Interval) * time.Second).Before(time.Now()) {
monitorData.RUnlock()
r := performExecCheck(command, e.Timeout)
monitorData.Lock()
e.Timestamp = time.Now()
if r {
e.TotalOK++
e.LastOK = time.Now()
e.Errors = 0
if e.Status == STATUS_ERROR {
alert("Exec", e.Name, STATUS_OK, e.LastErrorStart, "")
}
e.Status = STATUS_OK
} else {
e.Errors++
e.TotalError++
e.LastError = time.Now()
// First error will set STATUS_WARN, error will be triggered after the threshold
if e.Status == STATUS_OK {
e.Status = STATUS_WARN
}
if e.Status == STATUS_WARN && e.Errors >= e.Threshold {
alert("Exec", e.Name, STATUS_ERROR, e.LastOK, "")
e.Status = STATUS_ERROR
e.LastErrorStart = time.Now()
}
}
monitorData.Unlock()
monitorData.RLock()
}
}
}
// Perform exec check for a single target.
// Return false in case of error or timeout.
func performExecCheck(command string, timeout int) bool {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Millisecond)
defer cancel()
var cmd *exec.Cmd
if runtime.GOOS == "windows" {
cmd = exec.CommandContext(ctx, command)
} else {
cmd = exec.CommandContext(ctx, "sh", "-c", command)
}
out, err := cmd.Output()
debug(fmt.Sprintf("Exec %s output: %s", command, out))
if ctx.Err() == context.DeadlineExceeded {
debug(fmt.Sprintf("Exec %s: timeout exceeded", command))
return false
} else if err != nil {
debug(fmt.Sprintf("Exec %s: %s", command, err))
return false
} else {
debug(fmt.Sprintf("Exec %s: OK", command))
return true
}
}
// Perform check for a single 'url', potentially matching content against 'pattern'.
// Returns boolean, error string, content string.
func performHTTPCheck(url string, pattern string, timeout int) (bool, string, string) {
errValue := ""
okValue := ""
client := http.Client{
Timeout: time.Millisecond * time.Duration(timeout),
}
resp, err := client.Get(url)
if err != nil {
errValue = err.Error()
} else if resp.StatusCode != http.StatusOK {
errValue = fmt.Sprintf("status code %d", resp.StatusCode)
} else {
defer resp.Body.Close()
bodyBytes, bodyErr := io.ReadAll(resp.Body)
if bodyErr != nil {
errValue = bodyErr.Error()
} else {
okValue = string(bodyBytes)
if pattern != "" && !strings.Contains(okValue, pattern) {
errValue = "Response does not match pattern"
}
}
}
return errValue == "", errValue, okValue
}
// Pings a host with a single packet (Linux and Windows).
// Returns false if ping exits with error code or with "Destination host unreachable".
// Returns true in case of successful ping.
func ping(host string) bool {
cmd := exec.Command("ping", "-c", "1", host)
if runtime.GOOS == "windows" {
cmd = exec.Command("ping", "-n", "1", host)
}
out, err := cmd.Output()
if err != nil || strings.Contains(string(out), "Destination host unreachable") {
return false
}
return true
}
// Processes a log entry, prepending it to logHistory, truncating logHistory if needed.
func log(s string) {
logLock.Lock()
entry := TimedEntry{time.Now(), s}
fmt.Printf("[%s] %s\n", entry.Timestamp.Format("2006-01-02 15:04:05"), entry.Value)
logHistory = append(logHistory, TimedEntry{})
copy(logHistory[1:], logHistory)
logHistory[0] = entry
if len(logHistory) > getConfig().LogSize {
logHistory = logHistory[:getConfig().LogSize]
}
logLock.Unlock()
}
// Omits a debug log entry, if debug logging is enabled.
func debug(s string) {
if getConfig().Debug {
log("(" + s + ")")
}
}
// getConfig returns the current configuration.
func getConfig() *Config {
configLock.RLock()
defer configLock.RUnlock()
return config
}
// Serves the main web page.
func serveIndex(w http.ResponseWriter, r *http.Request) {