engine.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. package alerting
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/opentracing/opentracing-go"
  7. "github.com/opentracing/opentracing-go/ext"
  8. tlog "github.com/opentracing/opentracing-go/log"
  9. "github.com/benbjohnson/clock"
  10. "github.com/grafana/grafana/pkg/log"
  11. "github.com/grafana/grafana/pkg/registry"
  12. "github.com/grafana/grafana/pkg/services/rendering"
  13. "github.com/grafana/grafana/pkg/setting"
  14. "golang.org/x/sync/errgroup"
  15. )
  16. type AlertingService struct {
  17. RenderService rendering.Service `inject:""`
  18. execQueue chan *Job
  19. //clock clock.Clock
  20. ticker *Ticker
  21. scheduler Scheduler
  22. evalHandler EvalHandler
  23. ruleReader RuleReader
  24. log log.Logger
  25. resultHandler ResultHandler
  26. }
  27. func init() {
  28. registry.RegisterService(&AlertingService{})
  29. }
  30. func NewEngine() *AlertingService {
  31. e := &AlertingService{}
  32. e.Init()
  33. return e
  34. }
  35. func (e *AlertingService) IsDisabled() bool {
  36. return !setting.AlertingEnabled || !setting.ExecuteAlerts
  37. }
  38. func (e *AlertingService) Init() error {
  39. e.ticker = NewTicker(time.Now(), time.Second*0, clock.New())
  40. e.execQueue = make(chan *Job, 1000)
  41. e.scheduler = NewScheduler()
  42. e.evalHandler = NewEvalHandler()
  43. e.ruleReader = NewRuleReader()
  44. e.log = log.New("alerting.engine")
  45. e.resultHandler = NewResultHandler(e.RenderService)
  46. return nil
  47. }
  48. func (e *AlertingService) Run(ctx context.Context) error {
  49. alertGroup, ctx := errgroup.WithContext(ctx)
  50. alertGroup.Go(func() error { return e.alertingTicker(ctx) })
  51. alertGroup.Go(func() error { return e.runJobDispatcher(ctx) })
  52. err := alertGroup.Wait()
  53. return err
  54. }
  55. func (e *AlertingService) alertingTicker(grafanaCtx context.Context) error {
  56. defer func() {
  57. if err := recover(); err != nil {
  58. e.log.Error("Scheduler Panic: stopping alertingTicker", "error", err, "stack", log.Stack(1))
  59. }
  60. }()
  61. tickIndex := 0
  62. for {
  63. select {
  64. case <-grafanaCtx.Done():
  65. return grafanaCtx.Err()
  66. case tick := <-e.ticker.C:
  67. // TEMP SOLUTION update rules ever tenth tick
  68. if tickIndex%10 == 0 {
  69. e.scheduler.Update(e.ruleReader.Fetch())
  70. }
  71. e.scheduler.Tick(tick, e.execQueue)
  72. tickIndex++
  73. }
  74. }
  75. }
  76. func (e *AlertingService) runJobDispatcher(grafanaCtx context.Context) error {
  77. dispatcherGroup, alertCtx := errgroup.WithContext(grafanaCtx)
  78. for {
  79. select {
  80. case <-grafanaCtx.Done():
  81. return dispatcherGroup.Wait()
  82. case job := <-e.execQueue:
  83. dispatcherGroup.Go(func() error { return e.processJobWithRetry(alertCtx, job) })
  84. }
  85. }
  86. }
  87. var (
  88. unfinishedWorkTimeout = time.Second * 5
  89. // TODO: Make alertTimeout and alertMaxAttempts configurable in the config file.
  90. alertTimeout = time.Second * 30
  91. resultHandleTimeout = time.Second * 30
  92. alertMaxAttempts = 3
  93. )
  94. func (e *AlertingService) processJobWithRetry(grafanaCtx context.Context, job *Job) error {
  95. defer func() {
  96. if err := recover(); err != nil {
  97. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  98. }
  99. }()
  100. cancelChan := make(chan context.CancelFunc, alertMaxAttempts*2)
  101. attemptChan := make(chan int, 1)
  102. // Initialize with first attemptID=1
  103. attemptChan <- 1
  104. job.Running = true
  105. for {
  106. select {
  107. case <-grafanaCtx.Done():
  108. // In case grafana server context is cancel, let a chance to job processing
  109. // to finish gracefully - by waiting a timeout duration - before forcing its end.
  110. unfinishedWorkTimer := time.NewTimer(unfinishedWorkTimeout)
  111. select {
  112. case <-unfinishedWorkTimer.C:
  113. return e.endJob(grafanaCtx.Err(), cancelChan, job)
  114. case <-attemptChan:
  115. return e.endJob(nil, cancelChan, job)
  116. }
  117. case attemptID, more := <-attemptChan:
  118. if !more {
  119. return e.endJob(nil, cancelChan, job)
  120. }
  121. go e.processJob(attemptID, attemptChan, cancelChan, job)
  122. }
  123. }
  124. }
  125. func (e *AlertingService) endJob(err error, cancelChan chan context.CancelFunc, job *Job) error {
  126. job.Running = false
  127. close(cancelChan)
  128. for cancelFn := range cancelChan {
  129. cancelFn()
  130. }
  131. return err
  132. }
  133. func (e *AlertingService) processJob(attemptID int, attemptChan chan int, cancelChan chan context.CancelFunc, job *Job) {
  134. defer func() {
  135. if err := recover(); err != nil {
  136. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  137. }
  138. }()
  139. alertCtx, cancelFn := context.WithTimeout(context.Background(), alertTimeout)
  140. cancelChan <- cancelFn
  141. span := opentracing.StartSpan("alert execution")
  142. alertCtx = opentracing.ContextWithSpan(alertCtx, span)
  143. evalContext := NewEvalContext(alertCtx, job.Rule)
  144. evalContext.Ctx = alertCtx
  145. go func() {
  146. defer func() {
  147. if err := recover(); err != nil {
  148. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  149. ext.Error.Set(span, true)
  150. span.LogFields(
  151. tlog.Error(fmt.Errorf("%v", err)),
  152. tlog.String("message", "failed to execute alert rule. panic was recovered."),
  153. )
  154. span.Finish()
  155. close(attemptChan)
  156. }
  157. }()
  158. e.evalHandler.Eval(evalContext)
  159. span.SetTag("alertId", evalContext.Rule.Id)
  160. span.SetTag("dashboardId", evalContext.Rule.DashboardId)
  161. span.SetTag("firing", evalContext.Firing)
  162. span.SetTag("nodatapoints", evalContext.NoDataFound)
  163. span.SetTag("attemptID", attemptID)
  164. if evalContext.Error != nil {
  165. ext.Error.Set(span, true)
  166. span.LogFields(
  167. tlog.Error(evalContext.Error),
  168. tlog.String("message", "alerting execution attempt failed"),
  169. )
  170. if attemptID < alertMaxAttempts {
  171. span.Finish()
  172. e.log.Debug("Job Execution attempt triggered retry", "timeMs", evalContext.GetDurationMs(), "alertId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "firing", evalContext.Firing, "attemptID", attemptID)
  173. attemptChan <- (attemptID + 1)
  174. return
  175. }
  176. }
  177. resultHandleCtx, resultHandleCancelFn := context.WithTimeout(context.Background(), resultHandleTimeout)
  178. cancelChan <- resultHandleCancelFn
  179. evalContext.Ctx = resultHandleCtx
  180. evalContext.Rule.State = evalContext.GetNewState()
  181. e.resultHandler.Handle(evalContext)
  182. span.Finish()
  183. e.log.Debug("Job Execution completed", "timeMs", evalContext.GetDurationMs(), "alertId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "firing", evalContext.Firing, "attemptID", attemptID)
  184. close(attemptChan)
  185. }()
  186. }