6 %w{TERM INT}.each do |sig|
9 $stderr.puts "Received #{signame} signal"
14 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
15 lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
16 lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
17 unless lockfile.flock File::LOCK_EX|File::LOCK_NB
18 abort "Lock unavailable on #{lockfilename} - exit"
22 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
24 require File.dirname(__FILE__) + '/../config/boot'
25 require File.dirname(__FILE__) + '/../config/environment'
29 LOG_BUFFER_SIZE = 2**20
32 include ApplicationHelper
35 return act_as_system_user
42 def update_node_status
43 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
44 @nodes_in_state = {idle: 0, alloc: 0, down: 0}
48 `sinfo --noheader -o '%n:%t'`.
51 re = line.match /(\S+?):+(idle|alloc|down)/
54 # sinfo tells us about a node N times if it is shared by N partitions
55 next if node_seen[re[1]]
56 node_seen[re[1]] = true
58 # count nodes in each state
59 @nodes_in_state[re[2].to_sym] += 1
61 # update our database (and cache) when a node's state changes
62 if @node_state[re[1]] != re[2]
63 @node_state[re[1]] = re[2]
64 node = Node.where('hostname=?', re[1]).first
66 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
67 node.info[:slurm_state] = re[2]
70 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
84 if job.runtime_constraints['min_nodes']
85 min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
90 next if @nodes_in_state[:idle] < min_nodes
94 next if @running[job.uuid]
98 case Server::Application.config.crunch_job_wrapper
101 when :slurm_immediate
102 cmd_args = ["salloc",
107 "--job-name=#{job.uuid}",
108 "--nodes=#{min_nodes}"]
110 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
113 if Server::Application.config.crunch_job_user
114 cmd_args.unshift("sudo", "-E", "-u",
115 Server::Application.config.crunch_job_user,
116 "PERLLIB=#{ENV['PERLLIB']}")
119 job_auth = ApiClientAuthorization.
120 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
124 cmd_args << (ENV['CRUNCH_JOB_BIN'] || `which crunch-job`.strip)
125 cmd_args << '--job-api-token'
126 cmd_args << job_auth.api_token
131 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
134 commit = Commit.where(sha1: job.script_version).first
136 cmd_args << '--git-dir'
137 if File.exists?(File.
138 join(Rails.configuration.git_repositories_dir,
139 commit.repository_name + '.git'))
141 join(Rails.configuration.git_repositories_dir,
142 commit.repository_name + '.git')
145 join(Rails.configuration.git_repositories_dir,
146 commit.repository_name, '.git')
150 $stderr.puts "dispatch: #{cmd_args.join ' '}"
153 i, o, e, t = Open3.popen3(*cmd_args)
155 $stderr.puts "dispatch: popen3: #{$!}"
161 $stderr.puts "dispatch: job #{job.uuid}"
162 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
163 $stderr.puts start_banner
164 $redis.set job.uuid, start_banner + "\n"
165 $redis.publish job.uuid, start_banner
166 $redis.publish job.owner_uuid, start_banner
168 @running[job.uuid] = {
184 # no-op -- let crunch-job take care of locking.
189 # no-op -- let crunch-job take care of locking.
194 @running.each do |job_uuid, j|
197 # Throw away child stdout
199 j[:stdout].read_nonblock(2**20)
200 rescue Errno::EAGAIN, EOFError
203 # Read whatever is available from child stderr
206 stderr_buf = j[:stderr].read_nonblock(2**20)
207 rescue Errno::EAGAIN, EOFError
211 j[:stderr_buf] << stderr_buf
212 if j[:stderr_buf].index "\n"
213 lines = j[:stderr_buf].lines("\n").to_a
214 if j[:stderr_buf][-1] == "\n"
217 j[:stderr_buf] = lines.pop
220 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
222 pub_msg = "#{Time.now.ctime.to_s} #{line.strip}"
223 $redis.publish job.owner_uuid, pub_msg
224 $redis.publish job_uuid, pub_msg
225 $redis.append job_uuid, pub_msg + "\n"
226 if LOG_BUFFER_SIZE < $redis.strlen(job_uuid)
229 .getrange(job_uuid, (LOG_BUFFER_SIZE >> 1), -1)
239 return if 0 == @running.size
245 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
247 j_done = @running.values.
248 select { |j| j[:wait_thr].pid == pid_done }.
251 rescue SystemCallError
252 # I have @running processes but system reports I have no
253 # children. This is likely to happen repeatedly if it happens at
254 # all; I will log this no more than once per child process I
256 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
257 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
258 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
260 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
263 @running.each do |uuid, j|
264 if j[:wait_thr].status == false
265 pid_done = j[:wait_thr].pid
273 job_done = j_done[:job]
274 $stderr.puts "dispatch: child #{pid_done} exit"
275 $stderr.puts "dispatch: job #{job_done.uuid} end"
276 $redis.publish job_done.uuid, "end"
278 # Ensure every last drop of stdout and stderr is consumed
280 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
281 $stderr.puts j_done[:stderr_buf] + "\n"
285 j_done[:wait_thr].value
287 # Invalidate the per-job auth token
288 j_done[:job_auth].update_attributes expires_at: Time.now
290 @running.delete job_done.uuid
296 $stderr.puts "dispatch: ready"
297 while !$signal[:term] or @running.size > 0
300 @running.each do |uuid, j|
301 if !j[:started] and j[:sent_int] < 2
303 Process.kill 'INT', j[:wait_thr].pid
305 # No such pid = race condition + desired result is
312 refresh_todo unless did_recently(:refresh_todo, 1.0)
314 start_jobs unless @todo.empty? or did_recently(:start_jobs, 1.0)
317 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
324 def did_recently(thing, min_interval)
326 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
327 @did_recently[thing] = Time.now