-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
194 lines (158 loc) · 4.88 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/smtp"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"time"
"github.com/codeskyblue/go-sh"
)
// smtpServer data to smtp server.
type smtpServer struct {
host string
port string
}
// Address URI to smtp server.
func (s *smtpServer) Address() string {
return s.host + ":" + s.port
}
//GetEnvVar is a helper function for gathering env variables
func GetEnvVar(key, fallback string) string {
value, exists := os.LookupEnv(key)
if !exists {
value = fallback
}
return value
}
type logFormat struct {
Loglevel string `json:"level"`
Caller string `json:"caller"`
Message string `json:"message"`
}
//LogMessage prints in JSON format
func LogMessage(logLevel, message string) {
//identify calling function
pc, _, _, _ := runtime.Caller(1)
details := runtime.FuncForPC(pc)
logStruct := logFormat{Loglevel: logLevel, Caller: details.Name(), Message: message}
logStr, _ := json.Marshal(logStruct)
log.Println(string(logStr))
}
//runCommand runs the ping test and greps appropriately for packet loss
func runCommand(commandApp string, args []string) (string, string, error) {
log.Println(args[0])
log.Println(args[1])
cmd := exec.Command(commandApp, args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
LogMessage("ERROR", "runCommand:"+string(stderr.Bytes()))
return "", "", err
}
return string(stdout.Bytes()), string(stderr.Bytes()), nil
}
//pingTest will run test pings to a destination and report on packet loss
func pingTest(destination string, count string) (string, error) {
log.Println("starting ping...")
var grepStr string
// var err error
if runtime.GOOS == "darwin" {
grepStr = "7"
} else {
grepStr = "6"
}
output, err := sh.Command("ping", destination, "-c", count).Command("grep", "loss").Command("awk", "{print $"+grepStr+"}").Output()
//log errors and return
if err != nil {
LogMessage("ERROR", err.Error())
return string(output), err
}
outputStr := strings.TrimSpace(string(output))
return outputStr, nil
}
//sendeEmail will send email alerts
func sendEmail(message string) {
//set variables from ENV
emailPassword := os.Getenv("EMAIL_PASSWORD")
senderEmail := os.Getenv("SENDER_EMAIL")
destEmail := []string{os.Getenv("DEST_EMAIL")}
smtpHost := os.Getenv("SMTP_HOST")
smtpPort := os.Getenv("SMTP_PORT")
smtpServer := smtpServer{host: smtpHost, port: smtpPort}
emailMessage := []byte(message)
auth := smtp.PlainAuth("", senderEmail, emailPassword, smtpServer.host)
err := smtp.SendMail(smtpServer.Address(), auth, senderEmail, destEmail, emailMessage)
if err != nil {
// fmt.Println(err)
LogMessage("ERROR", err.Error())
return
}
fmt.Println("Email Sent!")
}
//parsePingTimeResult checks results for errors
func parsePingTestResult(pingResult string, err error, packetLossPercentage float64) {
if err != nil {
LogMessage("ERROR", "pingResult:"+pingResult+" err:"+err.Error())
sendEmail("pingResult:" + pingResult + " err:" + err.Error())
return
} else if pingResult != "0%" && pingResult != "0.0%" {
//convert to float and check if packet loss is higher than packetLossPercentage send email alerts
LogMessage("ERROR", "packet loss: "+pingResult)
pingResult = strings.Trim(pingResult, "%")
pingResultInt, err := strconv.ParseFloat(pingResult, 64)
if err != nil {
LogMessage("ERROR", "coudln't convert pingResult: "+err.Error())
return
} else if pingResultInt >= packetLossPercentage {
sendEmail("packet loss: " + pingResult)
return
}
}
// LogMessage("INFO", "packet loss: "+pingResult)
return
}
func main() {
//Initialize variables
destination := GetEnvVar("PING_DESTINATION", "google.com")
count := GetEnvVar("PING_COUNT", "10")
_, err := strconv.Atoi(count)
if err != nil {
log.Fatal("Need an integer for the PING_COUNT variable.")
}
loopStr := GetEnvVar("LOOP", "0")
loop, err := strconv.Atoi(loopStr)
if err != nil {
log.Fatal("Need an integer for the LOOP variable.")
}
packetLossPercentageStr := GetEnvVar("PACKET_LOSS_PERCENTAGE", "10")
packetLossPercentage, err := strconv.ParseFloat(packetLossPercentageStr, 64)
if err != nil || packetLossPercentage > 100 || packetLossPercentage < 0 {
log.Fatal("Need a digit between 1 and 100 for PACKET_LOSS_PERCENTAGE variable.")
}
fmt.Printf("\ncount:%s", count)
fmt.Printf("\ndestination:%s", destination)
fmt.Printf("\nchecking for %v%% packet loss\n\n", packetLossPercentage)
//loop x number of times otherwise continue
if loop != 0 {
for i := 0; i < loop; i++ {
//invoke pingTest and then parse results
pingResult, err := pingTest(destination, count)
parsePingTestResult(pingResult, err, packetLossPercentage)
}
} else {
for {
//invoke pingTest and then parse results
pingResult, err := pingTest(destination, count)
parsePingTestResult(pingResult, err, packetLossPercentage)
time.Sleep(5 * time.Second)
}
}
}