engine.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. alertMaxAttempts = 3
  92. )
  93. func (e *AlertingService) processJobWithRetry(grafanaCtx context.Context, job *Job) error {
  94. defer func() {
  95. if err := recover(); err != nil {
  96. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  97. }
  98. }()
  99. cancelChan := make(chan context.CancelFunc, alertMaxAttempts)
  100. attemptChan := make(chan int, 1)
  101. // Initialize with first attemptID=1
  102. attemptChan <- 1
  103. job.Running = true
  104. for {
  105. select {
  106. case <-grafanaCtx.Done():
  107. // In case grafana server context is cancel, let a chance to job processing
  108. // to finish gracefully - by waiting a timeout duration - before forcing its end.
  109. unfinishedWorkTimer := time.NewTimer(unfinishedWorkTimeout)
  110. select {
  111. case <-unfinishedWorkTimer.C:
  112. return e.endJob(grafanaCtx.Err(), cancelChan, job)
  113. case <-attemptChan:
  114. return e.endJob(nil, cancelChan, job)
  115. }
  116. case attemptID, more := <-attemptChan:
  117. if !more {
  118. return e.endJob(nil, cancelChan, job)
  119. }
  120. go e.processJob(attemptID, attemptChan, cancelChan, job)
  121. }
  122. }
  123. }
  124. func (e *AlertingService) endJob(err error, cancelChan chan context.CancelFunc, job *Job) error {
  125. job.Running = false
  126. close(cancelChan)
  127. for cancelFn := range cancelChan {
  128. cancelFn()
  129. }
  130. return err
  131. }
  132. func (e *AlertingService) processJob(attemptID int, attemptChan chan int, cancelChan chan context.CancelFunc, job *Job) {
  133. defer func() {
  134. if err := recover(); err != nil {
  135. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  136. }
  137. }()
  138. alertCtx, cancelFn := context.WithTimeout(context.Background(), alertTimeout)
  139. cancelChan <- cancelFn
  140. span := opentracing.StartSpan("alert execution")
  141. alertCtx = opentracing.ContextWithSpan(alertCtx, span)
  142. evalContext := NewEvalContext(alertCtx, job.Rule)
  143. evalContext.Ctx = alertCtx
  144. go func() {
  145. defer func() {
  146. if err := recover(); err != nil {
  147. e.log.Error("Alert Panic", "error", err, "stack", log.Stack(1))
  148. ext.Error.Set(span, true)
  149. span.LogFields(
  150. tlog.Error(fmt.Errorf("%v", err)),
  151. tlog.String("message", "failed to execute alert rule. panic was recovered."),
  152. )
  153. span.Finish()
  154. close(attemptChan)
  155. }
  156. }()
  157. e.evalHandler.Eval(evalContext)
  158. span.SetTag("alertId", evalContext.Rule.Id)
  159. span.SetTag("dashboardId", evalContext.Rule.DashboardId)
  160. span.SetTag("firing", evalContext.Firing)
  161. span.SetTag("nodatapoints", evalContext.NoDataFound)
  162. span.SetTag("attemptID", attemptID)
  163. if evalContext.Error != nil {
  164. ext.Error.Set(span, true)
  165. span.LogFields(
  166. tlog.Error(evalContext.Error),
  167. tlog.String("message", "alerting execution attempt failed"),
  168. )
  169. if attemptID < alertMaxAttempts {
  170. span.Finish()
  171. e.log.Debug("Job Execution attempt triggered retry", "timeMs", evalContext.GetDurationMs(), "alertId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "firing", evalContext.Firing, "attemptID", attemptID)
  172. attemptChan <- (attemptID + 1)
  173. return
  174. }
  175. }
  176. evalContext.Rule.State = evalContext.GetNewState()
  177. e.resultHandler.Handle(evalContext)
  178. span.Finish()
  179. e.log.Debug("Job Execution completed", "timeMs", evalContext.GetDurationMs(), "alertId", evalContext.Rule.Id, "name", evalContext.Rule.Name, "firing", evalContext.Firing, "attemptID", attemptID)
  180. close(attemptChan)
  181. }()
  182. }