6 (ARGV.any? ? ARGV : ['--jobs', '--pipelines']).each do |arg|
11 $options[:pipelines] = true
13 abort "Unrecognized command line option '#{arg}'"
16 if not ($options[:jobs] or $options[:pipelines])
17 abort "Nothing to do. Please specify at least one of: --jobs, --pipelines."
20 ARGV.reject! { |a| a =~ /--jobs|--pipelines/ }
24 %w{TERM INT}.each do |sig|
27 $stderr.puts "Received #{signame} signal"
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"
40 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
42 require File.dirname(__FILE__) + '/../config/boot'
43 require File.dirname(__FILE__) + '/../config/environment'
47 include ApplicationHelper
50 return act_as_system_user
56 @todo = Job.queue.select(&:repository)
59 if $options[:pipelines]
60 @todo_pipelines = PipelineInstance.queue
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
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 ":"
87 def update_node_status
88 if Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
94 re = line.match /(\S+?):+(idle|alloc|down)?/
97 _, node_name, node_state = *re
98 node_state = 'down' unless %w(idle alloc down).include? node_state
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
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
109 $stderr.puts "dispatch: update #{node_name} state to #{node_state}"
110 node.info['slurm_state'] = node_state
112 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
114 elsif node_state != 'down'
115 $stderr.puts "dispatch: sinfo reports '#{node_name}' is not down, but no node has that name"
120 $stderr.puts "dispatch: error updating node status: #{error}"
125 def positive_int(raw_value, default=nil)
126 value = begin raw_value.to_i rescue 0 end
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',
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|
148 positive_int(node.info[node_key], 0) >=
149 positive_int(job.runtime_constraints[job_key], 0)
152 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
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) }
159 if usable_nodes.count >= min_node_count
160 return usable_nodes.map { |node| node.hostname }
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
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
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
190 next if @running[job.uuid]
193 case Server::Application.config.crunch_job_wrapper
196 # Don't run more than one at a time.
200 when :slurm_immediate
201 nodelist = nodes_available_for_job(job)
203 if Time.now < @node_wait_deadline
209 cmd_args = ["salloc",
214 "--job-name=#{job.uuid}",
215 "--nodelist=#{nodelist.join(',')}"]
217 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
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']}")
232 job_auth = ApiClientAuthorization.
233 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
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."
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`
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
253 $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
259 $stderr.puts `cd #{arvados_internal.shellescape} && git fetch-pack --all #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
261 cmd_args << crunch_job_bin
262 cmd_args << '--job-api-token'
263 cmd_args << job_auth.api_token
266 cmd_args << '--git-dir'
267 cmd_args << arvados_internal
269 $stderr.puts "dispatch: #{cmd_args.join ' '}"
272 i, o, e, t = Open3.popen3(*cmd_args)
274 $stderr.puts "dispatch: popen3: #{$!}"
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
284 @running[job.uuid] = {
294 stderr_buf_to_flush: '',
295 stderr_flushed_at: 0,
306 # no-op -- let crunch-job take care of locking.
311 # no-op -- let crunch-job take care of locking.
316 @running.each do |job_uuid, j|
319 # Throw away child stdout
321 j[:stdout].read_nonblock(2**20)
322 rescue Errno::EAGAIN, EOFError
325 # Read whatever is available from child stderr
328 stderr_buf = j[:stderr].read_nonblock(2**20)
329 rescue Errno::EAGAIN, EOFError
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"
339 j[:stderr_buf] = lines.pop
342 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
344 pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
345 j[:stderr_buf_to_flush] << pub_msg
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))
358 return if 0 == @running.size
364 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
366 j_done = @running.values.
367 select { |j| j[:wait_thr].pid == pid_done }.
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
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}"
379 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
382 @running.each do |uuid, j|
383 if j[:wait_thr].status == false
384 pid_done = j[:wait_thr].pid
392 job_done = j_done[:job]
393 $stderr.puts "dispatch: child #{pid_done} exit"
394 $stderr.puts "dispatch: job #{job_done.uuid} end"
396 # Ensure every last drop of stdout and stderr is consumed
398 write_log j_done # write any remaining logs
400 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
401 $stderr.puts j_done[:stderr_buf] + "\n"
404 # Wait the thread (returns a Process::Status)
405 exit_status = j_done[:wait_thr].value
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
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.
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
435 # Invalidate the per-job auth token
436 j_done[:job_auth].update_attributes expires_at: Time.now
438 @running.delete job_done.uuid
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,
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
451 expire_tokens.each do |k, v|
452 v.update_attributes expires_at: Time.now
453 @pipe_auth_tokens.delete k
460 @pipe_auth_tokens ||= { }
461 $stderr.puts "dispatch: ready"
462 while !$signal[:term] or @running.size > 0
465 @running.each do |uuid, j|
466 if !j[:started] and j[:sent_int] < 2
468 Process.kill 'INT', j[:wait_thr].pid
470 # No such pid = race condition + desired result is
477 refresh_todo unless did_recently(:refresh_todo, 1.0)
479 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
482 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
487 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
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)
499 def too_many_events_logged_for_job(j)
500 return (j[:events_logged] >= Rails.configuration.crunch_limit_log_events_per_job)
503 def did_recently(thing, min_interval)
505 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
506 @did_recently[thing] = Time.now
513 # send message to log table. we want these records to be transient
514 def write_log running_job
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"
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]})
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
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
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