scheduler.rb 12 KB

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