-
Notifications
You must be signed in to change notification settings - Fork 563
/
Copy pathnotifications.go
291 lines (257 loc) · 8.37 KB
/
notifications.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package controllers
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/diggerhq/digger/ee/drift/dbmodels"
"github.com/diggerhq/digger/ee/drift/model"
utils2 "github.com/diggerhq/digger/next/utils"
"github.com/gin-gonic/gin"
"github.com/slack-go/slack"
)
func sendTestSlackWebhook(webhookURL string) error {
payload := map[string]interface{}{
"blocks": []map[string]interface{}{
{
"type": "section",
"fields": []map[string]string{
{"type": "mrkdwn", "text": "*Project*"},
{"type": "mrkdwn", "text": "*Status*"},
},
},
{"type": "divider"},
{
"type": "section",
"fields": []map[string]string{
{"type": "mrkdwn", "text": "<https://driftapp.digger.dev|Dev environment>"},
{"type": "mrkdwn", "text": ":large_yellow_circle: Drift detected"},
},
},
{"type": "divider"},
{
"type": "section",
"fields": []map[string]string{
{"type": "mrkdwn", "text": "<https://driftapp.digger.dev|Staging environment>"},
{"type": "mrkdwn", "text": ":white_circle: Acknowledged drift"},
},
},
{"type": "divider"},
{
"type": "section",
"fields": []map[string]string{
{"type": "mrkdwn", "text": "<https://driftapp.digger.dev|Prod environment>"},
{"type": "mrkdwn", "text": ":large_green_circle: No drift"},
},
},
{"type": "divider"},
{
"type": "section",
"fields": []map[string]string{
{"type": "mrkdwn", "text": ":arrow_right: *Note: This is a test notification*pwd"},
},
},
{"type": "divider"},
},
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("error marshalling JSON: %v", err)
}
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(jsonPayload))
if err != nil {
return fmt.Errorf("error sending POST request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("non-OK HTTP status: %s", resp.Status)
}
return nil
}
type TestSlackNotificationForOrgRequest struct {
OrgId string `json:"org_id"`
}
func (mc MainController) SendTestSlackNotificationForOrg(c *gin.Context) {
var request TestSlackNotificationForOrgRequest
err := c.BindJSON(&request)
if err != nil {
log.Printf("Error binding JSON: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error binding JSON"})
return
}
orgId := request.OrgId
os := dbmodels.DB.Query.OrgSetting
orgSettings, err := dbmodels.DB.Query.OrgSetting.Where(os.OrgID.Eq(orgId)).First()
if err != nil {
log.Printf("Error reading org: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error reading org"})
return
}
slackNotificationUrl := orgSettings.SlackNotificationURL
err = sendTestSlackWebhook(slackNotificationUrl)
if err != nil {
log.Printf("Error sending slack notification: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error sending slack notification"})
return
}
c.String(200, "ok")
}
func sectionBlockForProject(project model.Project) (*slack.SectionBlock, error) {
switch project.DriftStatus {
case dbmodels.DriftStatusNoDrift:
sectionBlock := slack.NewSectionBlock(
nil,
[]*slack.TextBlockObject{
slack.NewTextBlockObject("mrkdwn", fmt.Sprintf("<%v/project/%v|%v>", os.Getenv("DIGGER_APP_URL"), project.ID, project.Name), false, false),
slack.NewTextBlockObject("mrkdwn", ":large_green_circle: No Drift", false, false),
},
nil,
)
return sectionBlock, nil
case dbmodels.DriftStatusAcknowledgeDrift:
sectionBlock := slack.NewSectionBlock(
nil,
[]*slack.TextBlockObject{
slack.NewTextBlockObject("mrkdwn", fmt.Sprintf("<%v/project/%v|%v>", os.Getenv("DIGGER_APP_URL"), project.ID, project.Name), false, false),
slack.NewTextBlockObject("mrkdwn", ":white_circle: Acknowledged Drift", false, false),
},
nil,
)
return sectionBlock, nil
case dbmodels.DriftStatusNewDrift:
sectionBlock := slack.NewSectionBlock(
nil,
[]*slack.TextBlockObject{
slack.NewTextBlockObject("mrkdwn", fmt.Sprintf("<%v/project/%v|%v>", os.Getenv("DIGGER_APP_URL"), project.ID, project.Name), false, false),
slack.NewTextBlockObject("mrkdwn", ":large_yellow_circle: Drift detected", false, false),
},
nil,
)
return sectionBlock, nil
default:
return nil, fmt.Errorf("Could not")
}
}
type RealSlackNotificationForOrgRequest struct {
OrgId string `json:"org_id"`
}
func (mc MainController) SendRealSlackNotificationForOrg(c *gin.Context) {
var request RealSlackNotificationForOrgRequest
err := c.BindJSON(&request)
if err != nil {
log.Printf("Error binding JSON: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error binding JSON"})
return
}
orgId := request.OrgId
os := dbmodels.DB.Query.OrgSetting
orgSettings, err := dbmodels.DB.Query.OrgSetting.Where(os.OrgID.Eq(orgId)).First()
slackNotificationUrl := orgSettings.SlackNotificationURL
projects, err := dbmodels.DB.LoadProjectsForOrg(orgId)
if err != nil {
log.Printf("could not load projects for org %v err: %v", orgId, err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Could not load projects for org " + orgId})
return
}
numOfProjectsWithDriftEnabled := 0
var messageBlocks []slack.Block
fieldsBlock := slack.NewSectionBlock(
nil,
[]*slack.TextBlockObject{
slack.NewTextBlockObject("mrkdwn", "*Project*", false, false),
slack.NewTextBlockObject("mrkdwn", "*Status*", false, false),
},
nil,
)
messageBlocks = append(messageBlocks, fieldsBlock)
messageBlocks = append(messageBlocks, slack.NewDividerBlock())
for _, project := range projects {
if project.DriftEnabled {
numOfProjectsWithDriftEnabled++
sectionBlockForProject, err := sectionBlockForProject(*project)
if err != nil {
log.Printf("could not get block for project: %v err: %v", project.ID, err)
c.JSON(500, gin.H{"error": fmt.Sprintf("could not get notification block for project %v", project.ID)})
return
}
messageBlocks = append(messageBlocks, sectionBlockForProject)
messageBlocks = append(messageBlocks, slack.NewDividerBlock())
}
}
if numOfProjectsWithDriftEnabled == 0 {
log.Printf("no projects with drift enabled for org: %v, succeeding", orgId)
c.String(200, "ok")
return
}
msg := &slack.WebhookMessage{
Blocks: &slack.Blocks{
BlockSet: messageBlocks,
},
}
err = slack.PostWebhook(slackNotificationUrl, msg)
if err != nil {
log.Printf("error sending slack webhook: %v", err)
c.JSON(500, gin.H{"error": "error sending slack webhook"})
return
}
c.String(200, "ok")
}
func (mc MainController) ProcessAllNotifications(c *gin.Context) {
diggerHostname := os.Getenv("DIGGER_HOSTNAME")
webhookSecret := os.Getenv("DIGGER_WEBHOOK_SECRET")
orgSettings, err := dbmodels.DB.Query.OrgSetting.Find()
if err != nil {
log.Printf("could not select all orgs: %v", err)
}
sendSlackNotificationUrl, err := url.JoinPath(diggerHostname, "_internal/send_slack_notification_for_org")
if err != nil {
log.Printf("could not form drift url: %v", err)
c.JSON(500, gin.H{"error": "could not form drift url"})
return
}
for _, orgSetting := range orgSettings {
cron := orgSetting.Schedule
matches, err := utils2.MatchesCrontab(cron, time.Now().Add((-7 * time.Minute)))
if err != nil {
log.Printf("could not check matching crontab for org: %v %v", orgSetting.OrgID, err)
continue
}
if matches {
fmt.Println("Matching org ID: ", orgSetting.OrgID)
payload := RealSlackNotificationForOrgRequest{OrgId: orgSetting.OrgID}
// Convert payload to JSON
jsonPayload, err := json.Marshal(payload)
if err != nil {
fmt.Println("Process Drift: error marshaling JSON:", err)
continue
}
// Create a new request
req, err := http.NewRequest("POST", sendSlackNotificationUrl, bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Process slack notification: Error creating request:", err)
continue
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", webhookSecret))
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
continue
}
defer resp.Body.Close()
// Get the status code
statusCode := resp.StatusCode
if statusCode != 200 {
log.Printf("send slack notification got unexpected status for org: %v - status: %v", orgSetting.OrgID, statusCode)
}
}
}
c.String(200, "success")
}