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