7 %w{TERM INT}.each do |sig|
10 $stderr.puts "Received #{signame} signal"
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"
23 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
25 require File.dirname(__FILE__) + '/../config/boot'
26 require File.dirname(__FILE__) + '/../config/environment'
30 include ApplicationHelper
33 return act_as_system_user
37 @todo = Job.queue.select do |j| j.repository end
38 @todo_pipelines = PipelineInstance.queue
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
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 ":"
64 def update_node_status
65 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
71 re = line.match /(\S+?):+(idle|alloc|down)?/
74 _, node_name, node_state = *re
75 node_state = 'down' unless %w(idle alloc down).include? node_state
77 # sinfo tells us about a node N times if it is shared by N partitions
78 next if node_seen[node_name]
79 node_seen[node_name] = true
81 # update our database (and cache) when a node's state changes
82 if @node_state[node_name] != node_state
83 @node_state[node_name] = node_state
84 node = Node.where('hostname=?', node_name).order(:last_ping_at).last
86 $stderr.puts "dispatch: update #{node_name} state to #{node_state}"
87 node.info['slurm_state'] = node_state
89 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
91 elsif node_state != 'down'
92 $stderr.puts "dispatch: sinfo reports '#{node_name}' is not down, but no node has that name"
97 $stderr.puts "dispatch: error updating node status: #{error}"
102 def positive_int(raw_value, default=nil)
103 value = begin raw_value.to_i rescue 0 end
111 NODE_CONSTRAINT_MAP = {
112 # Map Job runtime_constraints keys to the corresponding Node info key.
113 'min_ram_mb_per_node' => 'total_ram_mb',
114 'min_scratch_mb_per_node' => 'total_scratch_mb',
115 'min_cores_per_node' => 'total_cpu_cores',
118 def nodes_available_for_job_now(job)
119 # Find Nodes that satisfy a Job's runtime constraints (by building
120 # a list of Procs and using them to test each Node). If there
121 # enough to run the Job, return an array of their names.
122 # Otherwise, return nil.
123 need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
125 positive_int(node.info[node_key], 0) >=
126 positive_int(job.runtime_constraints[job_key], 0)
129 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
131 Node.find_each do |node|
132 good_node = (node.info['slurm_state'] == 'idle')
133 need_procs.each { |node_test| good_node &&= node_test.call(node) }
136 if usable_nodes.count >= min_node_count
137 return usable_nodes.map { |node| node.hostname }
144 def nodes_available_for_job(job)
145 # Check if there are enough idle nodes with the Job's minimum
146 # hardware requirements to run it. If so, return an array of
147 # their names. If not, up to once per hour, signal start_jobs to
148 # hold off launching Jobs. This delay is meant to give the Node
149 # Manager an opportunity to make new resources available for new
152 # The exact timing parameters here might need to be adjusted for
153 # the best balance between helping the longest-waiting Jobs run,
154 # and making efficient use of immediately available resources.
155 # These are all just first efforts until we have more data to work
157 nodelist = nodes_available_for_job_now(job)
158 if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
159 $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
160 @node_wait_deadline = Time.now + 5.minutes
167 next if @running[job.uuid]
170 case Server::Application.config.crunch_job_wrapper
173 # Don't run more than one at a time.
177 when :slurm_immediate
178 nodelist = nodes_available_for_job(job)
180 if Time.now < @node_wait_deadline
186 cmd_args = ["salloc",
191 "--job-name=#{job.uuid}",
192 "--nodelist=#{nodelist.join(',')}"]
194 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
199 if Server::Application.config.crunch_job_user
200 cmd_args.unshift("sudo", "-E", "-u",
201 Server::Application.config.crunch_job_user,
202 "PATH=#{ENV['PATH']}",
203 "PERLLIB=#{ENV['PERLLIB']}",
204 "PYTHONPATH=#{ENV['PYTHONPATH']}",
205 "RUBYLIB=#{ENV['RUBYLIB']}",
206 "GEM_PATH=#{ENV['GEM_PATH']}")
209 job_auth = ApiClientAuthorization.
210 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
214 crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
215 if crunch_job_bin == ''
216 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
221 arvados_internal = Rails.configuration.git_internal_dir
222 if not File.exists? arvados_internal
223 $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
226 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
227 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
230 $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
236 $stderr.puts `cd #{arvados_internal.shellescape} && git fetch-pack --all #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
238 cmd_args << crunch_job_bin
239 cmd_args << '--job-api-token'
240 cmd_args << job_auth.api_token
243 cmd_args << '--git-dir'
244 cmd_args << arvados_internal
246 $stderr.puts "dispatch: #{cmd_args.join ' '}"
249 i, o, e, t = Open3.popen3(*cmd_args)
251 $stderr.puts "dispatch: popen3: #{$!}"
257 $stderr.puts "dispatch: job #{job.uuid}"
258 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
259 $stderr.puts start_banner
261 @running[job.uuid] = {
271 stderr_buf_to_flush: '',
272 stderr_flushed_at: 0,
283 # no-op -- let crunch-job take care of locking.
288 # no-op -- let crunch-job take care of locking.
293 @running.each do |job_uuid, j|
296 # Throw away child stdout
298 j[:stdout].read_nonblock(2**20)
299 rescue Errno::EAGAIN, EOFError
302 # Read whatever is available from child stderr
305 stderr_buf = j[:stderr].read_nonblock(2**20)
306 rescue Errno::EAGAIN, EOFError
310 j[:stderr_buf] << stderr_buf
311 if j[:stderr_buf].index "\n"
312 lines = j[:stderr_buf].lines("\n").to_a
313 if j[:stderr_buf][-1] == "\n"
316 j[:stderr_buf] = lines.pop
319 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
321 pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
322 j[:stderr_buf_to_flush] << pub_msg
325 if (Rails.configuration.crunch_log_bytes_per_event < j[:stderr_buf_to_flush].size or
326 (j[:stderr_flushed_at] + Rails.configuration.crunch_log_seconds_between_events < Time.now.to_i))
335 return if 0 == @running.size
341 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
343 j_done = @running.values.
344 select { |j| j[:wait_thr].pid == pid_done }.
347 rescue SystemCallError
348 # I have @running processes but system reports I have no
349 # children. This is likely to happen repeatedly if it happens at
350 # all; I will log this no more than once per child process I
352 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
353 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
354 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
356 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
359 @running.each do |uuid, j|
360 if j[:wait_thr].status == false
361 pid_done = j[:wait_thr].pid
369 job_done = j_done[:job]
370 $stderr.puts "dispatch: child #{pid_done} exit"
371 $stderr.puts "dispatch: job #{job_done.uuid} end"
373 # Ensure every last drop of stdout and stderr is consumed
375 write_log j_done # write any remaining logs
377 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
378 $stderr.puts j_done[:stderr_buf] + "\n"
381 # Wait the thread (returns a Process::Status)
382 exit_status = j_done[:wait_thr].value
384 jobrecord = Job.find_by_uuid(job_done.uuid)
385 if exit_status.to_i != 75 and jobrecord.started_at
386 # Clean up state fields in case crunch-job exited without
387 # putting the job in a suitable "finished" state.
388 jobrecord.running = false
389 jobrecord.finished_at ||= Time.now
390 if jobrecord.success.nil?
391 jobrecord.success = false
395 # Don't fail the job if crunch-job didn't even get as far as
396 # starting it. If the job failed to run due to an infrastructure
397 # issue with crunch-job or slurm, we want the job to stay in the
398 # queue. If crunch-job exited after losing a race to another
399 # crunch-job process, it exits 75 and we should leave the job
400 # record alone so the winner of the race do its thing.
402 # There is still an unhandled race condition: If our crunch-job
403 # process is about to lose a race with another crunch-job
404 # process, but crashes before getting to its "exit 75" (for
405 # example, "cannot fork" or "cannot reach API server") then we
406 # will assume incorrectly that it's our process's fault
407 # jobrecord.started_at is non-nil, and mark the job as failed
408 # even though the winner of the race is probably still doing
412 # Invalidate the per-job auth token
413 j_done[:job_auth].update_attributes expires_at: Time.now
415 @running.delete job_done.uuid
419 expire_tokens = @pipe_auth_tokens.dup
420 @todo_pipelines.each do |p|
421 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
422 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
424 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
425 expire_tokens.delete p.uuid
428 expire_tokens.each do |k, v|
429 v.update_attributes expires_at: Time.now
430 @pipe_auth_tokens.delete k
437 @pipe_auth_tokens ||= { }
438 $stderr.puts "dispatch: ready"
439 while !$signal[:term] or @running.size > 0
442 @running.each do |uuid, j|
443 if !j[:started] and j[:sent_int] < 2
445 Process.kill 'INT', j[:wait_thr].pid
447 # No such pid = race condition + desired result is
454 refresh_todo unless did_recently(:refresh_todo, 1.0)
456 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
459 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
464 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
471 def too_many_bytes_logged_for_job(j)
472 return (j[:bytes_logged] + j[:stderr_buf_to_flush].size >
473 Rails.configuration.crunch_limit_log_event_bytes_per_job)
476 def too_many_events_logged_for_job(j)
477 return (j[:events_logged] >= Rails.configuration.crunch_limit_log_events_per_job)
480 def did_recently(thing, min_interval)
482 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
483 @did_recently[thing] = Time.now
490 # send message to log table. we want these records to be transient
491 def write_log running_job
493 if (running_job && running_job[:stderr_buf_to_flush] != '')
494 # Truncate logs if they exceed crunch_limit_log_event_bytes_per_job
495 # or crunch_limit_log_events_per_job.
496 if (too_many_bytes_logged_for_job(running_job))
497 return if running_job[:log_truncated]
498 running_job[:log_truncated] = true
499 running_job[:stderr_buf_to_flush] =
500 "Server configured limit reached (crunch_limit_log_event_bytes_per_job: #{Rails.configuration.crunch_limit_log_event_bytes_per_job}). Subsequent logs truncated"
501 elsif (too_many_events_logged_for_job(running_job))
502 return if running_job[:log_truncated]
503 running_job[:log_truncated] = true
504 running_job[:stderr_buf_to_flush] =
505 "Server configured limit reached (crunch_limit_log_events_per_job: #{Rails.configuration.crunch_limit_log_events_per_job}). Subsequent logs truncated"
507 log = Log.new(object_uuid: running_job[:job].uuid,
508 event_type: 'stderr',
509 owner_uuid: running_job[:job].owner_uuid,
510 properties: {"text" => running_job[:stderr_buf_to_flush]})
512 running_job[:bytes_logged] += running_job[:stderr_buf_to_flush].size
513 running_job[:events_logged] += 1
514 running_job[:stderr_buf_to_flush] = ''
515 running_job[:stderr_flushed_at] = Time.now.to_i
518 running_job[:stderr_buf] = "Failed to write logs \n"
519 running_job[:stderr_buf_to_flush] = ''
520 running_job[:stderr_flushed_at] = Time.now.to_i
526 # This is how crunch-job child procs know where the "refresh" trigger file is
527 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger