alert_notification.go 9.3 KB

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