88840d53b69a4358e6686b7e3f99b154dd5ddc31
[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       $redis.publish job.owner_uuid, start_banner
167
168       @running[job.uuid] = {
169         stdin: i,
170         stdout: o,
171         stderr: e,
172         wait_thr: t,
173         job: job,
174         stderr_buf: '',
175         started: false,
176         sent_int: 0,
177         job_auth: job_auth
178       }
179       i.close
180     end
181   end
182
183   def take(job)
184     # no-op -- let crunch-job take care of locking.
185     true
186   end
187
188   def untake(job)
189     # no-op -- let crunch-job take care of locking.
190     true
191   end
192
193   def read_pipes
194     @running.each do |job_uuid, j|
195       job = j[:job]
196
197       # Throw away child stdout
198       begin
199         j[:stdout].read_nonblock(2**20)
200       rescue Errno::EAGAIN, EOFError
201       end
202
203       # Read whatever is available from child stderr
204       stderr_buf = false
205       begin
206         stderr_buf = j[:stderr].read_nonblock(2**20)
207       rescue Errno::EAGAIN, EOFError
208       end
209
210       if stderr_buf
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"
215             j[:stderr_buf] = ''
216           else
217             j[:stderr_buf] = lines.pop
218           end
219           lines.each do |line|
220             $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
221             $stderr.puts line
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)
227               $redis.set(job_uuid,
228                          $redis
229                            .getrange(job_uuid, (LOG_BUFFER_SIZE >> 1), -1)
230                            .sub(/^.*?\n/, ''))
231             end
232           end
233         end
234       end
235     end
236   end
237
238   def reap_children
239     return if 0 == @running.size
240     pid_done = nil
241     j_done = nil
242
243     if false
244       begin
245         pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
246         if pid_done
247           j_done = @running.values.
248             select { |j| j[:wait_thr].pid == pid_done }.
249             first
250         end
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
255         # start.
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}"
259         end
260         @running.each do |uuid,j| j[:warned_waitpid_error] = true end
261       end
262     else
263       @running.each do |uuid, j|
264         if j[:wait_thr].status == false
265           pid_done = j[:wait_thr].pid
266           j_done = j
267         end
268       end
269     end
270
271     return if !pid_done
272
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"
277
278     # Ensure every last drop of stdout and stderr is consumed
279     read_pipes
280     if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
281       $stderr.puts j_done[:stderr_buf] + "\n"
282     end
283
284     # Wait the thread
285     j_done[:wait_thr].value
286
287     # Invalidate the per-job auth token
288     j_done[:job_auth].update_attributes expires_at: Time.now
289
290     @running.delete job_done.uuid
291   end
292
293   def run
294     act_as_system_user
295     @running ||= {}
296     $stderr.puts "dispatch: ready"
297     while !$signal[:term] or @running.size > 0
298       read_pipes
299       if $signal[:term]
300         @running.each do |uuid, j|
301           if !j[:started] and j[:sent_int] < 2
302             begin
303               Process.kill 'INT', j[:wait_thr].pid
304             rescue Errno::ESRCH
305               # No such pid = race condition + desired result is
306               # already achieved
307             end
308             j[:sent_int] += 1
309           end
310         end
311       else
312         refresh_todo unless did_recently(:refresh_todo, 1.0)
313         update_node_status
314         start_jobs unless @todo.empty? or did_recently(:start_jobs, 1.0)
315       end
316       reap_children
317       select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
318              [], [], 1)
319     end
320   end
321
322   protected
323
324   def did_recently(thing, min_interval)
325     @did_recently ||= {}
326     if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
327       @did_recently[thing] = Time.now
328       false
329     else
330       true
331     end
332   end
333 end
334
335 Dispatcher.new.run