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