alert_notification.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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", 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 SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToCompleteCommand) error {
  193. return withDbSession(ctx, func(sess *DBSession) error {
  194. version := cmd.State.Version
  195. var current m.AlertNotificationState
  196. sess.ID(cmd.State.Id).Get(&current)
  197. cmd.State.State = m.AlertNotificationStateCompleted
  198. cmd.State.Version++
  199. sql := `UPDATE alert_notification_state SET
  200. state = ?,
  201. version = ?,
  202. sent_at = ?,
  203. updated_at = ?
  204. WHERE
  205. id = ?`
  206. _, err := sess.Exec(sql, cmd.State.State, cmd.State.Version, cmd.State.SentAt, timeNow().Unix(), cmd.State.Id)
  207. if err != nil {
  208. return err
  209. }
  210. if current.Version != version {
  211. return m.ErrAlertNotificationStateVersionConflict
  212. }
  213. return nil
  214. })
  215. }
  216. func SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToPendingCommand) error {
  217. return withDbSession(ctx, func(sess *DBSession) error {
  218. currentVersion := cmd.State.Version
  219. cmd.State.State = m.AlertNotificationStatePending
  220. cmd.State.Version++
  221. sql := `UPDATE alert_notification_state SET
  222. state = ?,
  223. version = ?,
  224. updated_at = ?
  225. WHERE
  226. id = ? AND
  227. version = ?`
  228. res, err := sess.Exec(sql, cmd.State.State, cmd.State.Version, timeNow().Unix(), cmd.State.Id, currentVersion)
  229. if err != nil {
  230. return err
  231. }
  232. affected, _ := res.RowsAffected()
  233. if affected == 0 {
  234. return m.ErrAlertNotificationStateVersionConflict
  235. }
  236. return nil
  237. })
  238. }
  239. func GetAlertNotificationState(ctx context.Context, cmd *m.GetNotificationStateQuery) error {
  240. return withDbSession(ctx, func(sess *DBSession) error {
  241. nj := &m.AlertNotificationState{}
  242. exist, err := getAlertNotificationState(sess, cmd, nj)
  243. // if exists, return it, otherwise create it with default values
  244. if err != nil {
  245. return err
  246. }
  247. if exist {
  248. cmd.Result = nj
  249. return nil
  250. }
  251. notificationState := &m.AlertNotificationState{
  252. OrgId: cmd.OrgId,
  253. AlertId: cmd.AlertId,
  254. NotifierId: cmd.NotifierId,
  255. State: "unknown",
  256. UpdatedAt: timeNow().Unix(),
  257. }
  258. if _, err := sess.Insert(notificationState); err != nil {
  259. if dialect.IsUniqueConstraintViolation(err) {
  260. exist, err = getAlertNotificationState(sess, cmd, nj)
  261. if err != nil {
  262. return err
  263. }
  264. if !exist {
  265. return errors.New("Should not happen")
  266. }
  267. cmd.Result = nj
  268. return nil
  269. }
  270. return err
  271. }
  272. cmd.Result = notificationState
  273. return nil
  274. })
  275. }
  276. func getAlertNotificationState(sess *DBSession, cmd *m.GetNotificationStateQuery, nj *m.AlertNotificationState) (bool, error) {
  277. exist, err := sess.
  278. Where("alert_notification_state.org_id = ?", cmd.OrgId).
  279. Where("alert_notification_state.alert_id = ?", cmd.AlertId).
  280. Where("alert_notification_state.notifier_id = ?", cmd.NotifierId).
  281. Get(nj)
  282. return exist, err
  283. }