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