4266: Use each_line as enumerator instead of building an array with lines.each.
[arvados.git] / services / api / script / crunch-dispatch.rb
1 #!/usr/bin/env ruby
2
3 include Process
4
5 $options = {}
6 (ARGV.any? ? ARGV : ['--jobs', '--pipelines']).each do |arg|
7   case arg
8   when '--jobs'
9     $options[:jobs] = true
10   when '--pipelines'
11     $options[:pipelines] = true
12   else
13     abort "Unrecognized command line option '#{arg}'"
14   end
15 end
16 if not ($options[:jobs] or $options[:pipelines])
17   abort "Nothing to do. Please specify at least one of: --jobs, --pipelines."
18 end
19
20 ARGV.reject! { |a| a =~ /--jobs|--pipelines/ }
21
22 $warned = {}
23 $signal = {}
24 %w{TERM INT}.each do |sig|
25   signame = sig
26   Signal.trap(sig) do
27     $stderr.puts "Received #{signame} signal"
28     $signal[:term] = true
29   end
30 end
31
32 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
33   lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
34   lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
35   unless lockfile.flock File::LOCK_EX|File::LOCK_NB
36     abort "Lock unavailable on #{lockfilename} - exit"
37   end
38 end
39
40 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
41
42 require File.dirname(__FILE__) + '/../config/boot'
43 require File.dirname(__FILE__) + '/../config/environment'
44 require 'open3'
45
46 class Dispatcher
47   include ApplicationHelper
48
49   def sysuser
50     return act_as_system_user
51   end
52
53   def refresh_todo
54     @todo = []
55     if $options[:jobs]
56       @todo = Job.queue.select(&:repository)
57     end
58     @todo_pipelines = []
59     if $options[:pipelines]
60       @todo_pipelines = PipelineInstance.queue
61     end
62   end
63
64   def each_slurm_line(cmd, outfmt, max_fields=nil)
65     max_fields ||= outfmt.split(":").size
66     max_fields += 1  # To accommodate the node field we add
67     @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
68     if Gem::Version.new('2.3') <= @@slurm_version
69       `#{cmd} --noheader -o '%n:#{outfmt}'`.each_line do |line|
70         yield line.chomp.split(":", max_fields)
71       end
72     else
73       # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
74       # into multiple rows with one hostname each.
75       `#{cmd} --noheader -o '%N:#{outfmt}'`.each_line do |line|
76         tokens = line.chomp.split(":", max_fields)
77         if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
78           tokens.shift
79           re[2].split(",").each do |range|
80             range = range.split("-").collect(&:to_i)
81             (range[0]..range[-1]).each do |n|
82               yield [re[1] + n.to_s] + tokens
83             end
84           end
85         else
86           yield tokens
87         end
88       end
89     end
90   end
91
92   def slurm_status
93     slurm_nodes = {}
94     each_slurm_line("sinfo", "%t") do |hostname, state|
95       state.sub!(/\W+$/, "")
96       state = "down" unless %w(idle alloc down).include?(state)
97       slurm_nodes[hostname] = {state: state, job: nil}
98     end
99     each_slurm_line("squeue", "%j") do |hostname, job_uuid|
100       slurm_nodes[hostname][:job] = job_uuid if slurm_nodes[hostname]
101     end
102     slurm_nodes
103   end
104
105   def update_node_status
106     return unless Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
107     @node_state ||= {}
108     slurm_status.each_pair do |hostname, slurmdata|
109       next if @node_state[hostname] == slurmdata
110       begin
111         node = Node.where('hostname=?', hostname).order(:last_ping_at).last
112         if node
113           $stderr.puts "dispatch: update #{hostname} state to #{slurmdata}"
114           node.info["slurm_state"] = slurmdata[:state]
115           node.job_uuid = slurmdata[:job]
116           if node.save
117             @node_state[hostname] = slurmdata
118           else
119             $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
120           end
121         elsif slurmdata[:state] != 'down'
122           $stderr.puts "dispatch: SLURM reports '#{hostname}' is not down, but no node has that name"
123         end
124       rescue => error
125         $stderr.puts "dispatch: error updating #{hostname} node status: #{error}"
126       end
127     end
128   end
129
130   def positive_int(raw_value, default=nil)
131     value = begin raw_value.to_i rescue 0 end
132     if value > 0
133       value
134     else
135       default
136     end
137   end
138
139   NODE_CONSTRAINT_MAP = {
140     # Map Job runtime_constraints keys to the corresponding Node info key.
141     'min_ram_mb_per_node' => 'total_ram_mb',
142     'min_scratch_mb_per_node' => 'total_scratch_mb',
143     'min_cores_per_node' => 'total_cpu_cores',
144   }
145
146   def nodes_available_for_job_now(job)
147     # Find Nodes that satisfy a Job's runtime constraints (by building
148     # a list of Procs and using them to test each Node).  If there
149     # enough to run the Job, return an array of their names.
150     # Otherwise, return nil.
151     need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
152       Proc.new do |node|
153         positive_int(node.info[node_key], 0) >=
154           positive_int(job.runtime_constraints[job_key], 0)
155       end
156     end
157     min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
158     usable_nodes = []
159     Node.find_each do |node|
160       good_node = (node.info['slurm_state'] == 'idle')
161       need_procs.each { |node_test| good_node &&= node_test.call(node) }
162       if good_node
163         usable_nodes << node
164         if usable_nodes.count >= min_node_count
165           return usable_nodes.map { |node| node.hostname }
166         end
167       end
168     end
169     nil
170   end
171
172   def nodes_available_for_job(job)
173     # Check if there are enough idle nodes with the Job's minimum
174     # hardware requirements to run it.  If so, return an array of
175     # their names.  If not, up to once per hour, signal start_jobs to
176     # hold off launching Jobs.  This delay is meant to give the Node
177     # Manager an opportunity to make new resources available for new
178     # Jobs.
179     #
180     # The exact timing parameters here might need to be adjusted for
181     # the best balance between helping the longest-waiting Jobs run,
182     # and making efficient use of immediately available resources.
183     # These are all just first efforts until we have more data to work
184     # with.
185     nodelist = nodes_available_for_job_now(job)
186     if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
187       $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
188       @node_wait_deadline = Time.now + 5.minutes
189     end
190     nodelist
191   end
192
193   def start_jobs
194     @todo.each do |job|
195       next if @running[job.uuid]
196
197       cmd_args = nil
198       case Server::Application.config.crunch_job_wrapper
199       when :none
200         if @running.size > 0
201             # Don't run more than one at a time.
202             return
203         end
204         cmd_args = []
205       when :slurm_immediate
206         nodelist = nodes_available_for_job(job)
207         if nodelist.nil?
208           if Time.now < @node_wait_deadline
209             break
210           else
211             next
212           end
213         end
214         cmd_args = ["salloc",
215                     "--chdir=/",
216                     "--immediate",
217                     "--exclusive",
218                     "--no-kill",
219                     "--job-name=#{job.uuid}",
220                     "--nodelist=#{nodelist.join(',')}"]
221       else
222         raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
223       end
224
225       if Server::Application.config.crunch_job_user
226         cmd_args.unshift("sudo", "-E", "-u",
227                          Server::Application.config.crunch_job_user,
228                          "PATH=#{ENV['PATH']}",
229                          "PERLLIB=#{ENV['PERLLIB']}",
230                          "PYTHONPATH=#{ENV['PYTHONPATH']}",
231                          "RUBYLIB=#{ENV['RUBYLIB']}",
232                          "GEM_PATH=#{ENV['GEM_PATH']}")
233       end
234
235       job_auth = ApiClientAuthorization.
236         new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
237             api_client_id: 0)
238       if not job_auth.save
239         $stderr.puts "dispatch: job_auth.save failed"
240         next
241       end
242
243       crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
244       if crunch_job_bin == ''
245         raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
246       end
247
248       require 'shellwords'
249
250       arvados_internal = Rails.configuration.git_internal_dir
251       if not File.exists? arvados_internal
252         $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
253       end
254
255       repo_root = Rails.configuration.git_repositories_dir
256       src_repo = File.join(repo_root, job.repository + '.git')
257       if not File.exists? src_repo
258         src_repo = File.join(repo_root, job.repository, '.git')
259         if not File.exists? src_repo
260           $stderr.puts "dispatch: No #{job.repository}.git or #{job.repository}/.git at #{repo_root}"
261           sleep 1
262           next
263         end
264       end
265
266       git = "git --git-dir=#{arvados_internal.shellescape}"
267
268       # check if the commit needs to be fetched or not
269       commit_rev = `#{git} rev-list -n1 #{job.script_version.shellescape} 2>/dev/null`.chomp
270       unless $? == 0 and commit_rev == job.script_version
271         # commit does not exist in internal repository, so import the source repository using git fetch-pack
272         cmd = "#{git} fetch-pack --no-progress --all #{src_repo.shellescape}"
273         $stderr.puts cmd
274         $stderr.puts `#{cmd}`
275         unless $? == 0
276           $stderr.puts "dispatch: git fetch-pack failed"
277           sleep 1
278           next
279         end
280       end
281
282       # check if the commit needs to be tagged with this job uuid
283       tag_rev = `#{git} rev-list -n1 #{job.uuid.shellescape} 2>/dev/null`.chomp
284       if $? != 0
285         # no job tag found, so create one
286         cmd = "#{git} tag #{job.uuid.shellescape} #{job.script_version.shellescape}"
287         $stderr.puts cmd
288         $stderr.puts `#{cmd}`
289         unless $? == 0
290           $stderr.puts "dispatch: git tag failed"
291           sleep 1
292           next
293         end
294       else
295         # job tag found, check that it has the expected revision
296         unless tag_rev == job.script_version
297           # Uh oh, the tag doesn't point to the revision we were expecting.
298           # Someone has been monkeying with the job record and/or git.
299           $stderr.puts "dispatch: Already a tag #{job.script_version} pointing to commit #{tag_rev} but expected commit #{job.script_version}"
300           job.state = "Failed"
301           if not job.save
302             $stderr.puts "dispatch: job.save failed"
303             next
304           end
305           next
306         end
307       end
308
309       cmd_args << crunch_job_bin
310       cmd_args << '--job-api-token'
311       cmd_args << job_auth.api_token
312       cmd_args << '--job'
313       cmd_args << job.uuid
314       cmd_args << '--git-dir'
315       cmd_args << arvados_internal
316
317       $stderr.puts "dispatch: #{cmd_args.join ' '}"
318
319       begin
320         i, o, e, t = Open3.popen3(*cmd_args)
321       rescue
322         $stderr.puts "dispatch: popen3: #{$!}"
323         sleep 1
324         next
325       end
326
327       $stderr.puts "dispatch: job #{job.uuid}"
328       start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
329       $stderr.puts start_banner
330
331       @running[job.uuid] = {
332         stdin: i,
333         stdout: o,
334         stderr: e,
335         wait_thr: t,
336         job: job,
337         buf: {stderr: '', stdout: ''},
338         started: false,
339         sent_int: 0,
340         job_auth: job_auth,
341         stderr_buf_to_flush: '',
342         stderr_flushed_at: Time.new(0),
343         bytes_logged: 0,
344         events_logged: 0,
345         log_throttle_is_open: true,
346         log_throttle_reset_time: Time.now + Rails.configuration.crunch_log_throttle_period,
347         log_throttle_bytes_so_far: 0,
348         log_throttle_lines_so_far: 0,
349         log_throttle_bytes_skipped: 0,
350       }
351       i.close
352       update_node_status
353     end
354   end
355
356   # Test for hard cap on total output and for log throttling.  Returns whether
357   # the log line should go to output or not.  Modifies "line" in place to
358   # replace it with an error if a logging limit is tripped.
359   def rate_limit running_job, line
360     message = false
361     linesize = line.size
362     if running_job[:log_throttle_is_open]
363       running_job[:log_throttle_lines_so_far] += 1
364       running_job[:log_throttle_bytes_so_far] += linesize
365       running_job[:bytes_logged] += linesize
366
367       if (running_job[:bytes_logged] >
368           Rails.configuration.crunch_limit_log_bytes_per_job)
369         message = "Exceeded log limit #{Rails.configuration.crunch_limit_log_bytes_per_job} bytes (crunch_limit_log_bytes_per_job). Log will be truncated."
370         running_job[:log_throttle_reset_time] = Time.now + 100.years
371         running_job[:log_throttle_is_open] = false
372
373       elsif (running_job[:log_throttle_bytes_so_far] >
374              Rails.configuration.crunch_log_throttle_bytes)
375         remaining_time = running_job[:log_throttle_reset_time] - Time.now
376         message = "Exceeded rate #{Rails.configuration.crunch_log_throttle_bytes} bytes per #{Rails.configuration.crunch_log_throttle_period} seconds (crunch_log_throttle_bytes). Logging will be silenced for the next #{remaining_time.round} seconds.\n"
377         running_job[:log_throttle_is_open] = false
378
379       elsif (running_job[:log_throttle_lines_so_far] >
380              Rails.configuration.crunch_log_throttle_lines)
381         remaining_time = running_job[:log_throttle_reset_time] - Time.now
382         message = "Exceeded rate #{Rails.configuration.crunch_log_throttle_lines} lines per #{Rails.configuration.crunch_log_throttle_period} seconds (crunch_log_throttle_lines), logging will be silenced for the next #{remaining_time.round} seconds.\n"
383         running_job[:log_throttle_is_open] = false
384       end
385     end
386
387     if not running_job[:log_throttle_is_open]
388       # Don't log anything if any limit has been exceeded. Just count lossage.
389       running_job[:log_throttle_bytes_skipped] += linesize
390     end
391
392     if message
393       # Yes, write to logs, but use our "rate exceeded" message
394       # instead of the log message that exceeded the limit.
395       line.replace message
396       true
397     else
398       running_job[:log_throttle_is_open]
399     end
400   end
401
402   def read_pipes
403     @running.each do |job_uuid, j|
404       job = j[:job]
405
406       now = Time.now
407       if now > j[:log_throttle_reset_time]
408         # It has been more than throttle_period seconds since the last
409         # checkpoint so reset the throttle
410         if j[:log_throttle_bytes_skipped] > 0
411           message = "#{job_uuid} ! Skipped #{j[:log_throttle_bytes_skipped]} bytes of log"
412           $stderr.puts message
413           j[:stderr_buf_to_flush] << "#{Time.now.ctime.to_s} #{message}\n"
414         end
415
416         j[:log_throttle_reset_time] = now + Rails.configuration.crunch_log_throttle_period
417         j[:log_throttle_bytes_so_far] = 0
418         j[:log_throttle_lines_so_far] = 0
419         j[:log_throttle_bytes_skipped] = 0
420         j[:log_throttle_is_open] = true
421       end
422
423       j[:buf].each do |stream, streambuf|
424         # Read some data from the child stream
425         buf = ''
426         begin
427           # It's important to use a big enough buffer here. When we're
428           # being flooded with logs, we must read and discard many
429           # bytes at once. Otherwise, we can easily peg a CPU with
430           # time-checking and other loop overhead. (Quick tests show a
431           # 1MiB buffer working 2.5x as fast as a 64 KiB buffer.)
432           #
433           # So don't reduce this buffer size!
434           buf = j[stream].read_nonblock(2**20)
435         rescue Errno::EAGAIN, EOFError
436         end
437
438         # Short circuit the counting code if we're just going to throw
439         # away the data anyway.
440         if not j[:log_throttle_is_open]
441           j[:log_throttle_bytes_skipped] += streambuf.size + buf.size
442           streambuf.replace ''
443           next
444         elsif buf == ''
445           next
446         end
447
448         # Append to incomplete line from previous read, if any
449         streambuf << buf
450
451         bufend = ''
452         streambuf.each_line do |line|
453           if not line.end_with? $/
454             if line.size > Rails.configuration.crunch_log_throttle_bytes
455               # Without a limit here, we'll use 2x an arbitrary amount
456               # of memory, and waste a lot of time copying strings
457               # around, all without providing any feedback to anyone
458               # about what's going on _or_ hitting any of our throttle
459               # limits.
460               #
461               # Here we leave "line" alone, knowing it will never be
462               # sent anywhere: rate_limit() will reach
463               # crunch_log_throttle_bytes immediately. However, we'll
464               # leave [...] in bufend: if the trailing end of the long
465               # line does end up getting sent anywhere, it will have
466               # some indication that it incomplete.
467               bufend = "[...]"
468             else
469               # If line length is sane, we'll wait for the rest of the
470               # line to appear in the next read_pipes() call.
471               bufend = line
472               break
473             end
474           end
475           # rate_limit returns true or false as to whether to actually log
476           # the line or not.  It also modifies "line" in place to replace
477           # it with an error if a logging limit is tripped.
478           if rate_limit j, line
479             $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
480             $stderr.puts line
481             pub_msg = "#{Time.now.ctime.to_s} #{line.strip}\n"
482             j[:stderr_buf_to_flush] << pub_msg
483           end
484         end
485
486         # Leave the trailing incomplete line (if any) in streambuf for
487         # next time.
488         streambuf.replace bufend
489       end
490       # Flush buffered logs to the logs table, if appropriate. We have
491       # to do this even if we didn't collect any new logs this time:
492       # otherwise, buffered data older than seconds_between_events
493       # won't get flushed until new data arrives.
494       write_log j
495     end
496   end
497
498   def reap_children
499     return if 0 == @running.size
500     pid_done = nil
501     j_done = nil
502
503     if false
504       begin
505         pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
506         if pid_done
507           j_done = @running.values.
508             select { |j| j[:wait_thr].pid == pid_done }.
509             first
510         end
511       rescue SystemCallError
512         # I have @running processes but system reports I have no
513         # children. This is likely to happen repeatedly if it happens at
514         # all; I will log this no more than once per child process I
515         # start.
516         if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
517           children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
518           $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
519         end
520         @running.each do |uuid,j| j[:warned_waitpid_error] = true end
521       end
522     else
523       @running.each do |uuid, j|
524         if j[:wait_thr].status == false
525           pid_done = j[:wait_thr].pid
526           j_done = j
527         end
528       end
529     end
530
531     return if !pid_done
532
533     job_done = j_done[:job]
534     $stderr.puts "dispatch: child #{pid_done} exit"
535     $stderr.puts "dispatch: job #{job_done.uuid} end"
536
537     # Ensure every last drop of stdout and stderr is consumed.
538     read_pipes
539     # Reset flush timestamp to make sure log gets written.
540     j_done[:stderr_flushed_at] = Time.new(0)
541     # Write any remaining logs.
542     write_log j_done
543
544     j_done[:buf].each do |stream, streambuf|
545       if streambuf != ''
546         $stderr.puts streambuf + "\n"
547       end
548     end
549
550     # Wait the thread (returns a Process::Status)
551     exit_status = j_done[:wait_thr].value.exitstatus
552
553     jobrecord = Job.find_by_uuid(job_done.uuid)
554     if exit_status != 75 and jobrecord.state == "Running"
555       # crunch-job did not return exit code 75 (see below) and left the job in
556       # the "Running" state, which means there was an unhandled error.  Fail
557       # the job.
558       jobrecord.state = "Failed"
559       if not jobrecord.save
560         $stderr.puts "dispatch: jobrecord.save failed"
561       end
562     else
563       # Don't fail the job if crunch-job didn't even get as far as
564       # starting it. If the job failed to run due to an infrastructure
565       # issue with crunch-job or slurm, we want the job to stay in the
566       # queue. If crunch-job exited after losing a race to another
567       # crunch-job process, it exits 75 and we should leave the job
568       # record alone so the winner of the race do its thing.
569       #
570       # There is still an unhandled race condition: If our crunch-job
571       # process is about to lose a race with another crunch-job
572       # process, but crashes before getting to its "exit 75" (for
573       # example, "cannot fork" or "cannot reach API server") then we
574       # will assume incorrectly that it's our process's fault
575       # jobrecord.started_at is non-nil, and mark the job as failed
576       # even though the winner of the race is probably still doing
577       # fine.
578     end
579
580     # Invalidate the per-job auth token
581     j_done[:job_auth].update_attributes expires_at: Time.now
582
583     @running.delete job_done.uuid
584   end
585
586   def update_pipelines
587     expire_tokens = @pipe_auth_tokens.dup
588     @todo_pipelines.each do |p|
589       pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
590                    create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
591                           api_client_id: 0))
592       puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-pipeline-here --no-wait --instance #{p.uuid}`
593       expire_tokens.delete p.uuid
594     end
595
596     expire_tokens.each do |k, v|
597       v.update_attributes expires_at: Time.now
598       @pipe_auth_tokens.delete k
599     end
600   end
601
602   def run
603     act_as_system_user
604     @running ||= {}
605     @pipe_auth_tokens ||= { }
606     $stderr.puts "dispatch: ready"
607     while !$signal[:term] or @running.size > 0
608       read_pipes
609       if $signal[:term]
610         @running.each do |uuid, j|
611           if !j[:started] and j[:sent_int] < 2
612             begin
613               Process.kill 'INT', j[:wait_thr].pid
614             rescue Errno::ESRCH
615               # No such pid = race condition + desired result is
616               # already achieved
617             end
618             j[:sent_int] += 1
619           end
620         end
621       else
622         refresh_todo unless did_recently(:refresh_todo, 1.0)
623         update_node_status
624         unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
625           start_jobs
626         end
627         unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
628           update_pipelines
629         end
630       end
631       reap_children
632       select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
633              [], [], 1)
634     end
635   end
636
637   protected
638
639   def did_recently(thing, min_interval)
640     @did_recently ||= {}
641     if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
642       @did_recently[thing] = Time.now
643       false
644     else
645       true
646     end
647   end
648
649   # send message to log table. we want these records to be transient
650   def write_log running_job
651     return if running_job[:stderr_buf_to_flush] == ''
652
653     # Send out to log event if buffer size exceeds the bytes per event or if
654     # it has been at least crunch_log_seconds_between_events seconds since
655     # the last flush.
656     if running_job[:stderr_buf_to_flush].size > Rails.configuration.crunch_log_bytes_per_event or
657         (Time.now - running_job[:stderr_flushed_at]) >= Rails.configuration.crunch_log_seconds_between_events
658       begin
659         log = Log.new(object_uuid: running_job[:job].uuid,
660                       event_type: 'stderr',
661                       owner_uuid: running_job[:job].owner_uuid,
662                       properties: {"text" => running_job[:stderr_buf_to_flush]})
663         log.save!
664         running_job[:events_logged] += 1
665       rescue => exception
666         $stderr.puts "Failed to write logs"
667         $stderr.puts exception.backtrace
668       end
669       running_job[:stderr_buf_to_flush] = ''
670       running_job[:stderr_flushed_at] = Time.now
671     end
672   end
673 end
674
675 # This is how crunch-job child procs know where the "refresh" trigger file is
676 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger
677
678 Dispatcher.new.run