/
uptime.go
115 lines (85 loc) · 1.74 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 main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/smtp"
"os"
"runtime"
"sync"
"time"
)
var wg sync.WaitGroup
var config Config
const delay = 1e9 * 100
type SMTPConfig struct {
Username string
Password string
Host string
OutgoingServer string `json:"outgoing_server"`
From string
}
type Config struct {
ToEmail []string `json:"to_email"`
DomainList []string `json:"domain_list"`
SMTP SMTPConfig
}
func main() {
runtime.GOMAXPROCS(4)
configFile, err := ioutil.ReadFile("./config.json")
if err != nil {
fmt.Printf("Failed to read config file: %v\n", err)
os.Exit(1)
}
json.Unmarshal(configFile, &config)
for {
go ping(config.DomainList)
time.Sleep(delay)
}
}
func ping(domainList []string) {
for i := range domainList {
fmt.Println("Pinging", domainList[i])
wg.Add(1)
go func(domain string) {
url := fmt.Sprintf("http://%s", domain)
res, err := http.Head(url)
if err == nil {
if res.StatusCode == 200 {
fmt.Println("Site is up")
} else {
fmt.Println("Site is down:", res.Status)
go alert(domain, res.Status)
}
} else {
fmt.Println("Site didn't respond:", err)
go alert(domain, err.Error())
}
wg.Done()
}(domainList[i])
wg.Wait()
}
}
func alert(domain string, error_message string) {
fmt.Println("Sending mail")
subject := fmt.Sprintf("Subject: %s is down\r\n\r\n", domain)
auth := smtp.PlainAuth(
"",
config.SMTP.Username,
config.SMTP.Password,
config.SMTP.Host,
)
err := smtp.SendMail(
config.SMTP.OutgoingServer,
auth,
config.SMTP.From,
config.ToEmail,
[]byte(subject+error_message),
)
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Mail sent")
}
}