huginn_scheduler.rb 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. require 'rufus/scheduler'
  2. class Rufus::Scheduler
  3. SCHEDULER_AGENT_TAG = Agents::SchedulerAgent.name
  4. class Job
  5. # Store an ID of SchedulerAgent in this job.
  6. def scheduler_agent_id=(id)
  7. self[:scheduler_agent_id] = id
  8. end
  9. # Extract an ID of SchedulerAgent if any.
  10. def scheduler_agent_id
  11. self[:scheduler_agent_id]
  12. end
  13. # Return a SchedulerAgent tied to this job. Return nil if it is
  14. # not found or disabled.
  15. def scheduler_agent
  16. agent_id = scheduler_agent_id or return nil
  17. Agent.of_type(Agents::SchedulerAgent).active.find_by(id: agent_id)
  18. end
  19. end
  20. # Get all jobs tied to any SchedulerAgent
  21. def scheduler_agent_jobs
  22. jobs(tag: SCHEDULER_AGENT_TAG)
  23. end
  24. # Get a job tied to a given SchedulerAgent
  25. def scheduler_agent_job(agent)
  26. scheduler_agent_jobs.find { |job|
  27. job.scheduler_agent_id == agent.id
  28. }
  29. end
  30. # Schedule or reschedule a job for a given SchedulerAgent and return
  31. # the running job. Return nil if unscheduled.
  32. def schedule_scheduler_agent(agent)
  33. job = scheduler_agent_job(agent)
  34. if agent.unavailable?
  35. if job
  36. puts "Unscheduling SchedulerAgent##{agent.id} (disabled)"
  37. job.unschedule
  38. end
  39. nil
  40. else
  41. if job
  42. return job if agent.memory['scheduled_at'] == job.scheduled_at.to_i
  43. puts "Rescheduling SchedulerAgent##{agent.id}"
  44. job.unschedule
  45. else
  46. puts "Scheduling SchedulerAgent##{agent.id}"
  47. end
  48. agent_id = agent.id
  49. job = schedule_cron agent.options['schedule'], tag: SCHEDULER_AGENT_TAG do |job|
  50. job.scheduler_agent_id = agent_id
  51. if scheduler_agent = job.scheduler_agent
  52. scheduler_agent.check!
  53. else
  54. puts "Unscheduling SchedulerAgent##{job.scheduler_agent_id} (disabled or deleted)"
  55. job.unschedule
  56. end
  57. end
  58. # Make sure the job is associated with a SchedulerAgent before
  59. # it is triggered.
  60. job.scheduler_agent_id = agent_id
  61. agent.memory['scheduled_at'] = job.scheduled_at.to_i
  62. agent.save
  63. job
  64. end
  65. end
  66. # Schedule or reschedule jobs for all SchedulerAgents and unschedule
  67. # orphaned jobs if any.
  68. def schedule_scheduler_agents
  69. scheduled_jobs = Agent.of_type(Agents::SchedulerAgent).map { |scheduler_agent|
  70. schedule_scheduler_agent(scheduler_agent)
  71. }.compact
  72. (scheduler_agent_jobs - scheduled_jobs).each { |job|
  73. puts "Unscheduling SchedulerAgent##{job.scheduler_agent_id} (orphaned)"
  74. job.unschedule
  75. }
  76. end
  77. end
  78. class HuginnScheduler
  79. FAILED_JOBS_TO_KEEP = 100
  80. attr_accessor :mutex
  81. def initialize(options = {})
  82. @rufus_scheduler = Rufus::Scheduler.new(options)
  83. self.mutex = Mutex.new
  84. end
  85. def stop
  86. @rufus_scheduler.stop
  87. end
  88. def run!
  89. tzinfo_friendly_timezone = ActiveSupport::TimeZone::MAPPING[ENV['TIMEZONE'].present? ? ENV['TIMEZONE'] : "Pacific Time (US & Canada)"]
  90. # Schedule event propagation.
  91. @rufus_scheduler.every '1m' do
  92. propagate!
  93. end
  94. # Schedule event cleanup.
  95. @rufus_scheduler.cron "0 0 * * * " + tzinfo_friendly_timezone do
  96. cleanup_expired_events!
  97. end
  98. # Schedule failed job cleanup.
  99. @rufus_scheduler.every '1h' do
  100. cleanup_failed_jobs!
  101. end
  102. # Schedule repeating events.
  103. %w[1m 2m 5m 10m 30m 1h 2h 5h 12h 1d 2d 7d].each do |schedule|
  104. @rufus_scheduler.every schedule do
  105. run_schedule "every_#{schedule}"
  106. end
  107. end
  108. # Schedule events for specific times.
  109. 24.times do |hour|
  110. @rufus_scheduler.cron "0 #{hour} * * * " + tzinfo_friendly_timezone do
  111. run_schedule hour_to_schedule_name(hour)
  112. end
  113. end
  114. # Schedule Scheduler Agents
  115. @rufus_scheduler.every '1m' do
  116. @rufus_scheduler.schedule_scheduler_agents
  117. end
  118. @rufus_scheduler.join
  119. end
  120. private
  121. def run_schedule(time)
  122. with_mutex do
  123. puts "Queuing schedule for #{time}"
  124. Agent.delay.run_schedule(time)
  125. end
  126. end
  127. def propagate!
  128. with_mutex do
  129. puts "Queuing event propagation"
  130. Agent.delay.receive!
  131. end
  132. end
  133. def cleanup_expired_events!
  134. with_mutex do
  135. puts "Running event cleanup"
  136. Event.delay.cleanup_expired!
  137. end
  138. end
  139. def cleanup_failed_jobs!
  140. num_to_keep = (ENV['FAILED_JOBS_TO_KEEP'].presence || FAILED_JOBS_TO_KEEP).to_i
  141. first_to_delete = Delayed::Job.where.not(failed_at: nil).order("failed_at DESC").offset(num_to_keep).limit(1).pluck(:failed_at).first
  142. Delayed::Job.where(["failed_at <= ?", first_to_delete]).delete_all if first_to_delete.present?
  143. end
  144. def hour_to_schedule_name(hour)
  145. if hour == 0
  146. "midnight"
  147. elsif hour < 12
  148. "#{hour}am"
  149. elsif hour == 12
  150. "noon"
  151. else
  152. "#{hour - 12}pm"
  153. end
  154. end
  155. def with_mutex
  156. ActiveRecord::Base.connection_pool.with_connection do
  157. mutex.synchronize do
  158. yield
  159. end
  160. end
  161. end
  162. end