7 (ARGV.any? ? ARGV : ['--jobs', '--pipelines']).each do |arg|
10 $options[:jobs] = true
12 $options[:pipelines] = true
14 abort "Unrecognized command line option '#{arg}'"
17 if not ($options[:jobs] or $options[:pipelines])
18 abort "Nothing to do. Please specify at least one of: --jobs, --pipelines."
21 ARGV.reject! { |a| a =~ /--jobs|--pipelines/ }
25 %w{TERM INT}.each do |sig|
28 $stderr.puts "Received #{signame} signal"
33 if ENV["CRUNCH_DISPATCH_LOCKFILE"]
34 lockfilename = ENV.delete "CRUNCH_DISPATCH_LOCKFILE"
35 lockfile = File.open(lockfilename, File::RDWR|File::CREAT, 0644)
36 unless lockfile.flock File::LOCK_EX|File::LOCK_NB
37 abort "Lock unavailable on #{lockfilename} - exit"
41 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
43 require File.dirname(__FILE__) + '/../config/boot'
44 require File.dirname(__FILE__) + '/../config/environment'
48 include ApplicationHelper
51 return act_as_system_user
57 @todo = Job.queue.select(&:repository)
60 if $options[:pipelines]
61 @todo_pipelines = PipelineInstance.queue
65 def each_slurm_line(cmd, outfmt, max_fields=nil)
66 max_fields ||= outfmt.split(":").size
67 max_fields += 1 # To accommodate the node field we add
68 @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
69 if Gem::Version.new('2.3') <= @@slurm_version
70 `#{cmd} --noheader -o '%n:#{outfmt}'`.each_line do |line|
71 yield line.chomp.split(":", max_fields)
74 # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
75 # into multiple rows with one hostname each.
76 `#{cmd} --noheader -o '%N:#{outfmt}'`.each_line do |line|
77 tokens = line.chomp.split(":", max_fields)
78 if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
80 re[2].split(",").each do |range|
81 range = range.split("-").collect(&:to_i)
82 (range[0]..range[-1]).each do |n|
83 yield [re[1] + n.to_s] + tokens
95 each_slurm_line("sinfo", "%t") do |hostname, state|
96 state.sub!(/\W+$/, "")
97 state = "down" unless %w(idle alloc down).include?(state)
98 slurm_nodes[hostname] = {state: state, job: nil}
100 each_slurm_line("squeue", "%j") do |hostname, job_uuid|
101 slurm_nodes[hostname][:job] = job_uuid if slurm_nodes[hostname]
106 def update_node_status
107 return unless Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
109 slurm_status.each_pair do |hostname, slurmdata|
110 next if @node_state[hostname] == slurmdata
112 node = Node.where('hostname=?', hostname).order(:last_ping_at).last
114 $stderr.puts "dispatch: update #{hostname} state to #{slurmdata}"
115 node.info["slurm_state"] = slurmdata[:state]
116 node.job_uuid = slurmdata[:job]
118 @node_state[hostname] = slurmdata
120 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
122 elsif slurmdata[:state] != 'down'
123 $stderr.puts "dispatch: SLURM reports '#{hostname}' is not down, but no node has that name"
126 $stderr.puts "dispatch: error updating #{hostname} node status: #{error}"
131 def positive_int(raw_value, default=nil)
132 value = begin raw_value.to_i rescue 0 end
140 NODE_CONSTRAINT_MAP = {
141 # Map Job runtime_constraints keys to the corresponding Node info key.
142 'min_ram_mb_per_node' => 'total_ram_mb',
143 'min_scratch_mb_per_node' => 'total_scratch_mb',
144 'min_cores_per_node' => 'total_cpu_cores',
147 def nodes_available_for_job_now(job)
148 # Find Nodes that satisfy a Job's runtime constraints (by building
149 # a list of Procs and using them to test each Node). If there
150 # enough to run the Job, return an array of their names.
151 # Otherwise, return nil.
152 need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
154 positive_int(node.info[node_key], 0) >=
155 positive_int(job.runtime_constraints[job_key], 0)
158 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
160 Node.find_each do |node|
161 good_node = (node.info['slurm_state'] == 'idle')
162 need_procs.each { |node_test| good_node &&= node_test.call(node) }
165 if usable_nodes.count >= min_node_count
166 return usable_nodes.map { |node| node.hostname }
173 def nodes_available_for_job(job)
174 # Check if there are enough idle nodes with the Job's minimum
175 # hardware requirements to run it. If so, return an array of
176 # their names. If not, up to once per hour, signal start_jobs to
177 # hold off launching Jobs. This delay is meant to give the Node
178 # Manager an opportunity to make new resources available for new
181 # The exact timing parameters here might need to be adjusted for
182 # the best balance between helping the longest-waiting Jobs run,
183 # and making efficient use of immediately available resources.
184 # These are all just first efforts until we have more data to work
186 nodelist = nodes_available_for_job_now(job)
187 if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
188 $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
189 @node_wait_deadline = Time.now + 5.minutes
194 def fail_job job, message
195 $stderr.puts "dispatch: #{job.uuid}: #{message}"
197 Log.new(object_uuid: job.uuid,
198 event_type: 'dispatch',
199 owner_uuid: job.owner_uuid,
201 properties: {"text" => message}).save!
203 $stderr.puts "dispatch: log.create failed"
207 $stderr.puts "dispatch: job.save failed"
213 next if @running[job.uuid]
216 case Server::Application.config.crunch_job_wrapper
219 # Don't run more than one at a time.
223 when :slurm_immediate
224 nodelist = nodes_available_for_job(job)
226 if Time.now < @node_wait_deadline
232 cmd_args = ["salloc",
237 "--job-name=#{job.uuid}",
238 "--nodelist=#{nodelist.join(',')}"]
240 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
243 if Server::Application.config.crunch_job_user
244 cmd_args.unshift("sudo", "-E", "-u",
245 Server::Application.config.crunch_job_user,
246 "PATH=#{ENV['PATH']}",
247 "PERLLIB=#{ENV['PERLLIB']}",
248 "PYTHONPATH=#{ENV['PYTHONPATH']}",
249 "RUBYLIB=#{ENV['RUBYLIB']}",
250 "GEM_PATH=#{ENV['GEM_PATH']}")
253 @authorizations ||= {}
254 if @authorizations[job.uuid] and
255 @authorizations[job.uuid].user.uuid != job.modified_by_user_uuid
256 # We already made a token for this job, but we need a new one
257 # because modified_by_user_uuid has changed (the job will run
258 # as a different user).
259 @authorizations[job.uuid].update_attributes expires_at: Time.now
260 @authorizations[job.uuid] = nil
262 if not @authorizations[job.uuid]
263 auth = ApiClientAuthorization.
264 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
267 $stderr.puts "dispatch: auth.save failed"
270 @authorizations[job.uuid] = auth
273 crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
274 if crunch_job_bin == ''
275 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
278 arvados_internal = Rails.configuration.git_internal_dir
279 if not File.exists? arvados_internal
280 $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
283 git = "git --git-dir=#{arvados_internal.shellescape}"
286 if !@have_commits[job.script_version]
288 repo_root = Rails.configuration.git_repositories_dir
289 src_repo = File.join(repo_root, job.repository + '.git')
290 if not File.exists? src_repo
291 src_repo = File.join(repo_root, job.repository, '.git')
292 if not File.exists? src_repo
293 fail_job job, "No #{job.repository}.git or #{job.repository}/.git at #{repo_root}"
298 # check if the commit needs to be fetched or not
299 commit_rev = `#{git} rev-list -n1 #{job.script_version.shellescape} 2>/dev/null`.chomp
300 unless $? == 0 and commit_rev == job.script_version
301 # commit does not exist in internal repository, so import the source repository using git fetch-pack
302 cmd = "#{git} fetch-pack --no-progress --all #{src_repo.shellescape}"
304 $stderr.puts `#{cmd}`
306 fail_job job, "git fetch-pack failed"
310 @have_commits[job.script_version] = true
314 if not @have_tags[job.uuid]
315 # check if the commit needs to be tagged with this job uuid
316 tag_rev = `#{git} rev-list -n1 #{job.uuid.shellescape} 2>/dev/null`.chomp
318 # no job tag found, so create one
319 cmd = "#{git} tag #{job.uuid.shellescape} #{job.script_version.shellescape}"
321 $stderr.puts `#{cmd}`
323 fail_job job, "git tag failed"
327 # job tag found, check that it has the expected revision
328 unless tag_rev == job.script_version
329 # Uh oh, the tag doesn't point to the revision we were expecting.
330 # Someone has been monkeying with the job record and/or git.
331 fail_job job, "Existing tag #{job.uuid} points to commit #{tag_rev} but expected commit #{job.script_version}"
335 @have_tags[job.uuid] = job.script_version
336 elsif @have_tags[job.uuid] != job.script_version
337 fail_job job, "Existing tag #{job.uuid} points to commit #{@have_tags[job.uuid]} but this job uses commit #{job.script_version}"
340 cmd_args << crunch_job_bin
341 cmd_args << '--job-api-token'
342 cmd_args << @authorizations[job.uuid].api_token
345 cmd_args << '--git-dir'
346 cmd_args << arvados_internal
348 $stderr.puts "dispatch: #{cmd_args.join ' '}"
351 i, o, e, t = Open3.popen3(*cmd_args)
353 $stderr.puts "dispatch: popen3: #{$!}"
358 $stderr.puts "dispatch: job #{job.uuid}"
359 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
360 $stderr.puts start_banner
362 @running[job.uuid] = {
368 buf: {stderr: '', stdout: ''},
371 job_auth: @authorizations[job.uuid],
372 stderr_buf_to_flush: '',
373 stderr_flushed_at: Time.new(0),
376 log_throttle_is_open: true,
377 log_throttle_reset_time: Time.now + Rails.configuration.crunch_log_throttle_period,
378 log_throttle_bytes_so_far: 0,
379 log_throttle_lines_so_far: 0,
380 log_throttle_bytes_skipped: 0,
387 # Test for hard cap on total output and for log throttling. Returns whether
388 # the log line should go to output or not. Modifies "line" in place to
389 # replace it with an error if a logging limit is tripped.
390 def rate_limit running_job, line
393 if running_job[:log_throttle_is_open]
394 running_job[:log_throttle_lines_so_far] += 1
395 running_job[:log_throttle_bytes_so_far] += linesize
396 running_job[:bytes_logged] += linesize
398 if (running_job[:bytes_logged] >
399 Rails.configuration.crunch_limit_log_bytes_per_job)
400 message = "Exceeded log limit #{Rails.configuration.crunch_limit_log_bytes_per_job} bytes (crunch_limit_log_bytes_per_job). Log will be truncated."
401 running_job[:log_throttle_reset_time] = Time.now + 100.years
402 running_job[:log_throttle_is_open] = false
404 elsif (running_job[:log_throttle_bytes_so_far] >
405 Rails.configuration.crunch_log_throttle_bytes)
406 remaining_time = running_job[:log_throttle_reset_time] - Time.now
407 message = "Exceeded rate #{Rails.configuration.crunch_log_throttle_bytes} bytes per #{Rails.configuration.crunch_log_throttle_period} seconds (crunch_log_throttle_bytes). Logging will be silenced for the next #{remaining_time.round} seconds.\n"
408 running_job[:log_throttle_is_open] = false
410 elsif (running_job[:log_throttle_lines_so_far] >
411 Rails.configuration.crunch_log_throttle_lines)
412 remaining_time = running_job[:log_throttle_reset_time] - Time.now
413 message = "Exceeded rate #{Rails.configuration.crunch_log_throttle_lines} lines per #{Rails.configuration.crunch_log_throttle_period} seconds (crunch_log_throttle_lines), logging will be silenced for the next #{remaining_time.round} seconds.\n"
414 running_job[:log_throttle_is_open] = false
418 if not running_job[:log_throttle_is_open]
419 # Don't log anything if any limit has been exceeded. Just count lossage.
420 running_job[:log_throttle_bytes_skipped] += linesize
424 # Yes, write to logs, but use our "rate exceeded" message
425 # instead of the log message that exceeded the limit.
429 running_job[:log_throttle_is_open]
434 @running.each do |job_uuid, j|
438 if now > j[:log_throttle_reset_time]
439 # It has been more than throttle_period seconds since the last
440 # checkpoint so reset the throttle
441 if j[:log_throttle_bytes_skipped] > 0
442 message = "#{job_uuid} ! Skipped #{j[:log_throttle_bytes_skipped]} bytes of log"
444 j[:stderr_buf_to_flush] << "#{Time.now.ctime.to_s} #{message}\n"
447 j[:log_throttle_reset_time] = now + Rails.configuration.crunch_log_throttle_period
448 j[:log_throttle_bytes_so_far] = 0
449 j[:log_throttle_lines_so_far] = 0
450 j[:log_throttle_bytes_skipped] = 0
451 j[:log_throttle_is_open] = true
454 j[:buf].each do |stream, streambuf|
455 # Read some data from the child stream
458 # It's important to use a big enough buffer here. When we're
459 # being flooded with logs, we must read and discard many
460 # bytes at once. Otherwise, we can easily peg a CPU with
461 # time-checking and other loop overhead. (Quick tests show a
462 # 1MiB buffer working 2.5x as fast as a 64 KiB buffer.)
464 # So don't reduce this buffer size!
465 buf = j[stream].read_nonblock(2**20)
466 rescue Errno::EAGAIN, EOFError
469 # Short circuit the counting code if we're just going to throw
470 # away the data anyway.
471 if not j[:log_throttle_is_open]
472 j[:log_throttle_bytes_skipped] += streambuf.size + buf.size
479 # Append to incomplete line from previous read, if any
483 streambuf.each_line do |line|
484 if not line.end_with? $/
485 if line.size > Rails.configuration.crunch_log_throttle_bytes
486 # Without a limit here, we'll use 2x an arbitrary amount
487 # of memory, and waste a lot of time copying strings
488 # around, all without providing any feedback to anyone
489 # about what's going on _or_ hitting any of our throttle
492 # Here we leave "line" alone, knowing it will never be
493 # sent anywhere: rate_limit() will reach
494 # crunch_log_throttle_bytes immediately. However, we'll
495 # leave [...] in bufend: if the trailing end of the long
496 # line does end up getting sent anywhere, it will have
497 # some indication that it is incomplete.
500 # If line length is sane, we'll wait for the rest of the
501 # line to appear in the next read_pipes() call.
506 # rate_limit returns true or false as to whether to actually log
507 # the line or not. It also modifies "line" in place to replace
508 # it with an error if a logging limit is tripped.
509 if rate_limit j, line
510 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
512 pub_msg = "#{Time.now.ctime.to_s} #{line.strip}\n"
513 j[:stderr_buf_to_flush] << pub_msg
517 # Leave the trailing incomplete line (if any) in streambuf for
519 streambuf.replace bufend
521 # Flush buffered logs to the logs table, if appropriate. We have
522 # to do this even if we didn't collect any new logs this time:
523 # otherwise, buffered data older than seconds_between_events
524 # won't get flushed until new data arrives.
530 return if 0 == @running.size
536 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
538 j_done = @running.values.
539 select { |j| j[:wait_thr].pid == pid_done }.
542 rescue SystemCallError
543 # I have @running processes but system reports I have no
544 # children. This is likely to happen repeatedly if it happens at
545 # all; I will log this no more than once per child process I
547 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
548 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
549 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
551 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
554 @running.each do |uuid, j|
555 if j[:wait_thr].status == false
556 pid_done = j[:wait_thr].pid
564 job_done = j_done[:job]
565 $stderr.puts "dispatch: child #{pid_done} exit"
566 $stderr.puts "dispatch: job #{job_done.uuid} end"
568 # Ensure every last drop of stdout and stderr is consumed.
570 # Reset flush timestamp to make sure log gets written.
571 j_done[:stderr_flushed_at] = Time.new(0)
572 # Write any remaining logs.
575 j_done[:buf].each do |stream, streambuf|
577 $stderr.puts streambuf + "\n"
581 # Wait the thread (returns a Process::Status)
582 exit_status = j_done[:wait_thr].value.exitstatus
584 jobrecord = Job.find_by_uuid(job_done.uuid)
585 if exit_status != 75 and jobrecord.state == "Running"
586 # crunch-job did not return exit code 75 (see below) and left the job in
587 # the "Running" state, which means there was an unhandled error. Fail
589 jobrecord.state = "Failed"
590 if not jobrecord.save
591 $stderr.puts "dispatch: jobrecord.save failed"
594 # Don't fail the job if crunch-job didn't even get as far as
595 # starting it. If the job failed to run due to an infrastructure
596 # issue with crunch-job or slurm, we want the job to stay in the
597 # queue. If crunch-job exited after losing a race to another
598 # crunch-job process, it exits 75 and we should leave the job
599 # record alone so the winner of the race do its thing.
601 # There is still an unhandled race condition: If our crunch-job
602 # process is about to lose a race with another crunch-job
603 # process, but crashes before getting to its "exit 75" (for
604 # example, "cannot fork" or "cannot reach API server") then we
605 # will assume incorrectly that it's our process's fault
606 # jobrecord.started_at is non-nil, and mark the job as failed
607 # even though the winner of the race is probably still doing
611 # Invalidate the per-job auth token
612 j_done[:job_auth].update_attributes expires_at: Time.now
614 @running.delete job_done.uuid
618 expire_tokens = @pipe_auth_tokens.dup
619 @todo_pipelines.each do |p|
620 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
621 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
623 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-pipeline-here --no-wait --instance #{p.uuid}`
624 expire_tokens.delete p.uuid
627 expire_tokens.each do |k, v|
628 v.update_attributes expires_at: Time.now
629 @pipe_auth_tokens.delete k
636 @pipe_auth_tokens ||= { }
637 $stderr.puts "dispatch: ready"
638 while !$signal[:term] or @running.size > 0
641 @running.each do |uuid, j|
642 if !j[:started] and j[:sent_int] < 2
644 Process.kill 'INT', j[:wait_thr].pid
646 # No such pid = race condition + desired result is
653 refresh_todo unless did_recently(:refresh_todo, 1.0)
654 update_node_status unless did_recently(:update_node_status, 1.0)
655 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
658 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
663 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
670 def did_recently(thing, min_interval)
672 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
673 @did_recently[thing] = Time.now
680 # send message to log table. we want these records to be transient
681 def write_log running_job
682 return if running_job[:stderr_buf_to_flush] == ''
684 # Send out to log event if buffer size exceeds the bytes per event or if
685 # it has been at least crunch_log_seconds_between_events seconds since
687 if running_job[:stderr_buf_to_flush].size > Rails.configuration.crunch_log_bytes_per_event or
688 (Time.now - running_job[:stderr_flushed_at]) >= Rails.configuration.crunch_log_seconds_between_events
690 log = Log.new(object_uuid: running_job[:job].uuid,
691 event_type: 'stderr',
692 owner_uuid: running_job[:job].owner_uuid,
693 properties: {"text" => running_job[:stderr_buf_to_flush]})
695 running_job[:events_logged] += 1
697 $stderr.puts "Failed to write logs"
698 $stderr.puts exception.backtrace
700 running_job[:stderr_buf_to_flush] = ''
701 running_job[:stderr_flushed_at] = Time.now
706 # This is how crunch-job child procs know where the "refresh" trigger file is
707 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger