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