alert_notification.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. package sqlstore
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/bus"
  9. m "github.com/grafana/grafana/pkg/models"
  10. )
  11. func init() {
  12. bus.AddHandler("sql", GetAlertNotifications)
  13. bus.AddHandler("sql", CreateAlertNotificationCommand)
  14. bus.AddHandler("sql", UpdateAlertNotification)
  15. bus.AddHandler("sql", DeleteAlertNotification)
  16. bus.AddHandler("sql", GetAlertNotificationsToSend)
  17. bus.AddHandler("sql", GetAllAlertNotifications)
  18. bus.AddHandlerCtx("sql", InsertAlertNotificationState)
  19. bus.AddHandlerCtx("sql", GetAlertNotificationState)
  20. bus.AddHandlerCtx("sql", SetAlertNotificationStateToCompleteCommand)
  21. bus.AddHandlerCtx("sql", SetAlertNotificationStateToPendingCommand)
  22. }
  23. func DeleteAlertNotification(cmd *m.DeleteAlertNotificationCommand) error {
  24. return inTransaction(func(sess *DBSession) error {
  25. sql := "DELETE FROM alert_notification WHERE alert_notification.org_id = ? AND alert_notification.id = ?"
  26. _, err := sess.Exec(sql, cmd.OrgId, cmd.Id)
  27. return err
  28. })
  29. }
  30. func GetAlertNotifications(query *m.GetAlertNotificationsQuery) error {
  31. return getAlertNotificationInternal(query, newSession())
  32. }
  33. func GetAllAlertNotifications(query *m.GetAllAlertNotificationsQuery) error {
  34. results := make([]*m.AlertNotification, 0)
  35. if err := x.Where("org_id = ?", query.OrgId).Find(&results); err != nil {
  36. return err
  37. }
  38. query.Result = results
  39. return nil
  40. }
  41. func GetAlertNotificationsToSend(query *m.GetAlertNotificationsToSendQuery) error {
  42. var sql bytes.Buffer
  43. params := make([]interface{}, 0)
  44. sql.WriteString(`SELECT
  45. alert_notification.id,
  46. alert_notification.org_id,
  47. alert_notification.name,
  48. alert_notification.type,
  49. alert_notification.created,
  50. alert_notification.updated,
  51. alert_notification.settings,
  52. alert_notification.is_default,
  53. alert_notification.send_reminder,
  54. alert_notification.frequency
  55. FROM alert_notification
  56. `)
  57. sql.WriteString(` WHERE alert_notification.org_id = ?`)
  58. params = append(params, query.OrgId)
  59. sql.WriteString(` AND ((alert_notification.is_default = ?)`)
  60. params = append(params, dialect.BooleanStr(true))
  61. if len(query.Ids) > 0 {
  62. sql.WriteString(` OR alert_notification.id IN (?` + strings.Repeat(",?", len(query.Ids)-1) + ")")
  63. for _, v := range query.Ids {
  64. params = append(params, v)
  65. }
  66. }
  67. sql.WriteString(`)`)
  68. results := make([]*m.AlertNotification, 0)
  69. if err := x.SQL(sql.String(), params...).Find(&results); err != nil {
  70. return err
  71. }
  72. query.Result = results
  73. return nil
  74. }
  75. func getAlertNotificationInternal(query *m.GetAlertNotificationsQuery, sess *DBSession) error {
  76. var sql bytes.Buffer
  77. params := make([]interface{}, 0)
  78. sql.WriteString(`SELECT
  79. alert_notification.id,
  80. alert_notification.org_id,
  81. alert_notification.name,
  82. alert_notification.type,
  83. alert_notification.created,
  84. alert_notification.updated,
  85. alert_notification.settings,
  86. alert_notification.is_default,
  87. alert_notification.send_reminder,
  88. alert_notification.frequency
  89. FROM alert_notification
  90. `)
  91. sql.WriteString(` WHERE alert_notification.org_id = ?`)
  92. params = append(params, query.OrgId)
  93. if query.Name != "" || query.Id != 0 {
  94. if query.Name != "" {
  95. sql.WriteString(` AND alert_notification.name = ?`)
  96. params = append(params, query.Name)
  97. }
  98. if query.Id != 0 {
  99. sql.WriteString(` AND alert_notification.id = ?`)
  100. params = append(params, query.Id)
  101. }
  102. }
  103. results := make([]*m.AlertNotification, 0)
  104. if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
  105. return err
  106. }
  107. if len(results) == 0 {
  108. query.Result = nil
  109. } else {
  110. query.Result = results[0]
  111. }
  112. return nil
  113. }
  114. func CreateAlertNotificationCommand(cmd *m.CreateAlertNotificationCommand) error {
  115. return inTransaction(func(sess *DBSession) error {
  116. existingQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
  117. err := getAlertNotificationInternal(existingQuery, sess)
  118. if err != nil {
  119. return err
  120. }
  121. if existingQuery.Result != nil {
  122. return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
  123. }
  124. var frequency time.Duration
  125. if cmd.SendReminder {
  126. if cmd.Frequency == "" {
  127. return m.ErrNotificationFrequencyNotFound
  128. }
  129. frequency, err = time.ParseDuration(cmd.Frequency)
  130. if err != nil {
  131. return err
  132. }
  133. }
  134. alertNotification := &m.AlertNotification{
  135. OrgId: cmd.OrgId,
  136. Name: cmd.Name,
  137. Type: cmd.Type,
  138. Settings: cmd.Settings,
  139. SendReminder: cmd.SendReminder,
  140. Frequency: frequency,
  141. Created: time.Now(),
  142. Updated: time.Now(),
  143. IsDefault: cmd.IsDefault,
  144. }
  145. if _, err = sess.MustCols("send_reminder").Insert(alertNotification); err != nil {
  146. return err
  147. }
  148. cmd.Result = alertNotification
  149. return nil
  150. })
  151. }
  152. func UpdateAlertNotification(cmd *m.UpdateAlertNotificationCommand) error {
  153. return inTransaction(func(sess *DBSession) (err error) {
  154. current := m.AlertNotification{}
  155. if _, err = sess.ID(cmd.Id).Get(&current); err != nil {
  156. return err
  157. }
  158. // check if name exists
  159. sameNameQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
  160. if err := getAlertNotificationInternal(sameNameQuery, sess); err != nil {
  161. return err
  162. }
  163. if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
  164. return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
  165. }
  166. current.Updated = time.Now()
  167. current.Settings = cmd.Settings
  168. current.Name = cmd.Name
  169. current.Type = cmd.Type
  170. current.IsDefault = cmd.IsDefault
  171. current.SendReminder = cmd.SendReminder
  172. if current.SendReminder {
  173. if cmd.Frequency == "" {
  174. return m.ErrNotificationFrequencyNotFound
  175. }
  176. frequency, err := time.ParseDuration(cmd.Frequency)
  177. if err != nil {
  178. return err
  179. }
  180. current.Frequency = frequency
  181. }
  182. sess.UseBool("is_default", "send_reminder")
  183. if affected, err := sess.ID(cmd.Id).Update(current); err != nil {
  184. return err
  185. } else if affected == 0 {
  186. return fmt.Errorf("Could not update alert notification")
  187. }
  188. cmd.Result = &current
  189. return nil
  190. })
  191. }
  192. func InsertAlertNotificationState(ctx context.Context, cmd *m.InsertAlertNotificationCommand) error {
  193. return withDbSession(ctx, func(sess *DBSession) error {
  194. notificationState := &m.AlertNotificationState{
  195. OrgId: cmd.OrgId,
  196. AlertId: cmd.AlertId,
  197. NotifierId: cmd.NotifierId,
  198. SentAt: cmd.SentAt,
  199. State: cmd.State,
  200. }
  201. _, err := sess.Insert(notificationState)
  202. if err == nil {
  203. return nil
  204. }
  205. uniqenessIndexFailureCodes := []string{
  206. "UNIQUE constraint failed",
  207. "pq: duplicate key value violates unique constraint",
  208. "Error 1062: Duplicate entry ",
  209. }
  210. for _, code := range uniqenessIndexFailureCodes {
  211. if strings.HasPrefix(err.Error(), code) {
  212. return m.ErrAlertNotificationStateAlreadyExist
  213. }
  214. }
  215. return err
  216. })
  217. }
  218. func SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToCompleteCommand) error {
  219. return withDbSession(ctx, func(sess *DBSession) error {
  220. sql := `UPDATE alert_notification_state SET
  221. state= ?
  222. WHERE
  223. id = ?`
  224. res, err := sess.Exec(sql, m.AlertNotificationStateCompleted, cmd.Id)
  225. if err != nil {
  226. return err
  227. }
  228. affected, _ := res.RowsAffected()
  229. if affected == 0 {
  230. return m.ErrAlertNotificationStateVersionConflict
  231. }
  232. return nil
  233. })
  234. }
  235. func SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToPendingCommand) error {
  236. return withDbSession(ctx, func(sess *DBSession) error {
  237. sql := `UPDATE alert_notification_state SET
  238. state= ?,
  239. version = ?
  240. WHERE
  241. id = ? AND
  242. version = ?`
  243. res, err := sess.Exec(sql, m.AlertNotificationStatePending, cmd.Version+1, cmd.Id, cmd.Version)
  244. if err != nil {
  245. return err
  246. }
  247. affected, _ := res.RowsAffected()
  248. if affected == 0 {
  249. return m.ErrAlertNotificationStateVersionConflict
  250. }
  251. return nil
  252. })
  253. }
  254. func GetAlertNotificationState(ctx context.Context, cmd *m.GetNotificationStateQuery) error {
  255. return withDbSession(ctx, func(sess *DBSession) error {
  256. nj := &m.AlertNotificationState{}
  257. exist, err := sess.Desc("alert_notification_state.sent_at").
  258. Where("alert_notification_state.org_id = ?", cmd.OrgId).
  259. Where("alert_notification_state.alert_id = ?", cmd.AlertId).
  260. Where("alert_notification_state.notifier_id = ?", cmd.NotifierId).
  261. Get(nj)
  262. if err != nil {
  263. return err
  264. }
  265. if !exist {
  266. return m.ErrAlertNotificationStateNotFound
  267. }
  268. cmd.Result = nj
  269. return nil
  270. })
  271. }