Change crunch-dispatch to use "git fetch-pack --all" insted of "git fetch" to
[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         if @running.size > 0
170             # Don't run more than one at a time.
171             return
172         end
173         cmd_args = []
174       when :slurm_immediate
175         nodelist = nodes_available_for_job(job)
176         if nodelist.nil?
177           if Time.now < @node_wait_deadline
178             break
179           else
180             next
181           end
182         end
183         cmd_args = ["salloc",
184                     "--chdir=/",
185                     "--immediate",
186                     "--exclusive",
187                     "--no-kill",
188                     "--job-name=#{job.uuid}",
189                     "--nodelist=#{nodelist.join(',')}"]
190       else
191         raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
192       end
193
194       next if !take(job)
195
196       if Server::Application.config.crunch_job_user
197         cmd_args.unshift("sudo", "-E", "-u",
198                          Server::Application.config.crunch_job_user,
199                          "PATH=#{ENV['PATH']}",
200                          "PERLLIB=#{ENV['PERLLIB']}",
201                          "PYTHONPATH=#{ENV['PYTHONPATH']}",
202                          "RUBYLIB=#{ENV['RUBYLIB']}",
203                          "GEM_PATH=#{ENV['GEM_PATH']}")
204       end
205
206       job_auth = ApiClientAuthorization.
207         new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
208             api_client_id: 0)
209       job_auth.save
210
211       crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
212       if crunch_job_bin == ''
213         raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
214       end
215
216       require 'shellwords'
217
218       arvados_internal = Rails.configuration.git_internal_dir
219       if not File.exists? arvados_internal
220         $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
221       end
222
223       src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
224       src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
225
226       unless src_repo
227         $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
228         sleep 1
229         untake(job)
230         next
231       end
232
233       $stderr.puts `cd #{arvados_internal.shellescape} && git fetch-pack --all #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
234
235       cmd_args << crunch_job_bin
236       cmd_args << '--job-api-token'
237       cmd_args << job_auth.api_token
238       cmd_args << '--job'
239       cmd_args << job.uuid
240       cmd_args << '--git-dir'
241       cmd_args << arvados_internal
242
243       $stderr.puts "dispatch: #{cmd_args.join ' '}"
244
245       begin
246         i, o, e, t = Open3.popen3(*cmd_args)
247       rescue
248         $stderr.puts "dispatch: popen3: #{$!}"
249         sleep 1
250         untake(job)
251         next
252       end
253
254       $stderr.puts "dispatch: job #{job.uuid}"
255       start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
256       $stderr.puts start_banner
257
258       @running[job.uuid] = {
259         stdin: i,
260         stdout: o,
261         stderr: e,
262         wait_thr: t,
263         job: job,
264         stderr_buf: '',
265         started: false,
266         sent_int: 0,
267         job_auth: job_auth,
268         stderr_buf_to_flush: '',
269         stderr_flushed_at: 0,
270         bytes_logged: 0,
271         events_logged: 0,
272         log_truncated: false
273       }
274       i.close
275       update_node_status
276     end
277   end
278
279   def take(job)
280     # no-op -- let crunch-job take care of locking.
281     true
282   end
283
284   def untake(job)
285     # no-op -- let crunch-job take care of locking.
286     true
287   end
288
289   def read_pipes
290     @running.each do |job_uuid, j|
291       job = j[:job]
292
293       # Throw away child stdout
294       begin
295         j[:stdout].read_nonblock(2**20)
296       rescue Errno::EAGAIN, EOFError
297       end
298
299       # Read whatever is available from child stderr
300       stderr_buf = false
301       begin
302         stderr_buf = j[:stderr].read_nonblock(2**20)
303       rescue Errno::EAGAIN, EOFError
304       end
305
306       if stderr_buf
307         j[:stderr_buf] << stderr_buf
308         if j[:stderr_buf].index "\n"
309           lines = j[:stderr_buf].lines("\n").to_a
310           if j[:stderr_buf][-1] == "\n"
311             j[:stderr_buf] = ''
312           else
313             j[:stderr_buf] = lines.pop
314           end
315           lines.each do |line|
316             $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
317             $stderr.puts line
318             pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
319             j[:stderr_buf_to_flush] << pub_msg
320           end
321
322           if (Rails.configuration.crunch_log_bytes_per_event < j[:stderr_buf_to_flush].size or
323               (j[:stderr_flushed_at] + Rails.configuration.crunch_log_seconds_between_events < Time.now.to_i))
324             write_log j
325           end
326         end
327       end
328     end
329   end
330
331   def reap_children
332     return if 0 == @running.size
333     pid_done = nil
334     j_done = nil
335
336     if false
337       begin
338         pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
339         if pid_done
340           j_done = @running.values.
341             select { |j| j[:wait_thr].pid == pid_done }.
342             first
343         end
344       rescue SystemCallError
345         # I have @running processes but system reports I have no
346         # children. This is likely to happen repeatedly if it happens at
347         # all; I will log this no more than once per child process I
348         # start.
349         if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
350           children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
351           $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
352         end
353         @running.each do |uuid,j| j[:warned_waitpid_error] = true end
354       end
355     else
356       @running.each do |uuid, j|
357         if j[:wait_thr].status == false
358           pid_done = j[:wait_thr].pid
359           j_done = j
360         end
361       end
362     end
363
364     return if !pid_done
365
366     job_done = j_done[:job]
367     $stderr.puts "dispatch: child #{pid_done} exit"
368     $stderr.puts "dispatch: job #{job_done.uuid} end"
369
370     # Ensure every last drop of stdout and stderr is consumed
371     read_pipes
372     write_log j_done # write any remaining logs
373
374     if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
375       $stderr.puts j_done[:stderr_buf] + "\n"
376     end
377
378     # Wait the thread
379     j_done[:wait_thr].value
380
381     jobrecord = Job.find_by_uuid(job_done.uuid)
382     if jobrecord.started_at
383       # Clean up state fields in case crunch-job exited without
384       # putting the job in a suitable "finished" state.
385       jobrecord.running = false
386       jobrecord.finished_at ||= Time.now
387       if jobrecord.success.nil?
388         jobrecord.success = false
389       end
390       jobrecord.save!
391     else
392       # Don't fail the job if crunch-job didn't even get as far as
393       # starting it. If the job failed to run due to an infrastructure
394       # issue with crunch-job or slurm, we want the job to stay in the
395       # queue.
396     end
397
398     # Invalidate the per-job auth token
399     j_done[:job_auth].update_attributes expires_at: Time.now
400
401     @running.delete job_done.uuid
402   end
403
404   def update_pipelines
405     expire_tokens = @pipe_auth_tokens.dup
406     @todo_pipelines.each do |p|
407       pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
408                    create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
409                           api_client_id: 0))
410       puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
411       expire_tokens.delete p.uuid
412     end
413
414     expire_tokens.each do |k, v|
415       v.update_attributes expires_at: Time.now
416       @pipe_auth_tokens.delete k
417     end
418   end
419
420   def run
421     act_as_system_user
422     @running ||= {}
423     @pipe_auth_tokens ||= { }
424     $stderr.puts "dispatch: ready"
425     while !$signal[:term] or @running.size > 0
426       read_pipes
427       if $signal[:term]
428         @running.each do |uuid, j|
429           if !j[:started] and j[:sent_int] < 2
430             begin
431               Process.kill 'INT', j[:wait_thr].pid
432             rescue Errno::ESRCH
433               # No such pid = race condition + desired result is
434               # already achieved
435             end
436             j[:sent_int] += 1
437           end
438         end
439       else
440         refresh_todo unless did_recently(:refresh_todo, 1.0)
441         update_node_status
442         unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
443           start_jobs
444         end
445         unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
446           update_pipelines
447         end
448       end
449       reap_children
450       select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
451              [], [], 1)
452     end
453   end
454
455   protected
456
457   def too_many_bytes_logged_for_job(j)
458     return (j[:bytes_logged] + j[:stderr_buf_to_flush].size >
459             Rails.configuration.crunch_limit_log_event_bytes_per_job)
460   end
461
462   def too_many_events_logged_for_job(j)
463     return (j[:events_logged] >= Rails.configuration.crunch_limit_log_events_per_job)
464   end
465
466   def did_recently(thing, min_interval)
467     @did_recently ||= {}
468     if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
469       @did_recently[thing] = Time.now
470       false
471     else
472       true
473     end
474   end
475
476   # send message to log table. we want these records to be transient
477   def write_log running_job
478     begin
479       if (running_job && running_job[:stderr_buf_to_flush] != '')
480         # Truncate logs if they exceed crunch_limit_log_event_bytes_per_job
481         # or crunch_limit_log_events_per_job.
482         if (too_many_bytes_logged_for_job(running_job))
483           return if running_job[:log_truncated]
484           running_job[:log_truncated] = true
485           running_job[:stderr_buf_to_flush] =
486               "Server configured limit reached (crunch_limit_log_event_bytes_per_job: #{Rails.configuration.crunch_limit_log_event_bytes_per_job}). Subsequent logs truncated"
487         elsif (too_many_events_logged_for_job(running_job))
488           return if running_job[:log_truncated]
489           running_job[:log_truncated] = true
490           running_job[:stderr_buf_to_flush] =
491               "Server configured limit reached (crunch_limit_log_events_per_job: #{Rails.configuration.crunch_limit_log_events_per_job}). Subsequent logs truncated"
492         end
493         log = Log.new(object_uuid: running_job[:job].uuid,
494                       event_type: 'stderr',
495                       owner_uuid: running_job[:job].owner_uuid,
496                       properties: {"text" => running_job[:stderr_buf_to_flush]})
497         log.save!
498         running_job[:bytes_logged] += running_job[:stderr_buf_to_flush].size
499         running_job[:events_logged] += 1
500         running_job[:stderr_buf_to_flush] = ''
501         running_job[:stderr_flushed_at] = Time.now.to_i
502       end
503     rescue
504       running_job[:stderr_buf] = "Failed to write logs \n"
505       running_job[:stderr_buf_to_flush] = ''
506       running_job[:stderr_flushed_at] = Time.now.to_i
507     end
508   end
509
510 end
511
512 # This is how crunch-job child procs know where the "refresh" trigger file is
513 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger
514
515 Dispatcher.new.run