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