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