9 %w{TERM INT}.each do |sig|
12 $stderr.puts "Received #{signame} signal"
17 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
18 lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
19 lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
20 unless lockfile.flock File::LOCK_EX|File::LOCK_NB
21 abort "Lock unavailable on #{lockfilename} - exit"
25 $trollopts = Trollop::options do
26 opt :use_env, "Pass selected environment variables (PATH, PYTHONPATH, RUBYLIB, GEM_PATH, PERLLIB) to crunch-job"
29 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
31 require File.dirname(__FILE__) + '/../config/boot'
32 require File.dirname(__FILE__) + '/../config/environment'
35 LOG_BUFFER_SIZE = 4096
38 include ApplicationHelper
41 return act_as_system_user
45 @todo = Job.queue.select do |j| j.repository end
46 @todo_pipelines = PipelineInstance.queue
50 @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
51 if Gem::Version.new('2.3') <= @@slurm_version
52 `sinfo --noheader -o '%n:%t'`.strip
54 # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
55 # into multiple rows with one hostname each.
56 `sinfo --noheader -o '%N:%t'`.split("\n").collect do |line|
57 tokens = line.split ":"
58 if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
59 re[2].split(",").collect do |range|
60 range = range.split("-").collect(&:to_i)
61 (range[0]..range[-1]).collect do |n|
62 [re[1] + n.to_s, tokens[1..-1]].join ":"
72 def update_node_status
73 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
74 @nodes_in_state = {idle: 0, alloc: 0, down: 0}
80 re = line.match /(\S+?):+(idle|alloc|down)/
83 # sinfo tells us about a node N times if it is shared by N partitions
84 next if node_seen[re[1]]
85 node_seen[re[1]] = true
87 # count nodes in each state
88 @nodes_in_state[re[2].to_sym] += 1
90 # update our database (and cache) when a node's state changes
91 if @node_state[re[1]] != re[2]
92 @node_state[re[1]] = re[2]
93 node = Node.where('hostname=?', re[1]).first
95 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
96 node.info[:slurm_state] = re[2]
99 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
113 if job.runtime_constraints['min_nodes']
114 min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
119 next if @nodes_in_state[:idle] < min_nodes
123 next if @running[job.uuid]
127 case Server::Application.config.crunch_job_wrapper
130 when :slurm_immediate
131 cmd_args = ["salloc",
136 "--job-name=#{job.uuid}",
137 "--nodes=#{min_nodes}"]
139 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
142 if Server::Application.config.crunch_job_user
143 cmd_args.unshift("sudo", "-E", "-u",
144 Server::Application.config.crunch_job_user,
145 "PATH=#{ENV['PATH']}",
146 "PERLLIB=#{ENV['PERLLIB']}",
147 "PYTHONPATH=#{ENV['PYTHONPATH']}",
148 "RUBYLIB=#{ENV['RUBYLIB']}",
149 "GEM_PATH=#{ENV['GEM_PATH']}")
152 job_auth = ApiClientAuthorization.
153 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
157 crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
158 if crunch_job_bin == ''
159 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
164 arvados_internal = Rails.configuration.git_internal_dir
165 if not File.exists? arvados_internal
166 $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
169 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
170 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
173 $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
179 $stderr.puts `cd #{arvados_internal.shellescape} && git fetch --no-tags #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
181 cmd_args << crunch_job_bin
182 cmd_args << '--job-api-token'
183 cmd_args << job_auth.api_token
186 cmd_args << '--git-dir'
187 cmd_args << arvados_internal
189 $stderr.puts "dispatch: #{cmd_args}"
192 i, o, e, t = Open3.popen3({}, *cmd_args, { :unsetenv_others => true})
194 $stderr.puts "dispatch: popen3: #{$!}"
200 $stderr.puts "dispatch: job #{job.uuid}"
201 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
202 $stderr.puts start_banner
204 @running[job.uuid] = {
214 stderr_buf_to_flush: '',
222 # no-op -- let crunch-job take care of locking.
227 # no-op -- let crunch-job take care of locking.
232 @running.each do |job_uuid, j|
235 # Throw away child stdout
237 j[:stdout].read_nonblock(2**20)
238 rescue Errno::EAGAIN, EOFError
241 # Read whatever is available from child stderr
244 stderr_buf = j[:stderr].read_nonblock(2**20)
245 rescue Errno::EAGAIN, EOFError
249 j[:stderr_buf] << stderr_buf
250 if j[:stderr_buf].index "\n"
251 lines = j[:stderr_buf].lines("\n").to_a
252 if j[:stderr_buf][-1] == "\n"
255 j[:stderr_buf] = lines.pop
258 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
260 pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
261 j[:stderr_buf_to_flush] << pub_msg
264 if (LOG_BUFFER_SIZE < j[:stderr_buf_to_flush].size) || ((j[:stderr_flushed_at]+1) < Time.now.to_i)
273 return if 0 == @running.size
279 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
281 j_done = @running.values.
282 select { |j| j[:wait_thr].pid == pid_done }.
285 rescue SystemCallError
286 # I have @running processes but system reports I have no
287 # children. This is likely to happen repeatedly if it happens at
288 # all; I will log this no more than once per child process I
290 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
291 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
292 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
294 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
297 @running.each do |uuid, j|
298 if j[:wait_thr].status == false
299 pid_done = j[:wait_thr].pid
307 job_done = j_done[:job]
308 $stderr.puts "dispatch: child #{pid_done} exit"
309 $stderr.puts "dispatch: job #{job_done.uuid} end"
311 # Ensure every last drop of stdout and stderr is consumed
313 write_log j_done # write any remaining logs
315 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
316 $stderr.puts j_done[:stderr_buf] + "\n"
320 j_done[:wait_thr].value
322 jobrecord = Job.find_by_uuid(job_done.uuid)
323 if jobrecord.started_at
324 # Clean up state fields in case crunch-job exited without
325 # putting the job in a suitable "finished" state.
326 jobrecord.running = false
327 jobrecord.finished_at ||= Time.now
328 if jobrecord.success.nil?
329 jobrecord.success = false
333 # Don't fail the job if crunch-job didn't even get as far as
334 # starting it. If the job failed to run due to an infrastructure
335 # issue with crunch-job or slurm, we want the job to stay in the
339 # Invalidate the per-job auth token
340 j_done[:job_auth].update_attributes expires_at: Time.now
342 @running.delete job_done.uuid
346 expire_tokens = @pipe_auth_tokens.dup
347 @todo_pipelines.each do |p|
348 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
349 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
351 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
352 expire_tokens.delete p.uuid
355 expire_tokens.each do |k, v|
356 v.update_attributes expires_at: Time.now
357 @pipe_auth_tokens.delete k
364 @pipe_auth_tokens ||= { }
365 $stderr.puts "dispatch: ready"
366 while !$signal[:term] or @running.size > 0
369 @running.each do |uuid, j|
370 if !j[:started] and j[:sent_int] < 2
372 Process.kill 'INT', j[:wait_thr].pid
374 # No such pid = race condition + desired result is
381 refresh_todo unless did_recently(:refresh_todo, 1.0)
383 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
386 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
391 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
398 def did_recently(thing, min_interval)
400 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
401 @did_recently[thing] = Time.now
408 # send message to log table. we want these records to be transient
409 def write_log running_job
411 if (running_job && running_job[:stderr_buf_to_flush] != '')
412 log = Log.new(object_uuid: running_job[:job].uuid,
413 event_type: 'stderr',
414 owner_uuid: running_job[:job].owner_uuid,
415 properties: {"text" => running_job[:stderr_buf_to_flush]})
417 running_job[:stderr_buf_to_flush] = ''
418 running_job[:stderr_flushed_at] = Time.now.to_i
421 running_job[:stderr_buf] = "Failed to write logs \n"
422 running_job[:stderr_buf_to_flush] = ''
423 running_job[:stderr_flushed_at] = Time.now.to_i
429 # This is how crunch-job child procs know where the "refresh" trigger file is
430 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger