alert_notification.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. if _, err := sess.Insert(notificationState); err != nil {
  202. if dialect.IsUniqueConstraintViolation(err) {
  203. return m.ErrAlertNotificationStateAlreadyExist
  204. }
  205. return err
  206. }
  207. return nil
  208. })
  209. }
  210. func SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToCompleteCommand) error {
  211. return withDbSession(ctx, func(sess *DBSession) error {
  212. sql := `UPDATE alert_notification_state SET
  213. state= ?
  214. WHERE
  215. id = ?`
  216. res, err := sess.Exec(sql, m.AlertNotificationStateCompleted, cmd.Id)
  217. if err != nil {
  218. return err
  219. }
  220. affected, _ := res.RowsAffected()
  221. if affected == 0 {
  222. return m.ErrAlertNotificationStateVersionConflict
  223. }
  224. return nil
  225. })
  226. }
  227. func SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *m.SetAlertNotificationStateToPendingCommand) error {
  228. return withDbSession(ctx, func(sess *DBSession) error {
  229. sql := `UPDATE alert_notification_state SET
  230. state= ?,
  231. version = ?
  232. WHERE
  233. id = ? AND
  234. version = ?`
  235. res, err := sess.Exec(sql, m.AlertNotificationStatePending, cmd.State.Version+1, cmd.State.Id, cmd.State.Version)
  236. if err != nil {
  237. return err
  238. }
  239. affected, _ := res.RowsAffected()
  240. if affected == 0 {
  241. return m.ErrAlertNotificationStateVersionConflict
  242. }
  243. return nil
  244. })
  245. }
  246. func GetAlertNotificationState(ctx context.Context, cmd *m.GetNotificationStateQuery) error {
  247. return withDbSession(ctx, func(sess *DBSession) error {
  248. nj := &m.AlertNotificationState{}
  249. exist, err := getAlertNotificationState(sess, cmd, nj)
  250. // if exists, return it, otherwise create it with default values
  251. if err != nil {
  252. return err
  253. }
  254. if exist {
  255. cmd.Result = nj
  256. return nil
  257. }
  258. // normally flow ends here
  259. if !exist {
  260. notificationState := &m.AlertNotificationState{
  261. OrgId: cmd.OrgId,
  262. AlertId: cmd.AlertId,
  263. NotifierId: cmd.NotifierId,
  264. State: "unknown",
  265. }
  266. _, err := sess.Insert(notificationState)
  267. uniqenessIndexFailureCodes := []string{
  268. "UNIQUE constraint failed",
  269. "pq: duplicate key value violates unique constraint",
  270. "Error 1062: Duplicate entry ",
  271. }
  272. for _, code := range uniqenessIndexFailureCodes {
  273. if strings.HasPrefix(err.Error(), code) {
  274. exist, err = getAlertNotificationState(sess, cmd, nj)
  275. if exist && err == nil {
  276. cmd.Result = nj
  277. return nil
  278. }
  279. }
  280. }
  281. if err != nil {
  282. return err
  283. }
  284. }
  285. cmd.Result = nj
  286. return nil
  287. })
  288. }
  289. func getAlertNotificationState(sess *DBSession, cmd *m.GetNotificationStateQuery, nj *m.AlertNotificationState) (bool, error) {
  290. exist, err := sess.Desc("alert_notification_state.sent_at").
  291. Where("alert_notification_state.org_id = ?", cmd.OrgId).
  292. Where("alert_notification_state.alert_id = ?", cmd.AlertId).
  293. Where("alert_notification_state.notifier_id = ?", cmd.NotifierId).
  294. Get(nj)
  295. return exist, err
  296. }