/
test_notification.go
111 lines (89 loc) · 2.61 KB
/
test_notification.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
package alerting
import (
"context"
"fmt"
"github.com/Fenrislol/grafana/pkg/components/securejsondata"
"github.com/Fenrislol/grafana/pkg/bus"
"github.com/Fenrislol/grafana/pkg/components/null"
"github.com/Fenrislol/grafana/pkg/components/simplejson"
"github.com/Fenrislol/grafana/pkg/infra/log"
"github.com/Fenrislol/grafana/pkg/models"
)
// NotificationTestCommand initiates an test
// execution of an alert notification.
type NotificationTestCommand struct {
OrgID int64
ID int64
State models.AlertStateType
Name string
Type string
Settings *simplejson.Json
SecureSettings map[string]string
}
var (
logger = log.New("alerting.testnotification")
)
func init() {
bus.AddHandler("alerting", handleNotificationTestCommand)
}
func handleNotificationTestCommand(cmd *NotificationTestCommand) error {
notifier := newNotificationService(nil)
model := &models.AlertNotification{
Name: cmd.Name,
Type: cmd.Type,
Settings: cmd.Settings,
}
secureSettingsMap := map[string]string{}
if cmd.ID > 0 {
query := &models.GetAlertNotificationsQuery{
OrgId: cmd.OrgID,
Id: cmd.ID,
}
if err := bus.Dispatch(query); err != nil {
return err
}
if query.Result.SecureSettings != nil {
secureSettingsMap = query.Result.SecureSettings.Decrypt()
}
}
for k, v := range cmd.SecureSettings {
secureSettingsMap[k] = v
}
model.SecureSettings = securejsondata.GetEncryptedJsonData(secureSettingsMap)
notifiers, err := InitNotifier(model)
if err != nil {
logger.Error("Failed to create notifier", "error", err.Error())
return err
}
return notifier.sendNotifications(createTestEvalContext(cmd), notifierStateSlice{{notifier: notifiers}})
}
func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext {
testRule := &Rule{
DashboardID: 1,
PanelID: 1,
Name: "Test notification",
Message: "Someone is testing the alert notification within Grafana.",
State: models.AlertStateAlerting,
}
ctx := NewEvalContext(context.Background(), testRule)
if cmd.Settings.Get("uploadImage").MustBool(true) {
ctx.ImagePublicURL = "https://grafana.com/assets/img/blog/mixed_styles.png"
}
ctx.IsTestRun = true
ctx.Firing = true
ctx.Error = fmt.Errorf("This is only a test")
ctx.EvalMatches = evalMatchesBasedOnState()
return ctx
}
func evalMatchesBasedOnState() []*EvalMatch {
matches := make([]*EvalMatch, 0)
matches = append(matches, &EvalMatch{
Metric: "High value",
Value: null.FloatFrom(100),
})
matches = append(matches, &EvalMatch{
Metric: "Higher Value",
Value: null.FloatFrom(200),
})
return matches
}