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