-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
188 lines (164 loc) · 4.72 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
// Copyright (C) 2021 Kamel Networks
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"gopkg.in/yaml.v2"
)
var (
m = sync.Mutex{}
username = ""
password = ""
sender = ""
port = ""
)
type Alert struct {
Status string `json:"status"`
Labels map[string]string `json:"labels"`
Annotations struct {
Description string `json:"description"`
Summary string `json:"summary"`
} `json:"annotations"`
}
type Callback struct {
Alerts []Alert `json:"alerts"`
}
func handle(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
defer r.Body.Close()
var cb Callback
if err := json.Unmarshal(b, &cb); err != nil {
log.Printf("Error handling JSON: %+v", err)
http.Error(w, "Handling error", http.StatusInternalServerError)
return
}
m.Lock()
defer m.Unlock()
for _, alert := range cb.Alerts {
handleAlert(w, r, &alert)
}
}
func handleAlert(w http.ResponseWriter, r *http.Request, alert *Alert) {
id := fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%+v", alert.Labels))))
df, err := ioutil.ReadFile("active-alerts.yaml")
if os.IsNotExist(err) {
df = []byte("")
} else if err != nil {
log.Printf("Error reading active alerts YAML: %+v", err)
http.Error(w, "Handling error", http.StatusInternalServerError)
return
}
idl := []string{}
if err := yaml.Unmarshal(df, &idl); err != nil {
log.Printf("Error parsing active alerts YAML: %+v", err)
http.Error(w, "Handling error", http.StatusInternalServerError)
return
}
found := false
for _, v := range idl {
if v == id {
found = true
break
}
}
if found {
// De-dup!
return
}
idl = append(idl, id)
yidl, err := yaml.Marshal(idl)
if err != nil {
log.Printf("Error creating new active alert YAML: %v", err)
http.Error(w, "Handling error", http.StatusInternalServerError)
return
}
to := "+" + r.URL.Path[1:]
if !strings.HasPrefix(to, "+467") {
log.Printf("Number has to start with +467.., to is: %q", to)
http.Error(w, "Invalid to number", http.StatusForbidden)
return
}
log.Printf("New alert! To: %q, ID: %q, Data: %+v", to, id, alert)
message := fmt.Sprintf("%s\n%s\n\n", alert.Annotations.Summary, alert.Annotations.Description)
for k, v := range alert.Labels {
message += fmt.Sprintf("%s: %s\n", k, v)
}
log.Printf("Message: %s", message)
data := url.Values{
"from": {sender},
"to": {to},
"message": {message},
}
req, err := http.NewRequest("POST", "https://api.46elks.com/a1/sms", bytes.NewBufferString(data.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
req.SetBasicAuth(username, password)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("SMS sending failure: %+v", err)
http.Error(w, "SMS error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("SMS sending read failure: %+v", err)
http.Error(w, "SMS error", http.StatusInternalServerError)
return
}
if err := ioutil.WriteFile("active-alerts.yaml", yidl, 0644); err != nil {
log.Printf("Error write new active alert YAML: %v", err)
http.Error(w, "Handling error", http.StatusInternalServerError)
return
}
}
func main() {
log.Printf("Running")
// Read environment variables for username and password
username := os.Getenv("API_USERNAME")
if username == "" {
log.Fatal("Environment variable API_USERNAME is not set")
}
password := os.Getenv("API_PASSWORD")
if password == "" {
log.Fatal("Environment variable API_PASSWORD is not set")
}
sender := os.Getenv("API_SENDER")
if sender == "" {
log.Fatal("Environment variable API_SENDER is not set")
}
// Read the environment variable for port, and use the default port 1025 if not set
port := os.Getenv("API_PORT")
if port == "" {
port = "1025"
}
// Ask soundgoof why the port 1025 was chosen
log.Fatal(http.ListenAndServe(":"+port, http.HandlerFunc(handle)))
}