grafana/pkg/services/sqlstore/alert_notification.go

362 lines
9.2 KiB
Go
Raw Normal View History

2016-06-13 22:39:00 +08:00
package sqlstore
import (
"bytes"
"context"
2018-09-28 17:17:03 +08:00
"errors"
"fmt"
"strings"
"time"
2016-06-13 22:39:00 +08:00
"github.com/grafana/grafana/pkg/bus"
m "github.com/grafana/grafana/pkg/models"
)
func init() {
bus.AddHandler("sql", GetAlertNotifications)
bus.AddHandler("sql", CreateAlertNotificationCommand)
bus.AddHandler("sql", UpdateAlertNotification)
bus.AddHandler("sql", DeleteAlertNotification)
bus.AddHandler("sql", GetAlertNotificationsToSend)
bus.AddHandler("sql", GetAllAlertNotifications)
bus.AddHandlerCtx("sql", GetOrCreateAlertNotificationState)
bus.AddHandlerCtx("sql", SetAlertNotificationStateToCompleteCommand)
bus.AddHandlerCtx("sql", SetAlertNotificationStateToPendingCommand)
}
func DeleteAlertNotification(cmd *m.DeleteAlertNotificationCommand) error {
return inTransaction(func(sess *DBSession) error {
sql := "DELETE FROM alert_notification WHERE alert_notification.org_id = ? AND alert_notification.id = ?"
if _, err := sess.Exec(sql, cmd.OrgId, cmd.Id); err != nil {
return err
}
if _, err := sess.Exec("DELETE FROM alert_notification_state WHERE alert_notification_state.org_id = ? AND alert_notification_state.notifier_id = ?", cmd.OrgId, cmd.Id); err != nil {
return err
}
return nil
})
2016-06-13 22:39:00 +08:00
}
func GetAlertNotifications(query *m.GetAlertNotificationsQuery) error {
return getAlertNotificationInternal(query, newSession())
}
func GetAllAlertNotifications(query *m.GetAllAlertNotificationsQuery) error {
results := make([]*m.AlertNotification, 0)
if err := x.Where("org_id = ?", query.OrgId).Find(&results); err != nil {
return err
}
query.Result = results
return nil
}
func GetAlertNotificationsToSend(query *m.GetAlertNotificationsToSendQuery) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
sql.WriteString(`SELECT
alert_notification.id,
alert_notification.org_id,
alert_notification.name,
alert_notification.type,
alert_notification.created,
alert_notification.updated,
alert_notification.settings,
2018-05-21 00:12:10 +08:00
alert_notification.is_default,
alert_notification.send_reminder,
2018-05-21 00:12:10 +08:00
alert_notification.frequency
FROM alert_notification
`)
sql.WriteString(` WHERE alert_notification.org_id = ?`)
params = append(params, query.OrgId)
sql.WriteString(` AND ((alert_notification.is_default = ?)`)
params = append(params, dialect.BooleanStr(true))
if len(query.Ids) > 0 {
sql.WriteString(` OR alert_notification.id IN (?` + strings.Repeat(",?", len(query.Ids)-1) + ")")
for _, v := range query.Ids {
params = append(params, v)
}
}
sql.WriteString(`)`)
results := make([]*m.AlertNotification, 0)
2018-01-24 05:30:45 +08:00
if err := x.SQL(sql.String(), params...).Find(&results); err != nil {
return err
}
query.Result = results
return nil
}
func getAlertNotificationInternal(query *m.GetAlertNotificationsQuery, sess *DBSession) error {
2016-06-13 22:39:00 +08:00
var sql bytes.Buffer
params := make([]interface{}, 0)
sql.WriteString(`SELECT
alert_notification.id,
alert_notification.org_id,
alert_notification.name,
alert_notification.type,
alert_notification.created,
alert_notification.updated,
alert_notification.settings,
2018-05-21 00:12:10 +08:00
alert_notification.is_default,
alert_notification.send_reminder,
2018-05-21 00:12:10 +08:00
alert_notification.frequency
FROM alert_notification
`)
2016-06-13 22:39:00 +08:00
sql.WriteString(` WHERE alert_notification.org_id = ?`)
params = append(params, query.OrgId)
2016-06-13 22:39:00 +08:00
if query.Name != "" || query.Id != 0 {
if query.Name != "" {
sql.WriteString(` AND alert_notification.name = ?`)
params = append(params, query.Name)
}
2016-06-13 22:39:00 +08:00
if query.Id != 0 {
sql.WriteString(` AND alert_notification.id = ?`)
params = append(params, query.Id)
}
}
results := make([]*m.AlertNotification, 0)
pkg/services/sqlstore: Fix x.Sql is deprecated: use SQL instead. (megacheck) See, $ gometalinter --vendor --disable-all --enable=megacheck --disable=gotype --deadline 6m ./... | grep SQL alert.go:43:9:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) alert_notification.go:122:12:warning: sess.Sql is deprecated: use SQL instead. (SA1019) (megacheck) annotation.go:226:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) dashboard.go:228:9:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) dashboard.go:302:10:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) dashboard.go:416:9:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) dashboard.go:635:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) migrations/user_mig.go:137:9:warning: sess.Sql is deprecated: use SQL instead. (SA1019) (megacheck) plugin_setting.go:29:10:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) quota.go:41:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) quota.go:84:13:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) quota.go:143:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) quota.go:186:13:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) quota.go:234:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) team.go:172:12:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) team.go:199:17:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) team.go:223:9:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) temp_user.go:99:10:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) temp_user.go:124:10:warning: x.Sql is deprecated: use SQL instead. (SA1019) (megacheck) user.go:375:3:warning: sess.Sql is deprecated: use SQL instead. (SA1019) (megacheck) user.go:377:3:warning: sess.Sql is deprecated: use SQL instead. (SA1019) (megacheck) user.go:379:3:warning: sess.Sql is deprecated: use SQL instead. (SA1019) (megacheck)
2018-09-16 18:26:05 +08:00
if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
2016-06-13 22:39:00 +08:00
return err
}
if len(results) == 0 {
query.Result = nil
} else {
query.Result = results[0]
}
2016-06-13 22:39:00 +08:00
return nil
}
func CreateAlertNotificationCommand(cmd *m.CreateAlertNotificationCommand) error {
return inTransaction(func(sess *DBSession) error {
existingQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
err := getAlertNotificationInternal(existingQuery, sess)
if err != nil {
return err
}
if existingQuery.Result != nil {
return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
}
2016-06-13 22:39:00 +08:00
2018-05-26 02:14:33 +08:00
var frequency time.Duration
if cmd.SendReminder {
if cmd.Frequency == "" {
return m.ErrNotificationFrequencyNotFound
}
frequency, err = time.ParseDuration(cmd.Frequency)
if err != nil {
return err
}
2018-05-21 00:12:10 +08:00
}
alertNotification := &m.AlertNotification{
OrgId: cmd.OrgId,
Name: cmd.Name,
Type: cmd.Type,
Settings: cmd.Settings,
SendReminder: cmd.SendReminder,
Frequency: frequency,
Created: time.Now(),
Updated: time.Now(),
IsDefault: cmd.IsDefault,
}
2016-06-13 22:39:00 +08:00
if _, err = sess.MustCols("send_reminder").Insert(alertNotification); err != nil {
return err
}
cmd.Result = alertNotification
return nil
2016-06-13 22:39:00 +08:00
})
}
func UpdateAlertNotification(cmd *m.UpdateAlertNotificationCommand) error {
return inTransaction(func(sess *DBSession) (err error) {
current := m.AlertNotification{}
2016-06-13 22:39:00 +08:00
2018-01-24 05:30:45 +08:00
if _, err = sess.ID(cmd.Id).Get(&current); err != nil {
return err
}
// check if name exists
sameNameQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
if err := getAlertNotificationInternal(sameNameQuery, sess); err != nil {
return err
}
if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
}
current.Updated = time.Now()
current.Settings = cmd.Settings
current.Name = cmd.Name
current.Type = cmd.Type
current.IsDefault = cmd.IsDefault
current.SendReminder = cmd.SendReminder
2018-05-21 00:12:10 +08:00
if current.SendReminder {
if cmd.Frequency == "" {
return m.ErrNotificationFrequencyNotFound
}
2018-05-21 04:08:42 +08:00
frequency, err := time.ParseDuration(cmd.Frequency)
if err != nil {
return err
}
current.Frequency = frequency
2018-05-21 00:12:10 +08:00
}
sess.UseBool("is_default", "send_reminder")
2018-01-24 05:30:45 +08:00
if affected, err := sess.ID(cmd.Id).Update(current); err != nil {
return err
} else if affected == 0 {
return fmt.Errorf("Could not update alert notification")
}
cmd.Result = &current
return nil
})
}
func SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToCompleteCommand) error {
return withDbSession(ctx, func(sess *DBSession) error {
version := cmd.State.Version
var current m.AlertNotificationState
sess.ID(cmd.State.Id).Get(&current)
cmd.State.State = m.AlertNotificationStateCompleted
cmd.State.Version++
sql := `UPDATE alert_notification_state SET
2018-09-28 17:17:03 +08:00
state = ?,
2018-09-28 21:11:03 +08:00
version = ?,
updated_at = ?
WHERE
id = ?`
_, err := sess.Exec(sql, cmd.State.State, cmd.State.Version, timeNow().Unix(), cmd.State.Id)
if err != nil {
return err
}
if current.Version != version {
return m.ErrAlertNotificationStateVersionConflict
}
return nil
})
}
func SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToPendingCommand) error {
return withDbSession(ctx, func(sess *DBSession) error {
currentVersion := cmd.State.Version
cmd.State.State = m.AlertNotificationStatePending
cmd.State.Version++
sql := `UPDATE alert_notification_state SET
2018-09-28 17:17:03 +08:00
state = ?,
version = ?,
updated_at = ?,
alert_rule_state_updated_version = ?
WHERE
id = ? AND
(version = ? OR alert_rule_state_updated_version < ?)`
res, err := sess.Exec(sql,
cmd.State.State,
cmd.State.Version,
timeNow().Unix(),
cmd.AlertRuleStateUpdatedVersion,
cmd.State.Id,
currentVersion,
cmd.AlertRuleStateUpdatedVersion)
if err != nil {
return err
}
affected, _ := res.RowsAffected()
if affected == 0 {
return m.ErrAlertNotificationStateVersionConflict
}
return nil
})
}
func GetOrCreateAlertNotificationState(ctx context.Context, cmd *m.GetOrCreateNotificationStateQuery) error {
return withDbSession(ctx, func(sess *DBSession) error {
2018-09-26 23:26:02 +08:00
nj := &m.AlertNotificationState{}
exist, err := getAlertNotificationState(sess, cmd, nj)
2018-09-27 20:32:54 +08:00
// if exists, return it, otherwise create it with default values
if err != nil {
return err
}
if exist {
cmd.Result = nj
return nil
}
2018-09-28 17:17:03 +08:00
notificationState := &m.AlertNotificationState{
OrgId: cmd.OrgId,
AlertId: cmd.AlertId,
NotifierId: cmd.NotifierId,
State: m.AlertNotificationStateUnknown,
UpdatedAt: timeNow().Unix(),
2018-09-28 17:17:03 +08:00
}
2018-09-27 20:32:54 +08:00
2018-09-28 17:17:03 +08:00
if _, err := sess.Insert(notificationState); err != nil {
if dialect.IsUniqueConstraintViolation(err) {
exist, err = getAlertNotificationState(sess, cmd, nj)
2018-09-27 20:32:54 +08:00
2018-09-28 17:17:03 +08:00
if err != nil {
return err
}
2018-09-28 17:17:03 +08:00
if !exist {
return errors.New("Should not happen")
2018-09-27 20:32:54 +08:00
}
2018-09-28 17:17:03 +08:00
cmd.Result = nj
return nil
}
2018-09-28 17:17:03 +08:00
return err
}
2018-09-28 17:17:03 +08:00
cmd.Result = notificationState
return nil
})
}
func getAlertNotificationState(sess *DBSession, cmd *m.GetOrCreateNotificationStateQuery, nj *m.AlertNotificationState) (bool, error) {
return sess.
Where("alert_notification_state.org_id = ?", cmd.OrgId).
Where("alert_notification_state.alert_id = ?", cmd.AlertId).
Where("alert_notification_state.notifier_id = ?", cmd.NotifierId).
Get(nj)
}