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