-
Notifications
You must be signed in to change notification settings - Fork 7
/
notify.go
219 lines (172 loc) · 5.19 KB
/
notify.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
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/slack-go/slack"
"github.com/hashicorp/go-retryablehttp"
"gitlab.com/tozd/go/errors"
)
const (
envSobaNtfyURL = "SOBA_NTFY_URL"
envSlackChannelID = "SLACK_CHANNEL_ID"
envSlackAPIToken = "SLACK_API_TOKEN"
envTelegramBotToken = "SOBA_TELEGRAM_BOT_TOKEN"
envTelegramChatID = "SOBA_TELEGRAM_CHAT_ID"
)
func getResultsErrors(results BackupResults) []errors.E {
var errs []errors.E
if results.Results == nil {
return nil
}
for _, providerResults := range *results.Results {
if providerResults.Results.Error != nil {
errs = append(errs, providerResults.Results.Error)
}
}
return errs
}
func notify(backupResults BackupResults, succeeded int, failed int) {
// optimistic create retryable http client
errs := getResultsErrors(backupResults)
webHookURL := os.Getenv(envSobaWebHookURL)
if webHookURL != "" {
err := sendWebhook(httpClient, sobaTime{
Time: time.Now(),
f: time.RFC3339,
}, backupResults, os.Getenv(envSobaWebHookURL), os.Getenv(envSobaWebHookFormat))
if err != nil {
logger.Printf("error sending webhook: %s", err)
} else {
logger.Println("webhook sent")
}
}
ntfyURL := os.Getenv(envSobaNtfyURL)
if ntfyURL != "" {
sendNtfy(httpClient, ntfyURL, succeeded, failed, errs)
}
slackChannelID := os.Getenv(envSlackChannelID)
if slackChannelID != "" {
sendSlackMessage(slackChannelID, succeeded, failed, errs)
}
telegramBotToken := os.Getenv(envTelegramBotToken)
telegramChatID := os.Getenv(envTelegramChatID)
if telegramBotToken != "" && telegramChatID != "" {
sendTelegramMessage(httpClient, telegramBotToken, telegramChatID, succeeded, failed, errs)
}
}
func sendTelegramMessage(hc *retryablehttp.Client, botToken, chatID string, succeeded, failed int, errs []errors.E) {
var text string
switch {
case succeeded > 0 && failed == 0:
text = "🚀 soba backups succeeded"
case failed > 0 && succeeded > 0:
text = "️⚠️ soba backups completed with errors"
default:
text = "️🚨 soba backups failed"
}
text += fmt.Sprintf("\ncompleted: %d, failed: %d",
succeeded, failed)
if len(errs) > 0 && errs[0] != nil {
text = fmt.Sprintf("%s\nerror: %s", text, errs[0].Error())
}
apiURL := "https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" +
chatID + "&text=" + url.QueryEscape(text)
req, err := retryablehttp.NewRequest(http.MethodPost, apiURL, nil)
if err != nil {
logger.Printf("telegram failed to create request: %v", err)
return
}
req.Header.Add("Content-Type", "application/json")
resp, err := hc.Do(req)
if err != nil {
logger.Printf("telegram failed to send api request - error: %s", err)
return
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
logger.Printf("telegram failed to close response body - error: %s", err)
}
}(resp.Body)
buf, err := io.ReadAll(resp.Body)
if err != nil {
logger.Printf("telegram failed to read response: %v", err)
return
}
if resp.StatusCode != 200 {
logger.Printf("telegram failed to send message - code [%d] - msg [%s]", resp.StatusCode, string(buf))
return
}
logger.Printf("telegram message successfully sent to chat id %s", chatID)
}
func sendNtfy(hc *retryablehttp.Client, nURL string, succeeded, failed int, errs []errors.E) {
nu, err := url.Parse(nURL)
if err != nil {
logger.Printf("ntfy failed to parse url: %v", err)
return
}
var req *retryablehttp.Request
msg := fmt.Sprintf("completed: %d, failed: %d",
succeeded, failed)
if len(errs) > 0 && errs[0] != nil {
msg = fmt.Sprintf("%s\nerror: %s", msg, errs[0].Error())
}
req, err = retryablehttp.NewRequest(http.MethodPost, nu.String(),
strings.NewReader(msg))
if err != nil {
logger.Printf("ntfy failed to create request: %v", err)
return
}
switch {
case succeeded > 0 && failed == 0:
req.Header.Set("Title", "🚀 soba backups succeeded")
case failed > 0 && succeeded > 0:
req.Header.Set("Title", "️⚠️ soba backups completed with errors")
default:
req.Header.Set("Title", "️🚨 soba backups failed")
}
req.Header.Set("Tags", "soba,backup,git")
_, err = hc.Do(req)
if err != nil {
logger.Printf("error: %s", err)
}
logger.Println("ntfy publish sent")
}
func sendSlackMessage(slackChannelID string, succeeded, failed int, errs []errors.E) {
errorMsgs := make([]string, 0)
for _, err := range errs {
if err != nil {
errorMsgs = append(errorMsgs, err.Error())
}
}
var title string
switch {
case succeeded > 0 && failed == 0:
title = "🚀 soba backups succeeded"
case failed > 0 && succeeded > 0:
title = "️⚠️ soba backups completed with errors"
default:
title = "️🚨 soba backups failed"
}
attachment := slack.Attachment{
Pretext: fmt.Sprintf("succeeded: %d, failed: %d", succeeded, failed),
Text: strings.Join(errorMsgs, "\n"),
}
api := slack.New(os.Getenv(envSlackAPIToken))
channelID, timestamp, err := api.PostMessage(
slackChannelID,
slack.MsgOptionText(title, false),
slack.MsgOptionAttachments(attachment),
slack.MsgOptionAsUser(true),
)
if err != nil {
logger.Println(err.Error())
return
}
logger.Printf("slack message successfully sent to channel %s at %s", channelID, timestamp)
}