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