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'
30 LOG_BUFFER_SIZE = 2**20
33 include ApplicationHelper
36 return act_as_system_user
43 def update_node_status
44 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
45 @nodes_in_state = {idle: 0, alloc: 0, down: 0}
49 `sinfo --noheader -o '%n:%t'`.
52 re = line.match /(\S+?):+(idle|alloc|down)/
55 # sinfo tells us about a node N times if it is shared by N partitions
56 next if node_seen[re[1]]
57 node_seen[re[1]] = true
59 # count nodes in each state
60 @nodes_in_state[re[2].to_sym] += 1
62 # update our database (and cache) when a node's state changes
63 if @node_state[re[1]] != re[2]
64 @node_state[re[1]] = re[2]
65 node = Node.where('hostname=?', re[1]).first
67 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
68 node.info[:slurm_state] = re[2]
71 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
85 if job.runtime_constraints['min_nodes']
86 min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
91 next if @nodes_in_state[:idle] < min_nodes
95 next if @running[job.uuid]
99 case Server::Application.config.crunch_job_wrapper
102 when :slurm_immediate
103 cmd_args = ["salloc",
108 "--job-name=#{job.uuid}",
109 "--nodes=#{min_nodes}"]
111 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
114 if Server::Application.config.crunch_job_user
115 cmd_args.unshift("sudo", "-E", "-u",
116 Server::Application.config.crunch_job_user,
117 "PERLLIB=#{ENV['PERLLIB']}")
120 job_auth = ApiClientAuthorization.
121 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
125 cmd_args << (ENV['CRUNCH_JOB_BIN'] || `which crunch-job`.strip)
126 cmd_args << '--job-api-token'
127 cmd_args << job_auth.api_token
132 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
135 commit = Commit.where(sha1: job.script_version).first
137 cmd_args << '--git-dir'
138 if File.exists?(File.
139 join(Rails.configuration.git_repositories_dir,
140 commit.repository_name + '.git'))
142 join(Rails.configuration.git_repositories_dir,
143 commit.repository_name + '.git')
146 join(Rails.configuration.git_repositories_dir,
147 commit.repository_name, '.git')
151 $stderr.puts "dispatch: #{cmd_args.join ' '}"
154 i, o, e, t = Open3.popen3(*cmd_args)
156 $stderr.puts "dispatch: popen3: #{$!}"
162 $stderr.puts "dispatch: job #{job.uuid}"
163 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
164 $stderr.puts start_banner
165 $redis.set job.uuid, start_banner + "\n"
166 $redis.publish job.uuid, start_banner
167 $redis.publish job.owner_uuid, start_banner
169 @running[job.uuid] = {
185 # no-op -- let crunch-job take care of locking.
190 # no-op -- let crunch-job take care of locking.
195 @running.each do |job_uuid, j|
198 # Throw away child stdout
200 j[:stdout].read_nonblock(2**20)
201 rescue Errno::EAGAIN, EOFError
204 # Read whatever is available from child stderr
207 stderr_buf = j[:stderr].read_nonblock(2**20)
208 rescue Errno::EAGAIN, EOFError
212 j[:stderr_buf] << stderr_buf
213 if j[:stderr_buf].index "\n"
214 lines = j[:stderr_buf].lines("\n").to_a
215 if j[:stderr_buf][-1] == "\n"
218 j[:stderr_buf] = lines.pop
221 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
223 pub_msg = "#{Time.now.ctime.to_s} #{line.strip}"
224 $redis.publish job.owner_uuid, pub_msg
225 $redis.publish job_uuid, pub_msg
226 $redis.append job_uuid, pub_msg + "\n"
227 if LOG_BUFFER_SIZE < $redis.strlen(job_uuid)
230 .getrange(job_uuid, (LOG_BUFFER_SIZE >> 1), -1)
240 return if 0 == @running.size
246 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
248 j_done = @running.values.
249 select { |j| j[:wait_thr].pid == pid_done }.
252 rescue SystemCallError
253 # I have @running processes but system reports I have no
254 # children. This is likely to happen repeatedly if it happens at
255 # all; I will log this no more than once per child process I
257 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
258 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
259 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
261 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
264 @running.each do |uuid, j|
265 if j[:wait_thr].status == false
266 pid_done = j[:wait_thr].pid
274 job_done = j_done[:job]
275 $stderr.puts "dispatch: child #{pid_done} exit"
276 $stderr.puts "dispatch: job #{job_done.uuid} end"
277 $redis.publish job_done.uuid, "end"
279 # Ensure every last drop of stdout and stderr is consumed
281 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
282 $stderr.puts j_done[:stderr_buf] + "\n"
286 j_done[:wait_thr].value
288 # Invalidate the per-job auth token
289 j_done[:job_auth].update_attributes expires_at: Time.now
291 @running.delete job_done.uuid
297 $stderr.puts "dispatch: ready"
298 while !$signal[:term] or @running.size > 0
301 @running.each do |uuid, j|
302 if !j[:started] and j[:sent_int] < 2
304 Process.kill 'INT', j[:wait_thr].pid
306 # No such pid = race condition + desired result is
313 refresh_todo unless did_recently(:refresh_todo, 1.0)
315 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
320 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
327 def did_recently(thing, min_interval)
329 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
330 @did_recently[thing] = Time.now
338 # This is how crunch-job child procs know where the "refresh" trigger file is
339 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger