alert_notification.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package sqlstore
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/grafana/grafana/pkg/bus"
  10. m "github.com/grafana/grafana/pkg/models"
  11. )
  12. func init() {
  13. bus.AddHandler("sql", GetAlertNotifications)
  14. bus.AddHandler("sql", CreateAlertNotificationCommand)
  15. bus.AddHandler("sql", UpdateAlertNotification)
  16. bus.AddHandler("sql", DeleteAlertNotification)
  17. bus.AddHandler("sql", GetAlertNotificationsToSend)
  18. bus.AddHandler("sql", GetAllAlertNotifications)
  19. bus.AddHandlerCtx("sql", GetOrCreateAlertNotificationState)
  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. if _, err := sess.Exec(sql, cmd.OrgId, cmd.Id); err != nil {
  27. return err
  28. }
  29. 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 {
  30. return err
  31. }
  32. return nil
  33. })
  34. }
  35. func GetAlertNotifications(query *m.GetAlertNotificationsQuery) error {
  36. return getAlertNotificationInternal(query, newSession())
  37. }
  38. func GetAllAlertNotifications(query *m.GetAllAlertNotificationsQuery) error {
  39. results := make([]*m.AlertNotification, 0)
  40. if err := x.Where("org_id = ?", query.OrgId).Find(&results); err != nil {
  41. return err
  42. }
  43. query.Result = results
  44. return nil
  45. }
  46. func GetAlertNotificationsToSend(query *m.GetAlertNotificationsToSendQuery) error {
  47. var sql bytes.Buffer
  48. params := make([]interface{}, 0)
  49. sql.WriteString(`SELECT
  50. alert_notification.id,
  51. alert_notification.org_id,
  52. alert_notification.name,
  53. alert_notification.type,
  54. alert_notification.created,
  55. alert_notification.updated,
  56. alert_notification.settings,
  57. alert_notification.is_default,
  58. alert_notification.disable_resolve_message,
  59. alert_notification.send_reminder,
  60. alert_notification.frequency
  61. FROM alert_notification
  62. `)
  63. sql.WriteString(` WHERE alert_notification.org_id = ?`)
  64. params = append(params, query.OrgId)
  65. sql.WriteString(` AND ((alert_notification.is_default = ?)`)
  66. params = append(params, dialect.BooleanStr(true))
  67. if len(query.Ids) > 0 {
  68. sql.WriteString(` OR alert_notification.id IN (?` + strings.Repeat(",?", len(query.Ids)-1) + ")")
  69. for _, v := range query.Ids {
  70. params = append(params, v)
  71. }
  72. }
  73. sql.WriteString(`)`)
  74. results := make([]*m.AlertNotification, 0)
  75. if err := x.SQL(sql.String(), params...).Find(&results); err != nil {
  76. return err
  77. }
  78. query.Result = results
  79. return nil
  80. }
  81. func getAlertNotificationInternal(query *m.GetAlertNotificationsQuery, sess *DBSession) error {
  82. var sql bytes.Buffer
  83. params := make([]interface{}, 0)
  84. sql.WriteString(`SELECT
  85. alert_notification.id,
  86. alert_notification.org_id,
  87. alert_notification.name,
  88. alert_notification.type,
  89. alert_notification.created,
  90. alert_notification.updated,
  91. alert_notification.settings,
  92. alert_notification.is_default,
  93. alert_notification.disable_resolve_message,
  94. alert_notification.send_reminder,
  95. alert_notification.frequency
  96. FROM alert_notification
  97. `)
  98. sql.WriteString(` WHERE alert_notification.org_id = ?`)
  99. params = append(params, query.OrgId)
  100. if query.Name != "" || query.Id != 0 {
  101. if query.Name != "" {
  102. sql.WriteString(` AND alert_notification.name = ?`)
  103. params = append(params, query.Name)
  104. }
  105. if query.Id != 0 {
  106. sql.WriteString(` AND alert_notification.id = ?`)
  107. params = append(params, query.Id)
  108. }
  109. }
  110. results := make([]*m.AlertNotification, 0)
  111. if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
  112. return err
  113. }
  114. if len(results) == 0 {
  115. query.Result = nil
  116. } else {
  117. query.Result = results[0]
  118. }
  119. return nil
  120. }
  121. func CreateAlertNotificationCommand(cmd *m.CreateAlertNotificationCommand) error {
  122. return inTransaction(func(sess *DBSession) error {
  123. existingQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
  124. err := getAlertNotificationInternal(existingQuery, sess)
  125. if err != nil {
  126. return err
  127. }
  128. if existingQuery.Result != nil {
  129. return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
  130. }
  131. var frequency time.Duration
  132. if cmd.SendReminder {
  133. if cmd.Frequency == "" {
  134. return m.ErrNotificationFrequencyNotFound
  135. }
  136. frequency, err = time.ParseDuration(cmd.Frequency)
  137. if err != nil {
  138. return err
  139. }
  140. }
  141. alertNotification := &m.AlertNotification{
  142. OrgId: cmd.OrgId,
  143. Name: cmd.Name,
  144. Type: cmd.Type,
  145. Settings: cmd.Settings,
  146. SendReminder: cmd.SendReminder,
  147. DisableResolveMessage: cmd.DisableResolveMessage,
  148. Frequency: frequency,
  149. Created: time.Now(),
  150. Updated: time.Now(),
  151. IsDefault: cmd.IsDefault,
  152. }
  153. if _, err = sess.MustCols("send_reminder").Insert(alertNotification); err != nil {
  154. return err
  155. }
  156. cmd.Result = alertNotification
  157. return nil
  158. })
  159. }
  160. func UpdateAlertNotification(cmd *m.UpdateAlertNotificationCommand) error {
  161. return inTransaction(func(sess *DBSession) (err error) {
  162. current := m.AlertNotification{}
  163. if _, err = sess.ID(cmd.Id).Get(&current); err != nil {
  164. return err
  165. }
  166. // check if name exists
  167. sameNameQuery := &m.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
  168. if err := getAlertNotificationInternal(sameNameQuery, sess); err != nil {
  169. return err
  170. }
  171. if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
  172. return fmt.Errorf("Alert notification name %s already exists", cmd.Name)
  173. }
  174. current.Updated = time.Now()
  175. current.Settings = cmd.Settings
  176. current.Name = cmd.Name
  177. current.Type = cmd.Type
  178. current.IsDefault = cmd.IsDefault
  179. current.SendReminder = cmd.SendReminder
  180. current.DisableResolveMessage = cmd.DisableResolveMessage
  181. if current.SendReminder {
  182. if cmd.Frequency == "" {
  183. return m.ErrNotificationFrequencyNotFound
  184. }
  185. frequency, err := time.ParseDuration(cmd.Frequency)
  186. if err != nil {
  187. return err
  188. }
  189. current.Frequency = frequency
  190. }
  191. sess.UseBool("is_default", "send_reminder", "disable_resolve_message")
  192. if affected, err := sess.ID(cmd.Id).Update(current); err != nil {
  193. return err
  194. } else if affected == 0 {
  195. return fmt.Errorf("Could not update alert notification")
  196. }
  197. cmd.Result = &current
  198. return nil
  199. })
  200. }
  201. func SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToCompleteCommand) error {
  202. return inTransactionCtx(ctx, func(sess *DBSession) error {
  203. version := cmd.Version
  204. var current m.AlertNotificationState
  205. sess.ID(cmd.Id).Get(&current)
  206. newVersion := cmd.Version + 1
  207. sql := `UPDATE alert_notification_state SET
  208. state = ?,
  209. version = ?,
  210. updated_at = ?
  211. WHERE
  212. id = ?`
  213. _, err := sess.Exec(sql, m.AlertNotificationStateCompleted, newVersion, timeNow().Unix(), cmd.Id)
  214. if err != nil {
  215. return err
  216. }
  217. if current.Version != version {
  218. sqlog.Error("notification state out of sync. the notification is marked as complete but has been modified between set as pending and completion.", "notifierId", current.NotifierId)
  219. }
  220. return nil
  221. })
  222. }
  223. func SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToPendingCommand) error {
  224. return withDbSession(ctx, func(sess *DBSession) error {
  225. newVersion := cmd.Version + 1
  226. sql := `UPDATE alert_notification_state SET
  227. state = ?,
  228. version = ?,
  229. updated_at = ?,
  230. alert_rule_state_updated_version = ?
  231. WHERE
  232. id = ? AND
  233. (version = ? OR alert_rule_state_updated_version < ?)`
  234. res, err := sess.Exec(sql,
  235. m.AlertNotificationStatePending,
  236. newVersion,
  237. timeNow().Unix(),
  238. cmd.AlertRuleStateUpdatedVersion,
  239. cmd.Id,
  240. cmd.Version,
  241. cmd.AlertRuleStateUpdatedVersion)
  242. if err != nil {
  243. return err
  244. }
  245. affected, _ := res.RowsAffected()
  246. if affected == 0 {
  247. return m.ErrAlertNotificationStateVersionConflict
  248. }
  249. cmd.ResultVersion = newVersion
  250. return nil
  251. })
  252. }
  253. func GetOrCreateAlertNotificationState(ctx context.Context, cmd *m.GetOrCreateNotificationStateQuery) error {
  254. return inTransactionCtx(ctx, func(sess *DBSession) error {
  255. nj := &m.AlertNotificationState{}
  256. exist, err := getAlertNotificationState(sess, cmd, nj)
  257. // if exists, return it, otherwise create it with default values
  258. if err != nil {
  259. return err
  260. }
  261. if exist {
  262. cmd.Result = nj
  263. return nil
  264. }
  265. notificationState := &m.AlertNotificationState{
  266. OrgId: cmd.OrgId,
  267. AlertId: cmd.AlertId,
  268. NotifierId: cmd.NotifierId,
  269. State: m.AlertNotificationStateUnknown,
  270. UpdatedAt: timeNow().Unix(),
  271. }
  272. if _, err := sess.Insert(notificationState); err != nil {
  273. if dialect.IsUniqueConstraintViolation(err) {
  274. exist, err = getAlertNotificationState(sess, cmd, nj)
  275. if err != nil {
  276. return err
  277. }
  278. if !exist {
  279. return errors.New("Should not happen")
  280. }
  281. cmd.Result = nj
  282. return nil
  283. }
  284. return err
  285. }
  286. cmd.Result = notificationState
  287. return nil
  288. })
  289. }
  290. func getAlertNotificationState(sess *DBSession, cmd *m.GetOrCreateNotificationStateQuery, nj *m.AlertNotificationState) (bool, error) {
  291. return sess.
  292. Where("alert_notification_state.org_id = ?", cmd.OrgId).
  293. Where("alert_notification_state.alert_id = ?", cmd.AlertId).
  294. Where("alert_notification_state.notifier_id = ?", cmd.NotifierId).
  295. Get(nj)
  296. }