-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsysalert_slack.go
More file actions
85 lines (74 loc) · 1.89 KB
/
sysalert_slack.go
File metadata and controls
85 lines (74 loc) · 1.89 KB
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
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/mem"
)
const (
threshold = 75.0
slackWebhook = "https://hooks.slack.com/services/your/webhook/url" // Replace with your webhook URL
)
func main() {
// Get CPU usage
cpuPercent, err := cpu.Percent(time.Second, false)
if err != nil {
fmt.Println("Error fetching CPU usage in this:", err)
return
}
cpuUsage := cpuPercent[0]
// Get memory usage
vmStat, err := mem.VirtualMemory()
if err != nil {
fmt.Println("Error fetching memory stats:", err)
return
}
memUsage := vmStat.UsedPercent
// Print stats
fmt.Printf("CPU Usage: %.2f%%\n", cpuUsage)
fmt.Printf("Memory Usage: %.2f%% (Used: %.2f GB / Total: %.2f GB)\n",
memUsage,
float64(vmStat.Used)/1024/1024/1024,
float64(vmStat.Total)/1024/1024/1024,
)
// Prepare alert message
var alerts []string
if cpuUsage > threshold {
alerts = append(alerts, fmt.Sprintf("🔥 *CPU usage is high:* %.2f%%", cpuUsage))
}
if memUsage > threshold {
alerts = append(alerts, fmt.Sprintf("💾 *Memory usage is high:* %.2f%%", memUsage))
}
// Send to Slack if there are alerts
if len(alerts) > 0 {
message := map[string]string{
"text": "*System Alert on Ubuntu Server:*\n" + fmt.Sprintf("> %s", stringJoin(alerts, "\n> ")),
}
sendSlackAlert(message)
}
}
func sendSlackAlert(payload map[string]string) {
jsonPayload, _ := json.Marshal(payload)
resp, err := http.Post(slackWebhook, "application/json", bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Error sending alert to Slack:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
fmt.Println("Slack returned non-200 status:", resp.Status)
}
}
func stringJoin(arr []string, sep string) string {
result := ""
for i, s := range arr {
result += s
if i < len(arr)-1 {
result += sep
}
}
return result
}