scheduler.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package alerting
  15. import (
  16. "time"
  17. "yunion.io/x/log"
  18. "yunion.io/x/onecloud/pkg/apis/monitor"
  19. "yunion.io/x/onecloud/pkg/monitor/options"
  20. )
  21. type schedulerImpl struct {
  22. jobs map[string]*Job
  23. }
  24. func newScheduler() scheduler {
  25. return &schedulerImpl{
  26. jobs: make(map[string]*Job),
  27. }
  28. }
  29. func (s *schedulerImpl) Update(rules []*Rule) {
  30. log.Debugf("Scheduling update, rule count %d", len(rules))
  31. jobs := make(map[string]*Job)
  32. for _, rule := range rules {
  33. var job *Job
  34. if s.jobs[rule.Id] != nil {
  35. job = s.jobs[rule.Id]
  36. } else {
  37. job = &Job{}
  38. job.SetRunning(false)
  39. }
  40. job.Rule = rule
  41. //offset := ((rule.Frequency * 1000) / int64(len(rules))) * int64(i)
  42. //job.Offset = int64(math.Floor(float64(offset) / 1000))
  43. if job.Offset == 0 {
  44. // zero offset causes division with 0 panics
  45. job.Offset = 1
  46. }
  47. jobs[rule.Id] = job
  48. }
  49. s.jobs = jobs
  50. }
  51. func (s *schedulerImpl) Tick(tickTime time.Time, execQueue chan *Job) {
  52. now := tickTime.Unix()
  53. for _, job := range s.jobs {
  54. if job.GetRunning() || job.Rule.State == monitor.AlertStatePaused {
  55. continue
  56. }
  57. if job.OffsetWait && now%job.Offset == 0 {
  58. job.OffsetWait = false
  59. s.enqueue(job, execQueue)
  60. continue
  61. }
  62. // Check the job frequency against the minium interval required
  63. interval := job.Rule.Frequency
  64. if interval < options.Options.AlertingMinIntervalSeconds {
  65. interval = options.Options.AlertingMinIntervalSeconds
  66. }
  67. if now%interval == 0 {
  68. if job.Offset > 0 {
  69. job.OffsetWait = true
  70. } else {
  71. s.enqueue(job, execQueue)
  72. }
  73. }
  74. }
  75. }
  76. func (s *schedulerImpl) enqueue(job *Job, execQueue chan *Job) {
  77. log.Debugf("Scheduler: putting job into exec queue, name %s:%s", job.Rule.Name, job.Rule.Id)
  78. execQueue <- job
  79. }