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