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