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