7 %w{TERM INT}.each do |sig|
10 $stderr.puts "Received #{signame} signal"
15 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
16 lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
17 lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
18 unless lockfile.flock File::LOCK_EX|File::LOCK_NB
19 abort "Lock unavailable on #{lockfilename} - exit"
23 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
25 require File.dirname(__FILE__) + '/../config/boot'
26 require File.dirname(__FILE__) + '/../config/environment'
29 LOG_BUFFER_SIZE = 4096
32 include ApplicationHelper
35 return act_as_system_user
39 @todo = Job.queue.select do |j| j.repository end
40 @todo_pipelines = PipelineInstance.queue
44 @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
45 if Gem::Version.new('2.3') <= @@slurm_version
46 `sinfo --noheader -o '%n:%t'`.strip
48 # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
49 # into multiple rows with one hostname each.
50 `sinfo --noheader -o '%N:%t'`.split("\n").collect do |line|
51 tokens = line.split ":"
52 if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
53 re[2].split(",").collect do |range|
54 range = range.split("-").collect(&:to_i)
55 (range[0]..range[-1]).collect do |n|
56 [re[1] + n.to_s, tokens[1..-1]].join ":"
66 def update_node_status
67 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
68 @nodes_in_state = {idle: 0, alloc: 0, down: 0}
74 re = line.match /(\S+?):+(idle|alloc|down)/
77 # sinfo tells us about a node N times if it is shared by N partitions
78 next if node_seen[re[1]]
79 node_seen[re[1]] = true
81 # count nodes in each state
82 @nodes_in_state[re[2].to_sym] += 1
84 # update our database (and cache) when a node's state changes
85 if @node_state[re[1]] != re[2]
86 @node_state[re[1]] = re[2]
87 node = Node.where('hostname=?', re[1]).first
89 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
90 node.info[:slurm_state] = re[2]
93 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
107 if job.runtime_constraints['min_nodes']
108 min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
113 next if @nodes_in_state[:idle] < min_nodes
117 next if @running[job.uuid]
121 case Server::Application.config.crunch_job_wrapper
124 when :slurm_immediate
125 cmd_args = ["salloc",
130 "--job-name=#{job.uuid}",
131 "--nodes=#{min_nodes}"]
133 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
136 if Server::Application.config.crunch_job_user
137 cmd_args.unshift("sudo", "-E", "-u",
138 Server::Application.config.crunch_job_user,
139 "PERLLIB=#{ENV['PERLLIB']}")
142 job_auth = ApiClientAuthorization.
143 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
147 crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
148 if crunch_job_bin == ''
149 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
154 arvados_internal = Rails.configuration.git_internal_dir
155 if not File.exists? arvados_internal
156 $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
159 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
160 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
163 $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
169 $stderr.puts `cd #{arvados_internal.shellescape} && git fetch --no-tags #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
171 cmd_args << crunch_job_bin
172 cmd_args << '--job-api-token'
173 cmd_args << job_auth.api_token
176 cmd_args << '--git-dir'
177 cmd_args << arvados_internal
179 $stderr.puts "dispatch: #{cmd_args.join ' '}"
182 i, o, e, t = Open3.popen3(*cmd_args)
184 $stderr.puts "dispatch: popen3: #{$!}"
190 $stderr.puts "dispatch: job #{job.uuid}"
191 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
192 $stderr.puts start_banner
194 @running[job.uuid] = {
204 stderr_buf_to_flush: '',
212 # no-op -- let crunch-job take care of locking.
217 # no-op -- let crunch-job take care of locking.
222 @running.each do |job_uuid, j|
225 # Throw away child stdout
227 j[:stdout].read_nonblock(2**20)
228 rescue Errno::EAGAIN, EOFError
231 # Read whatever is available from child stderr
234 stderr_buf = j[:stderr].read_nonblock(2**20)
235 rescue Errno::EAGAIN, EOFError
239 j[:stderr_buf] << stderr_buf
240 if j[:stderr_buf].index "\n"
241 lines = j[:stderr_buf].lines("\n").to_a
242 if j[:stderr_buf][-1] == "\n"
245 j[:stderr_buf] = lines.pop
248 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
250 pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
251 j[:stderr_buf_to_flush] << pub_msg
254 if (LOG_BUFFER_SIZE < j[:stderr_buf_to_flush].size) || ((j[:stderr_flushed_at]+1) < Time.now.to_i)
263 return if 0 == @running.size
269 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
271 j_done = @running.values.
272 select { |j| j[:wait_thr].pid == pid_done }.
275 rescue SystemCallError
276 # I have @running processes but system reports I have no
277 # children. This is likely to happen repeatedly if it happens at
278 # all; I will log this no more than once per child process I
280 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
281 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
282 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
284 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
287 @running.each do |uuid, j|
288 if j[:wait_thr].status == false
289 pid_done = j[:wait_thr].pid
297 job_done = j_done[:job]
298 $stderr.puts "dispatch: child #{pid_done} exit"
299 $stderr.puts "dispatch: job #{job_done.uuid} end"
301 # Ensure every last drop of stdout and stderr is consumed
303 write_log j_done # write any remaining logs
305 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
306 $stderr.puts j_done[:stderr_buf] + "\n"
310 j_done[:wait_thr].value
312 jobrecord = Job.find_by_uuid(job_done.uuid)
313 if jobrecord.started_at
314 # Clean up state fields in case crunch-job exited without
315 # putting the job in a suitable "finished" state.
316 jobrecord.running = false
317 jobrecord.finished_at ||= Time.now
318 if jobrecord.success.nil?
319 jobrecord.success = false
323 # Don't fail the job if crunch-job didn't even get as far as
324 # starting it. If the job failed to run due to an infrastructure
325 # issue with crunch-job or slurm, we want the job to stay in the
329 # Invalidate the per-job auth token
330 j_done[:job_auth].update_attributes expires_at: Time.now
332 @running.delete job_done.uuid
336 expire_tokens = @pipe_auth_tokens.dup
337 @todo_pipelines.each do |p|
338 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
339 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
341 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
342 expire_tokens.delete p.uuid
345 expire_tokens.each do |k, v|
346 v.update_attributes expires_at: Time.now
347 @pipe_auth_tokens.delete k
354 @pipe_auth_tokens ||= { }
355 $stderr.puts "dispatch: ready"
356 while !$signal[:term] or @running.size > 0
359 @running.each do |uuid, j|
360 if !j[:started] and j[:sent_int] < 2
362 Process.kill 'INT', j[:wait_thr].pid
364 # No such pid = race condition + desired result is
371 refresh_todo unless did_recently(:refresh_todo, 1.0)
373 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
376 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
381 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
388 def did_recently(thing, min_interval)
390 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
391 @did_recently[thing] = Time.now
398 # send message to log table. we want these records to be transient
399 def write_log running_job
401 if (running_job && running_job[:stderr_buf_to_flush] != '')
402 log = Log.new(object_uuid: running_job[:job].uuid,
403 event_type: 'stderr',
404 owner_uuid: running_job[:job].owner_uuid,
405 properties: {"text" => running_job[:stderr_buf_to_flush]})
407 running_job[:stderr_buf_to_flush] = ''
408 running_job[:stderr_flushed_at] = Time.now.to_i
411 running_job[:stderr_buf] = "Failed to write logs \n"
412 running_job[:stderr_buf_to_flush] = ''
413 running_job[:stderr_flushed_at] = Time.now.to_i
419 # This is how crunch-job child procs know where the "refresh" trigger file is
420 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger