7 %w{TERM INT}.each do |sig|
10 $stderr.puts "Received #{signame} signal"
15 $stderr.puts "Received HUP signal"
19 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
20 lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
21 lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
22 unless lockfile.flock File::LOCK_EX|File::LOCK_NB
23 abort "Lock unavailable on #{lockfilename} - exit"
27 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
29 require File.dirname(__FILE__) + '/../config/boot'
30 require File.dirname(__FILE__) + '/../config/environment'
34 LOG_BUFFER_SIZE = 2**20
37 include ApplicationHelper
40 return act_as_system_user
47 def update_node_status
48 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
49 @nodes_in_state = {idle: 0, alloc: 0, down: 0}
53 `sinfo --noheader -o '%n:%t'`.
56 re = line.match /(\S+?):+(idle|alloc|down)/
59 # sinfo tells us about a node N times if it is shared by N partitions
60 next if node_seen[re[1]]
61 node_seen[re[1]] = true
63 # count nodes in each state
64 @nodes_in_state[re[2].to_sym] += 1
66 # update our database (and cache) when a node's state changes
67 if @node_state[re[1]] != re[2]
68 @node_state[re[1]] = re[2]
69 node = Node.where('hostname=?', re[1]).first
71 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
72 node.info[:slurm_state] = re[2]
75 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
89 if job.runtime_constraints['min_nodes']
90 min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
95 next if @nodes_in_state[:idle] < min_nodes
99 next if @running[job.uuid]
103 case Server::Application.config.crunch_job_wrapper
106 when :slurm_immediate
107 cmd_args = ["salloc",
112 "--job-name=#{job.uuid}",
113 "--nodes=#{min_nodes}"]
115 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
118 if Server::Application.config.crunch_job_user
119 cmd_args.unshift("sudo", "-E", "-u",
120 Server::Application.config.crunch_job_user,
121 "PERLLIB=#{ENV['PERLLIB']}")
124 job_auth = ApiClientAuthorization.
125 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
129 cmd_args << (ENV['CRUNCH_JOB_BIN'] || `which crunch-job`.strip)
130 cmd_args << '--job-api-token'
131 cmd_args << job_auth.api_token
136 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
139 commit = Commit.where(sha1: job.script_version).first
141 cmd_args << '--git-dir'
142 if File.exists?(File.
143 join(Rails.configuration.git_repositories_dir,
144 commit.repository_name + '.git'))
146 join(Rails.configuration.git_repositories_dir,
147 commit.repository_name + '.git')
150 join(Rails.configuration.git_repositories_dir,
151 commit.repository_name, '.git')
155 $stderr.puts "dispatch: #{cmd_args.join ' '}"
158 i, o, e, t = Open3.popen3(*cmd_args)
160 $stderr.puts "dispatch: popen3: #{$!}"
166 $stderr.puts "dispatch: job #{job.uuid}"
167 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
168 $stderr.puts start_banner
169 $redis.set job.uuid, start_banner + "\n"
170 $redis.publish job.uuid, start_banner
171 $redis.publish job.owner_uuid, start_banner
173 @running[job.uuid] = {
189 # no-op -- let crunch-job take care of locking.
194 # no-op -- let crunch-job take care of locking.
199 @running.each do |job_uuid, j|
202 # Throw away child stdout
204 j[:stdout].read_nonblock(2**20)
205 rescue Errno::EAGAIN, EOFError
208 # Read whatever is available from child stderr
211 stderr_buf = j[:stderr].read_nonblock(2**20)
212 rescue Errno::EAGAIN, EOFError
216 j[:stderr_buf] << stderr_buf
217 if j[:stderr_buf].index "\n"
218 lines = j[:stderr_buf].lines("\n").to_a
219 if j[:stderr_buf][-1] == "\n"
222 j[:stderr_buf] = lines.pop
225 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
227 pub_msg = "#{Time.now.ctime.to_s} #{line.strip}"
228 $redis.publish job.owner_uuid, pub_msg
229 $redis.publish job_uuid, pub_msg
230 $redis.append job_uuid, pub_msg + "\n"
231 if LOG_BUFFER_SIZE < $redis.strlen(job_uuid)
234 .getrange(job_uuid, (LOG_BUFFER_SIZE >> 1), -1)
244 return if 0 == @running.size
250 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
252 j_done = @running.values.
253 select { |j| j[:wait_thr].pid == pid_done }.
256 rescue SystemCallError
257 # I have @running processes but system reports I have no
258 # children. This is likely to happen repeatedly if it happens at
259 # all; I will log this no more than once per child process I
261 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
262 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
263 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
265 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
268 @running.each do |uuid, j|
269 if j[:wait_thr].status == false
270 pid_done = j[:wait_thr].pid
278 job_done = j_done[:job]
279 $stderr.puts "dispatch: child #{pid_done} exit"
280 $stderr.puts "dispatch: job #{job_done.uuid} end"
281 $redis.publish job_done.uuid, "end"
283 # Ensure every last drop of stdout and stderr is consumed
285 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
286 $stderr.puts j_done[:stderr_buf] + "\n"
290 j_done[:wait_thr].value
292 # Invalidate the per-job auth token
293 j_done[:job_auth].update_attributes expires_at: Time.now
295 @running.delete job_done.uuid
301 $stderr.puts "dispatch: ready"
302 while !$signal[:term] or @running.size > 0
305 @running.each do |uuid, j|
306 if !j[:started] and j[:sent_int] < 2
308 Process.kill 'INT', j[:wait_thr].pid
310 # No such pid = race condition + desired result is
317 if File.exists?(Rails.configuration.crunch_dispatch_hup_trigger)
319 File.unlink(Rails.configuration.crunch_dispatch_hup_trigger)
322 $stderr.puts "Weird, hup_trigger file was deleted by someone else."
324 if not $warned[:hup_trigger_perm]
325 $warned[:hup_trigger_perm] = true
326 $stderr.puts "Install problem: I see the hup_trigger file but cannot delete it."
331 # Pass HUP through to all crunch-job processes.
332 @running.each do |uuid, j|
334 Process.kill 'HUP', j[:wait_thr].pid
336 # Process ended but hasn't been reaped. Nothing to do.
341 refresh_todo unless did_recently(:refresh_todo, 1.0)
343 start_jobs unless @todo.empty? or did_recently(:start_jobs, 1.0)
346 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
353 def did_recently(thing, min_interval)
355 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
356 @did_recently[thing] = Time.now