store the last ~512 KiB of job log messages in a redis buffer. fixes #1589
[arvados.git] / services / api / script / crunch-dispatch.rb
1 #!/usr/bin/env ruby
2
3 include Process
4
5 $signal = {}
6 %w{TERM INT}.each do |sig|
7   signame = sig
8   Signal.trap(sig) do
9     $stderr.puts "Received #{signame} signal"
10     $signal[:term] = true
11   end
12 end
13
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"
19   end
20 end
21
22 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
23
24 require File.dirname(__FILE__) + '/../config/boot'
25 require File.dirname(__FILE__) + '/../config/environment'
26 require 'open3'
27
28 $redis ||= Redis.new
29 LOG_BUFFER_SIZE = 2**20
30
31 class Dispatcher
32   include ApplicationHelper
33
34   def sysuser
35     return act_as_system_user
36   end
37
38   def refresh_todo
39     @todo = Job.queue
40   end
41
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}
45       @node_state ||= {}
46       node_seen = {}
47       begin
48         `sinfo --noheader -o '%n:%t'`.
49           split("\n").
50           each do |line|
51           re = line.match /(\S+?):+(idle|alloc|down)/
52           next if !re
53
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
57
58           # count nodes in each state
59           @nodes_in_state[re[2].to_sym] += 1
60
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
65             if node
66               $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
67               node.info[:slurm_state] = re[2]
68               node.save
69             elsif re[2] != 'down'
70               $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
71             end
72           end
73         end
74       rescue
75       end
76     end
77   end
78
79   def start_jobs
80     @todo.each do |job|
81
82       min_nodes = 1
83       begin
84         if job.runtime_constraints['min_nodes']
85           min_nodes = begin job.runtime_constraints['min_nodes'].to_i rescue 1 end
86         end
87       end
88
89       begin
90         next if @nodes_in_state[:idle] < min_nodes
91       rescue
92       end
93
94       next if @running[job.uuid]
95       next if !take(job)
96
97       cmd_args = nil
98       case Server::Application.config.crunch_job_wrapper
99       when :none
100         cmd_args = []
101       when :slurm_immediate
102         cmd_args = ["salloc",
103                     "--chdir=/",
104                     "--immediate",
105                     "--exclusive",
106                     "--no-kill",
107                     "--job-name=#{job.uuid}",
108                     "--nodes=#{min_nodes}"]
109       else
110         raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
111       end
112
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']}")
117       end
118
119       job_auth = ApiClientAuthorization.
120         new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
121             api_client_id: 0)
122       job_auth.save
123
124       cmd_args << (ENV['CRUNCH_JOB_BIN'] || `which crunch-job`.strip)
125       cmd_args << '--job-api-token'
126       cmd_args << job_auth.api_token
127       cmd_args << '--job'
128       cmd_args << job.uuid
129
130       if cmd_args[0] == ''
131         raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
132       end
133
134       commit = Commit.where(sha1: job.script_version).first
135       if commit
136         cmd_args << '--git-dir'
137         if File.exists?(File.
138                         join(Rails.configuration.git_repositories_dir,
139                              commit.repository_name + '.git'))
140           cmd_args << File.
141             join(Rails.configuration.git_repositories_dir,
142                  commit.repository_name + '.git')
143         else
144           cmd_args << File.
145             join(Rails.configuration.git_repositories_dir,
146                  commit.repository_name, '.git')
147         end
148       end
149
150       $stderr.puts "dispatch: #{cmd_args.join ' '}"
151
152       begin
153         i, o, e, t = Open3.popen3(*cmd_args)
154       rescue
155         $stderr.puts "dispatch: popen3: #{$!}"
156         sleep 1
157         untake(job)
158         next
159       end
160
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
167       @running[job.uuid] = {
168         stdin: i,
169         stdout: o,
170         stderr: e,
171         wait_thr: t,
172         job: job,
173         stderr_buf: '',
174         started: false,
175         sent_int: 0,
176         job_auth: job_auth
177       }
178       i.close
179     end
180   end
181
182   def take(job)
183     # no-op -- let crunch-job take care of locking.
184     true
185   end
186
187   def untake(job)
188     # no-op -- let crunch-job take care of locking.
189     true
190   end
191
192   def read_pipes
193     @running.each do |job_uuid, j|
194       job = j[:job]
195
196       # Throw away child stdout
197       begin
198         j[:stdout].read_nonblock(2**20)
199       rescue Errno::EAGAIN, EOFError
200       end
201
202       # Read whatever is available from child stderr
203       stderr_buf = false
204       begin
205         stderr_buf = j[:stderr].read_nonblock(2**20)
206       rescue Errno::EAGAIN, EOFError
207       end
208
209       if stderr_buf
210         j[:stderr_buf] << stderr_buf
211         if j[:stderr_buf].index "\n"
212           lines = j[:stderr_buf].lines("\n").to_a
213           if j[:stderr_buf][-1] == "\n"
214             j[:stderr_buf] = ''
215           else
216             j[:stderr_buf] = lines.pop
217           end
218           lines.each do |line|
219             $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
220             $stderr.puts line
221             $redis.publish job_uuid, "#{Time.now.ctime.to_s} #{line.strip}"
222             $redis.append job_uuid, "#{Time.now.ctime.to_s} #{line}"
223             if LOG_BUFFER_SIZE < $redis.strlen(job_uuid)
224               $redis.set(job_uuid,
225                          $redis
226                            .getrange(job_uuid, (LOG_BUFFER_SIZE >> 1), -1)
227                            .sub(/^.*?\n/, ''))
228             end
229           end
230         end
231       end
232     end
233   end
234
235   def reap_children
236     return if 0 == @running.size
237     pid_done = nil
238     j_done = nil
239
240     if false
241       begin
242         pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
243         if pid_done
244           j_done = @running.values.
245             select { |j| j[:wait_thr].pid == pid_done }.
246             first
247         end
248       rescue SystemCallError
249         # I have @running processes but system reports I have no
250         # children. This is likely to happen repeatedly if it happens at
251         # all; I will log this no more than once per child process I
252         # start.
253         if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
254           children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
255           $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
256         end
257         @running.each do |uuid,j| j[:warned_waitpid_error] = true end
258       end
259     else
260       @running.each do |uuid, j|
261         if j[:wait_thr].status == false
262           pid_done = j[:wait_thr].pid
263           j_done = j
264         end
265       end
266     end
267
268     return if !pid_done
269
270     job_done = j_done[:job]
271     $stderr.puts "dispatch: child #{pid_done} exit"
272     $stderr.puts "dispatch: job #{job_done.uuid} end"
273     $redis.publish job_done.uuid, "end"
274
275     # Ensure every last drop of stdout and stderr is consumed
276     read_pipes
277     if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
278       $stderr.puts j_done[:stderr_buf] + "\n"
279     end
280
281     # Wait the thread
282     j_done[:wait_thr].value
283
284     # Invalidate the per-job auth token
285     j_done[:job_auth].update_attributes expires_at: Time.now
286
287     @running.delete job_done.uuid
288   end
289
290   def run
291     act_as_system_user
292     @running ||= {}
293     $stderr.puts "dispatch: ready"
294     while !$signal[:term] or @running.size > 0
295       read_pipes
296       if $signal[:term]
297         @running.each do |uuid, j|
298           if !j[:started] and j[:sent_int] < 2
299             begin
300               Process.kill 'INT', j[:wait_thr].pid
301             rescue Errno::ESRCH
302               # No such pid = race condition + desired result is
303               # already achieved
304             end
305             j[:sent_int] += 1
306           end
307         end
308       else
309         refresh_todo unless did_recently(:refresh_todo, 1.0)
310         update_node_status
311         start_jobs unless @todo.empty? or did_recently(:start_jobs, 1.0)
312       end
313       reap_children
314       select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
315              [], [], 1)
316     end
317   end
318
319   protected
320
321   def did_recently(thing, min_interval)
322     @did_recently ||= {}
323     if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
324       @did_recently[thing] = Time.now
325       false
326     else
327       true
328     end
329   end
330 end
331
332 Dispatcher.new.run