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