alert_notification.go 9.4 KB

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