Merge branch 'master' into 2934-limit-crunch-logs
[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 class Dispatcher
30   include ApplicationHelper
31
32   def sysuser
33     return act_as_system_user
34   end
35
36   def refresh_todo
37     @todo = Job.queue.select do |j| j.repository end
38     @todo_pipelines = PipelineInstance.queue
39   end
40
41   def sinfo
42     @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
43     if Gem::Version.new('2.3') <= @@slurm_version
44       `sinfo --noheader -o '%n:%t'`.strip
45     else
46       # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
47       # into multiple rows with one hostname each.
48       `sinfo --noheader -o '%N:%t'`.split("\n").collect do |line|
49         tokens = line.split ":"
50         if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
51           re[2].split(",").collect do |range|
52             range = range.split("-").collect(&:to_i)
53             (range[0]..range[-1]).collect do |n|
54               [re[1] + n.to_s, tokens[1..-1]].join ":"
55             end
56           end
57         else
58           tokens.join ":"
59         end
60       end.flatten.join "\n"
61     end
62   end
63
64   def update_node_status
65     if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
66       @node_state ||= {}
67       node_seen = {}
68       begin
69         sinfo.split("\n").
70           each do |line|
71           re = line.match /(\S+?):+(idle|alloc|down)/
72           next if !re
73
74           # sinfo tells us about a node N times if it is shared by N partitions
75           next if node_seen[re[1]]
76           node_seen[re[1]] = true
77
78           # update our database (and cache) when a node's state changes
79           if @node_state[re[1]] != re[2]
80             @node_state[re[1]] = re[2]
81             node = Node.where('hostname=?', re[1]).first
82             if node
83               $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
84               node.info['slurm_state'] = re[2]
85               if not node.save
86                 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
87               end
88             elsif re[2] != 'down'
89               $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
90             end
91           end
92         end
93       rescue => error
94         $stderr.puts "dispatch: error updating node status: #{error}"
95       end
96     end
97   end
98
99   def positive_int(raw_value, default=nil)
100     value = begin raw_value.to_i rescue 0 end
101     if value > 0
102       value
103     else
104       default
105     end
106   end
107
108   NODE_CONSTRAINT_MAP = {
109     # Map Job runtime_constraints keys to the corresponding Node info key.
110     'min_ram_mb_per_node' => 'total_ram_mb',
111     'min_scratch_mb_per_node' => 'total_scratch_mb',
112     'min_cores_per_node' => 'total_cpu_cores',
113   }
114
115   def nodes_available_for_job_now(job)
116     # Find Nodes that satisfy a Job's runtime constraints (by building
117     # a list of Procs and using them to test each Node).  If there
118     # enough to run the Job, return an array of their names.
119     # Otherwise, return nil.
120     need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
121       Proc.new do |node|
122         positive_int(node.info[node_key], 0) >=
123           positive_int(job.runtime_constraints[job_key], 0)
124       end
125     end
126     min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
127     usable_nodes = []
128     Node.find_each do |node|
129       good_node = (node.info['slurm_state'] == 'idle')
130       need_procs.each { |node_test| good_node &&= node_test.call(node) }
131       if good_node
132         usable_nodes << node
133         if usable_nodes.count >= min_node_count
134           return usable_nodes.map { |node| node.hostname }
135         end
136       end
137     end
138     nil
139   end
140
141   def nodes_available_for_job(job)
142     # Check if there are enough idle nodes with the Job's minimum
143     # hardware requirements to run it.  If so, return an array of
144     # their names.  If not, up to once per hour, signal start_jobs to
145     # hold off launching Jobs.  This delay is meant to give the Node
146     # Manager an opportunity to make new resources available for new
147     # Jobs.
148     #
149     # The exact timing parameters here might need to be adjusted for
150     # the best balance between helping the longest-waiting Jobs run,
151     # and making efficient use of immediately available resources.
152     # These are all just first efforts until we have more data to work
153     # with.
154     nodelist = nodes_available_for_job_now(job)
155     if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
156       $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
157       @node_wait_deadline = Time.now + 5.minutes
158     end
159     nodelist
160   end
161
162   def start_jobs
163     @todo.each do |job|
164       next if @running[job.uuid]
165
166       cmd_args = nil
167       case Server::Application.config.crunch_job_wrapper
168       when :none
169         cmd_args = []
170       when :slurm_immediate
171         nodelist = nodes_available_for_job(job)
172         if nodelist.nil?
173           if Time.now < @node_wait_deadline
174             break
175           else
176             next
177           end
178         end
179         cmd_args = ["salloc",
180                     "--chdir=/",
181                     "--immediate",
182                     "--exclusive",
183                     "--no-kill",
184                     "--job-name=#{job.uuid}",
185                     "--nodelist=#{nodelist.join(',')}"]
186       else
187         raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
188       end
189
190       next if !take(job)
191
192       if Server::Application.config.crunch_job_user
193         cmd_args.unshift("sudo", "-E", "-u",
194                          Server::Application.config.crunch_job_user,
195                          "PATH=#{ENV['PATH']}",
196                          "PERLLIB=#{ENV['PERLLIB']}",
197                          "PYTHONPATH=#{ENV['PYTHONPATH']}",
198                          "RUBYLIB=#{ENV['RUBYLIB']}",
199                          "GEM_PATH=#{ENV['GEM_PATH']}")
200       end
201
202       job_auth = ApiClientAuthorization.
203         new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
204             api_client_id: 0)
205       job_auth.save
206
207       crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
208       if crunch_job_bin == ''
209         raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
210       end
211
212       require 'shellwords'
213
214       arvados_internal = Rails.configuration.git_internal_dir
215       if not File.exists? arvados_internal
216         $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
217       end
218
219       src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
220       src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
221
222       unless src_repo
223         $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
224         sleep 1
225         untake(job)
226         next
227       end
228
229       $stderr.puts `cd #{arvados_internal.shellescape} && git fetch --no-tags #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
230
231       cmd_args << crunch_job_bin
232       cmd_args << '--job-api-token'
233       cmd_args << job_auth.api_token
234       cmd_args << '--job'
235       cmd_args << job.uuid
236       cmd_args << '--git-dir'
237       cmd_args << arvados_internal
238
239       $stderr.puts "dispatch: #{cmd_args.join ' '}"
240
241       begin
242         i, o, e, t = Open3.popen3(*cmd_args)
243       rescue
244         $stderr.puts "dispatch: popen3: #{$!}"
245         sleep 1
246         untake(job)
247         next
248       end
249
250       $stderr.puts "dispatch: job #{job.uuid}"
251       start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
252       $stderr.puts start_banner
253
254       @running[job.uuid] = {
255         stdin: i,
256         stdout: o,
257         stderr: e,
258         wait_thr: t,
259         job: job,
260         stderr_buf: '',
261         started: false,
262         sent_int: 0,
263         job_auth: job_auth,
264         stderr_buf_to_flush: '',
265         stderr_flushed_at: 0,
266         bytes_logged: 0,
267         events_logged: 0,
268         log_truncated: false
269       }
270       i.close
271       update_node_status
272     end
273   end
274
275   def take(job)
276     # no-op -- let crunch-job take care of locking.
277     true
278   end
279
280   def untake(job)
281     # no-op -- let crunch-job take care of locking.
282     true
283   end
284
285   def read_pipes
286     @running.each do |job_uuid, j|
287       job = j[:job]
288
289       # Throw away child stdout
290       begin
291         j[:stdout].read_nonblock(2**20)
292       rescue Errno::EAGAIN, EOFError
293       end
294
295       # Read whatever is available from child stderr
296       stderr_buf = false
297       begin
298         stderr_buf = j[:stderr].read_nonblock(2**20)
299       rescue Errno::EAGAIN, EOFError
300       end
301
302       if stderr_buf
303         j[:stderr_buf] << stderr_buf
304         if j[:stderr_buf].index "\n"
305           lines = j[:stderr_buf].lines("\n").to_a
306           if j[:stderr_buf][-1] == "\n"
307             j[:stderr_buf] = ''
308           else
309             j[:stderr_buf] = lines.pop
310           end
311           lines.each do |line|
312             $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
313             $stderr.puts line
314             pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
315             j[:stderr_buf_to_flush] << pub_msg
316           end
317
318           if (Rails.configuration.crunch_log_bytes_per_event < j[:stderr_buf_to_flush].size or
319               (j[:stderr_flushed_at] + Rails.configuration.crunch_log_seconds_between_events < Time.now.to_i))
320             write_log j
321           end
322         end
323       end
324     end
325   end
326
327   def reap_children
328     return if 0 == @running.size
329     pid_done = nil
330     j_done = nil
331
332     if false
333       begin
334         pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
335         if pid_done
336           j_done = @running.values.
337             select { |j| j[:wait_thr].pid == pid_done }.
338             first
339         end
340       rescue SystemCallError
341         # I have @running processes but system reports I have no
342         # children. This is likely to happen repeatedly if it happens at
343         # all; I will log this no more than once per child process I
344         # start.
345         if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
346           children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
347           $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
348         end
349         @running.each do |uuid,j| j[:warned_waitpid_error] = true end
350       end
351     else
352       @running.each do |uuid, j|
353         if j[:wait_thr].status == false
354           pid_done = j[:wait_thr].pid
355           j_done = j
356         end
357       end
358     end
359
360     return if !pid_done
361
362     job_done = j_done[:job]
363     $stderr.puts "dispatch: child #{pid_done} exit"
364     $stderr.puts "dispatch: job #{job_done.uuid} end"
365
366     # Ensure every last drop of stdout and stderr is consumed
367     read_pipes
368     write_log j_done # write any remaining logs
369
370     if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
371       $stderr.puts j_done[:stderr_buf] + "\n"
372     end
373
374     # Wait the thread
375     j_done[:wait_thr].value
376
377     jobrecord = Job.find_by_uuid(job_done.uuid)
378     if jobrecord.started_at
379       # Clean up state fields in case crunch-job exited without
380       # putting the job in a suitable "finished" state.
381       jobrecord.running = false
382       jobrecord.finished_at ||= Time.now
383       if jobrecord.success.nil?
384         jobrecord.success = false
385       end
386       jobrecord.save!
387     else
388       # Don't fail the job if crunch-job didn't even get as far as
389       # starting it. If the job failed to run due to an infrastructure
390       # issue with crunch-job or slurm, we want the job to stay in the
391       # queue.
392     end
393
394     # Invalidate the per-job auth token
395     j_done[:job_auth].update_attributes expires_at: Time.now
396
397     @running.delete job_done.uuid
398   end
399
400   def update_pipelines
401     expire_tokens = @pipe_auth_tokens.dup
402     @todo_pipelines.each do |p|
403       pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
404                    create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
405                           api_client_id: 0))
406       puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
407       expire_tokens.delete p.uuid
408     end
409
410     expire_tokens.each do |k, v|
411       v.update_attributes expires_at: Time.now
412       @pipe_auth_tokens.delete k
413     end
414   end
415
416   def run
417     act_as_system_user
418     @running ||= {}
419     @pipe_auth_tokens ||= { }
420     $stderr.puts "dispatch: ready"
421     while !$signal[:term] or @running.size > 0
422       read_pipes
423       if $signal[:term]
424         @running.each do |uuid, j|
425           if !j[:started] and j[:sent_int] < 2
426             begin
427               Process.kill 'INT', j[:wait_thr].pid
428             rescue Errno::ESRCH
429               # No such pid = race condition + desired result is
430               # already achieved
431             end
432             j[:sent_int] += 1
433           end
434         end
435       else
436         refresh_todo unless did_recently(:refresh_todo, 1.0)
437         update_node_status
438         unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
439           start_jobs
440         end
441         unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
442           update_pipelines
443         end
444       end
445       reap_children
446       select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
447              [], [], 1)
448     end
449   end
450
451   protected
452
453   def too_many_bytes_logged_for_job(j)
454     return (j[:bytes_logged] + j[:stderr_buf_to_flush].size >
455             Rails.configuration.crunch_limit_log_event_bytes_per_job)
456   end
457
458   def too_many_events_logged_for_job(j)
459     return (j[:events_logged] >= Rails.configuration.crunch_limit_log_events_per_job)
460   end
461
462   def did_recently(thing, min_interval)
463     @did_recently ||= {}
464     if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
465       @did_recently[thing] = Time.now
466       false
467     else
468       true
469     end
470   end
471
472   # send message to log table. we want these records to be transient
473   def write_log running_job
474     begin
475       if (running_job && running_job[:stderr_buf_to_flush] != '')
476         # Truncate logs if they exceed crunch_limit_log_event_bytes_per_job
477         # or crunch_limit_log_events_per_job.
478         if (too_many_bytes_logged_for_job(running_job))
479           return if running_job[:log_truncated]
480           running_job[:log_truncated] = true
481           running_job[:stderr_buf_to_flush] =
482               "Server configured limit reached (crunch_limit_log_event_bytes_per_job: #{Rails.configuration.crunch_limit_log_event_bytes_per_job}). Subsequent logs truncated"
483         elsif (too_many_events_logged_for_job(running_job))
484           return if running_job[:log_truncated]
485           running_job[:log_truncated] = true
486           running_job[:stderr_buf_to_flush] =
487               "Server configured limit reached (crunch_limit_log_events_per_job: #{Rails.configuration.crunch_limit_log_events_per_job}). Subsequent logs truncated"
488         end
489         log = Log.new(object_uuid: running_job[:job].uuid,
490                       event_type: 'stderr',
491                       owner_uuid: running_job[:job].owner_uuid,
492                       properties: {"text" => running_job[:stderr_buf_to_flush]})
493         log.save!
494         running_job[:bytes_logged] += running_job[:stderr_buf_to_flush].size
495         running_job[:events_logged] += 1
496         running_job[:stderr_buf_to_flush] = ''
497         running_job[:stderr_flushed_at] = Time.now.to_i
498       end
499     rescue
500       running_job[:stderr_buf] = "Failed to write logs \n"
501       running_job[:stderr_buf_to_flush] = ''
502       running_job[:stderr_flushed_at] = Time.now.to_i
503     end
504   end
505
506 end
507
508 # This is how crunch-job child procs know where the "refresh" trigger file is
509 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger
510
511 Dispatcher.new.run