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