scheduler.rb 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Scheduler < ApplicationModel
  3. extend ::Mixin::StartFinishLogger
  4. # rubocop:disable Style/ClassVars
  5. @@jobs_started = {}
  6. # rubocop:enable Style/ClassVars
  7. # start threads
  8. def self.threads
  9. Thread.abort_on_exception = true
  10. # reconnect in case db connection is lost
  11. begin
  12. ActiveRecord::Base.connection.reconnect!
  13. rescue => e
  14. logger.error "Can't reconnect to database #{e.inspect}"
  15. end
  16. # cleanup old background jobs
  17. cleanup
  18. # start worker for background jobs
  19. worker
  20. # start loop to execute scheduler jobs
  21. loop do
  22. logger.info 'Scheduler running...'
  23. # reconnect in case db connection is lost
  24. begin
  25. ActiveRecord::Base.connection.reconnect!
  26. rescue => e
  27. logger.error "Can't reconnect to database #{e.inspect}"
  28. end
  29. # read/load jobs and check if it is alredy started
  30. jobs = Scheduler.where('active = ?', true).order('prio ASC')
  31. jobs.each do |job|
  32. # ignore job is still running
  33. next if skip_job?(job)
  34. # check job.last_run
  35. next if job.last_run && job.period && job.last_run > (Time.zone.now - job.period)
  36. # run job as own thread
  37. @@jobs_started[ job.id ] = start_job(job)
  38. sleep 10
  39. end
  40. sleep 60
  41. end
  42. end
  43. # Checks if a Scheduler Job should get started or not.
  44. # The decision is based on if there is a running thread or not.
  45. # Invalid threads get canceled and new threads can get started.
  46. #
  47. # @param [Scheduler] job The job that should get checked for running threads.
  48. #
  49. # @example
  50. # Scheduler.skip_job(job)
  51. #
  52. # return [Boolean]
  53. def self.skip_job?(job)
  54. thread = @@jobs_started[ job.id ]
  55. return false if thread.blank?
  56. # check for validity of thread instance
  57. if !thread.respond_to?(:status)
  58. logger.error "Invalid thread stored for job '#{job.name}' (#{job.method}): #{thread.inspect}. Deleting and resting job."
  59. @@jobs_started.delete(job.id)
  60. return false
  61. end
  62. # check thread state:
  63. # http://devdocs.io/ruby~2.4/thread#method-i-status
  64. status = thread.status
  65. # non falsly state means it has some literal running state
  66. if status.present?
  67. logger.info "Running job thread for '#{job.name}' (#{job.method}) status is: #{status}"
  68. return true
  69. end
  70. # the following cases should not happen since the
  71. # @@jobs_started cleanup is performed inside of the
  72. # thread itself
  73. # therefore we have to log an error and remove it
  74. # from our threadpool @@jobs_started
  75. how = 'unknownly'
  76. if status.nil?
  77. how = 'via an exception'
  78. elsif status == false
  79. how = 'normally'
  80. end
  81. logger.error "Job thread terminated #{how} found for '#{job.name}' (#{job.method}). This should not happen. Please report."
  82. @@jobs_started.delete(job.id)
  83. false
  84. end
  85. # Checks all delayed jobs that are locked and cleans them up.
  86. # Should only get called when the Scheduler gets started.
  87. #
  88. # @see Scheduler#cleanup_delayed
  89. #
  90. # @param [Boolean] force forces the cleanup if not called in Scheduler starting context.
  91. #
  92. # @example
  93. # Scheduler.cleanup
  94. #
  95. # @raise [RuntimeError] If called without force and not when Scheduler gets started.
  96. #
  97. # return [nil]
  98. def self.cleanup(force: false)
  99. if !force && caller_locations(1..1).first.label != 'threads'
  100. raise 'This method should only get called when Scheduler.threads are initialized. Use `force: true` to start anyway.'
  101. end
  102. log_start_finish(:info, 'Cleanup of left over locked delayed jobs') do
  103. Delayed::Job.all.each do |job|
  104. log_start_finish(:info, "Checking left over delayed job #{job.inspect}") do
  105. cleanup_delayed(job)
  106. end
  107. end
  108. end
  109. end
  110. # Checks if the given job can be rescheduled or destroys it. Logs the action as warn.
  111. # Works only for locked jobs. Jobs that are not locked are ignored and
  112. # should get destroyed directly.
  113. # Checks the delayed job object for a method called .reschedule?. The memthod is called
  114. # with the delayed job as a parameter. The result value is expected as a Boolean. If the
  115. # result is true the lock gets removed and the delayed job gets rescheduled. If the return
  116. # value is false it will get destroyed which is the default behaviour.
  117. #
  118. # @param [Delayed::Job] job the job that should get checked for destroying/rescheduling.
  119. #
  120. # @example
  121. # Scheduler.cleanup_delayed(job)
  122. #
  123. # return [nil]
  124. def self.cleanup_delayed(job)
  125. return if job.locked_at.blank?
  126. job_name = job.name
  127. payload_object = job.payload_object
  128. reschedule = false
  129. if payload_object.present?
  130. if payload_object.respond_to?(:object)
  131. object = payload_object.object
  132. if object.respond_to?(:id)
  133. job_name += " (id: #{object.id})"
  134. end
  135. if object.respond_to?(:reschedule?) && object.reschedule?(job)
  136. reschedule = true
  137. end
  138. end
  139. if payload_object.respond_to?(:args)
  140. job_name += " - ARGS: #{payload_object.args.inspect}"
  141. end
  142. end
  143. if reschedule
  144. action = 'Rescheduling'
  145. job.unlock
  146. job.save
  147. else
  148. action = 'Destroyed'
  149. job.destroy
  150. end
  151. logger.warn "#{action} locked delayed job: #{job_name}"
  152. end
  153. def self.start_job(job)
  154. # start job and return thread handle
  155. Thread.new do
  156. ApplicationHandleInfo.current = 'scheduler'
  157. logger.info "Started job thread for '#{job.name}' (#{job.method})..."
  158. # start loop for periods equal or under 5 minutes
  159. if job.period && job.period <= 5.minutes
  160. loop do
  161. _start_job(job)
  162. job = Scheduler.lookup(id: job.id)
  163. # exit is job got deleted
  164. break if !job
  165. # exit if job is not active anymore
  166. break if !job.active
  167. # exit if there is no loop period defined
  168. break if !job.period
  169. # wait until next run
  170. sleep job.period
  171. end
  172. else
  173. _start_job(job)
  174. end
  175. job.pid = ''
  176. job.save
  177. logger.info " ...stopped thread for '#{job.method}'"
  178. ActiveRecord::Base.connection.close
  179. # release thread lock and remove thread handle
  180. @@jobs_started.delete(job.id)
  181. end
  182. end
  183. def self._start_job(job, try_count = 0, try_run_time = Time.zone.now)
  184. job.update!(
  185. last_run: Time.zone.now,
  186. pid: Thread.current.object_id,
  187. status: 'ok',
  188. error_message: '',
  189. )
  190. logger.info "execute #{job.method} (try_count #{try_count})..."
  191. eval job.method() # rubocop:disable Security/Eval
  192. rescue => e
  193. logger.error "execute #{job.method} (try_count #{try_count}) exited with error #{e.inspect}"
  194. # reconnect in case db connection is lost
  195. begin
  196. ActiveRecord::Base.connection.reconnect!
  197. rescue => e
  198. logger.error "Can't reconnect to database #{e.inspect}"
  199. end
  200. try_run_max = 10
  201. try_count += 1
  202. # reset error counter if to old
  203. if try_run_time + (60 * 5) < Time.zone.now
  204. try_count = 0
  205. end
  206. try_run_time = Time.zone.now
  207. # restart job again
  208. if try_run_max > try_count
  209. # wait between retries (see https://github.com/zammad/zammad/issues/1950)
  210. sleep(try_count) if Rails.env.production?
  211. _start_job(job, try_count, try_run_time)
  212. else
  213. # release thread lock and remove thread handle
  214. @@jobs_started.delete(job.id)
  215. error = "Failed to run #{job.method} after #{try_count} tries #{e.inspect}"
  216. logger.error error
  217. job.update!(
  218. error_message: error,
  219. status: 'error',
  220. active: false,
  221. )
  222. end
  223. # rescue any other Exceptions that are not StandardError or childs of it
  224. # https://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby
  225. # http://rubylearning.com/satishtalim/ruby_exceptions.html
  226. rescue Exception => e # rubocop:disable Lint/RescueException
  227. logger.error "execute #{job.method} (try_count #{try_count}) exited with a non standard-error #{e.inspect}"
  228. raise
  229. end
  230. def self.worker(foreground = false)
  231. # used for tests
  232. if foreground
  233. original_interface_handle = ApplicationHandleInfo.current
  234. ApplicationHandleInfo.current = 'scheduler'
  235. original_user_id = UserInfo.current_user_id
  236. UserInfo.current_user_id = nil
  237. loop do
  238. success, failure = Delayed::Worker.new.work_off
  239. if failure.nonzero?
  240. raise "ERROR: #{failure} failed background jobs: #{Delayed::Job.where('last_error IS NOT NULL').inspect}"
  241. end
  242. break if success.zero?
  243. end
  244. UserInfo.current_user_id = original_user_id
  245. ApplicationHandleInfo.current = original_interface_handle
  246. return
  247. end
  248. # used for production
  249. wait = 8
  250. Thread.new do
  251. sleep wait
  252. logger.info "Starting worker thread #{Delayed::Job}"
  253. loop do
  254. ApplicationHandleInfo.current = 'scheduler'
  255. result = nil
  256. realtime = Benchmark.realtime do
  257. logger.debug { "*** worker thread, #{Delayed::Job.all.count} in queue" }
  258. result = Delayed::Worker.new.work_off
  259. end
  260. count = result.sum
  261. if count.zero?
  262. sleep wait
  263. logger.debug { '*** worker thread loop' }
  264. else
  265. format "*** #{count} jobs processed at %<jps>.4f j/s, %<failed>d failed ...\n", jps: count / realtime, failed: result.last
  266. end
  267. end
  268. logger.info ' ...stopped worker thread'
  269. ActiveRecord::Base.connection.close
  270. end
  271. end
  272. # This function returns a list of failed jobs
  273. #
  274. # @example
  275. # Scheduler.failed_jobs
  276. #
  277. # return [Array]
  278. def self.failed_jobs
  279. where(status: 'error', active: false)
  280. end
  281. # This function restarts failed jobs to retry them
  282. #
  283. # @example
  284. # Scheduler.restart_failed_jobs
  285. #
  286. # return [true]
  287. def self.restart_failed_jobs
  288. failed_jobs.each do |job|
  289. job.update!(active: true)
  290. end
  291. true
  292. end
  293. end