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