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'
49 self.utc.strftime "%Y-%m-%d_%H:%M:%S"
54 include ApplicationHelper
58 @crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
59 if @crunch_job_bin.empty?
60 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
63 @arvados_internal = Rails.configuration.git_internal_dir
64 if not File.exists? @arvados_internal
65 $stderr.puts `mkdir -p #{@arvados_internal.shellescape} && git init --bare #{@arvados_internal.shellescape}`
66 raise "No internal git repository available" unless ($? == 0)
69 @repo_root = Rails.configuration.git_repositories_dir
75 @pipe_auth_tokens = {}
82 return act_as_system_user
87 @todo = Job.queue.select(&:repository)
89 if $options[:pipelines]
90 @todo_pipelines = PipelineInstance.queue
94 def each_slurm_line(cmd, outfmt, max_fields=nil)
95 max_fields ||= outfmt.split(":").size
96 max_fields += 1 # To accommodate the node field we add
97 @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
98 if Gem::Version.new('2.3') <= @@slurm_version
99 `#{cmd} --noheader -o '%n:#{outfmt}'`.each_line do |line|
100 yield line.chomp.split(":", max_fields)
103 # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
104 # into multiple rows with one hostname each.
105 `#{cmd} --noheader -o '%N:#{outfmt}'`.each_line do |line|
106 tokens = line.chomp.split(":", max_fields)
107 if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
109 re[2].split(",").each do |range|
110 range = range.split("-").collect(&:to_i)
111 (range[0]..range[-1]).each do |n|
112 yield [re[1] + n.to_s] + tokens
124 each_slurm_line("sinfo", "%t") do |hostname, state|
125 # Treat nodes in idle* state as down, because the * means that slurm
126 # hasn't been able to communicate with it recently.
127 state.sub!(/^idle\*/, "down")
128 state.sub!(/\W+$/, "")
129 state = "down" unless %w(idle alloc down).include?(state)
130 slurm_nodes[hostname] = {state: state, job: nil}
132 each_slurm_line("squeue", "%j") do |hostname, job_uuid|
133 slurm_nodes[hostname][:job] = job_uuid if slurm_nodes[hostname]
138 def update_node_status
139 return unless Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
140 slurm_status.each_pair do |hostname, slurmdata|
141 next if @node_state[hostname] == slurmdata
143 node = Node.where('hostname=?', hostname).order(:last_ping_at).last
145 $stderr.puts "dispatch: update #{hostname} state to #{slurmdata}"
146 node.info["slurm_state"] = slurmdata[:state]
147 node.job_uuid = slurmdata[:job]
149 @node_state[hostname] = slurmdata
151 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
153 elsif slurmdata[:state] != 'down'
154 $stderr.puts "dispatch: SLURM reports '#{hostname}' is not down, but no node has that name"
157 $stderr.puts "dispatch: error updating #{hostname} node status: #{error}"
162 def positive_int(raw_value, default=nil)
163 value = begin raw_value.to_i rescue 0 end
171 NODE_CONSTRAINT_MAP = {
172 # Map Job runtime_constraints keys to the corresponding Node info key.
173 'min_ram_mb_per_node' => 'total_ram_mb',
174 'min_scratch_mb_per_node' => 'total_scratch_mb',
175 'min_cores_per_node' => 'total_cpu_cores',
178 def nodes_available_for_job_now(job)
179 # Find Nodes that satisfy a Job's runtime constraints (by building
180 # a list of Procs and using them to test each Node). If there
181 # enough to run the Job, return an array of their names.
182 # Otherwise, return nil.
183 need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
185 positive_int(node.info[node_key], 0) >=
186 positive_int(job.runtime_constraints[job_key], 0)
189 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
191 Node.find_each do |node|
192 good_node = (node.info['slurm_state'] == 'idle')
193 need_procs.each { |node_test| good_node &&= node_test.call(node) }
196 if usable_nodes.count >= min_node_count
197 return usable_nodes.map { |node| node.hostname }
204 def nodes_available_for_job(job)
205 # Check if there are enough idle nodes with the Job's minimum
206 # hardware requirements to run it. If so, return an array of
207 # their names. If not, up to once per hour, signal start_jobs to
208 # hold off launching Jobs. This delay is meant to give the Node
209 # Manager an opportunity to make new resources available for new
212 # The exact timing parameters here might need to be adjusted for
213 # the best balance between helping the longest-waiting Jobs run,
214 # and making efficient use of immediately available resources.
215 # These are all just first efforts until we have more data to work
217 nodelist = nodes_available_for_job_now(job)
218 if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
219 $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
220 @node_wait_deadline = db_current_time + 5.minutes
225 def fail_job job, message
226 $stderr.puts "dispatch: #{job.uuid}: #{message}"
228 Log.new(object_uuid: job.uuid,
229 event_type: 'dispatch',
230 owner_uuid: job.owner_uuid,
232 properties: {"text" => message}).save!
234 $stderr.puts "dispatch: log.create failed"
238 job.lock @authorizations[job.uuid].user.uuid
241 $stderr.puts "dispatch: save failed setting job #{job.uuid} to failed"
243 rescue ArvadosModel::AlreadyLockedError
244 $stderr.puts "dispatch: tried to mark job #{job.uuid} as failed but it was already locked by someone else"
248 def stdout_s(cmd_a, opts={})
249 IO.popen(cmd_a, "r", opts) do |pipe|
250 return pipe.read.chomp
255 ["git", "--git-dir=#{@arvados_internal}"] + cmd_a
258 def get_authorization(job)
259 if @authorizations[job.uuid] and
260 @authorizations[job.uuid].user.uuid != job.modified_by_user_uuid
261 # We already made a token for this job, but we need a new one
262 # because modified_by_user_uuid has changed (the job will run
263 # as a different user).
264 @authorizations[job.uuid].update_attributes expires_at: db_current_time
265 @authorizations[job.uuid] = nil
267 if not @authorizations[job.uuid]
268 auth = ApiClientAuthorization.
269 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
272 $stderr.puts "dispatch: auth.save failed for #{job.uuid}"
274 @authorizations[job.uuid] = auth
277 @authorizations[job.uuid]
280 def get_commit(repo_name, commit_hash)
281 # @fetched_commits[V]==true if we know commit V exists in the
282 # arvados_internal git repository.
283 if !@fetched_commits[commit_hash]
284 src_repo = File.join(@repo_root, "#{repo_name}.git")
285 if not File.exists? src_repo
286 src_repo = File.join(@repo_root, repo_name, '.git')
287 if not File.exists? src_repo
288 fail_job job, "No #{repo_name}.git or #{repo_name}/.git at #{@repo_root}"
293 # check if the commit needs to be fetched or not
294 commit_rev = stdout_s(git_cmd("rev-list", "-n1", commit_hash),
296 unless $? == 0 and commit_rev == commit_hash
297 # commit does not exist in internal repository, so import the source repository using git fetch-pack
298 cmd = git_cmd("fetch-pack", "--no-progress", "--all", src_repo)
299 $stderr.puts "dispatch: #{cmd}"
300 $stderr.puts(stdout_s(cmd))
302 fail_job job, "git fetch-pack failed"
306 @fetched_commits[commit_hash] = true
308 @fetched_commits[commit_hash]
311 def tag_commit(commit_hash, tag_name)
312 # @git_tags[T]==V if we know commit V has been tagged T in the
313 # arvados_internal repository.
314 if not @git_tags[tag_name]
315 cmd = git_cmd("tag", tag_name, commit_hash)
316 $stderr.puts "dispatch: #{cmd}"
317 $stderr.puts(stdout_s(cmd, err: "/dev/null"))
319 # git tag failed. This may be because the tag already exists, so check for that.
320 tag_rev = stdout_s(git_cmd("rev-list", "-n1", tag_name))
322 # We got a revision back
323 if tag_rev != commit_hash
324 # Uh oh, the tag doesn't point to the revision we were expecting.
325 # Someone has been monkeying with the job record and/or git.
326 fail_job job, "Existing tag #{tag_name} points to commit #{tag_rev} but expected commit #{commit_hash}"
329 # we're okay (fall through to setting @git_tags below)
331 # git rev-list failed for some reason.
332 fail_job job, "'git tag' for #{tag_name} failed but did not find any existing tag using 'git rev-list'"
336 # 'git tag' was successful, or there is an existing tag that points to the same revision.
337 @git_tags[tag_name] = commit_hash
338 elsif @git_tags[tag_name] != commit_hash
339 fail_job job, "Existing tag #{tag_name} points to commit #{@git_tags[tag_name]} but this job uses commit #{commit_hash}"
347 next if @running[job.uuid]
350 case Server::Application.config.crunch_job_wrapper
353 # Don't run more than one at a time.
357 when :slurm_immediate
358 nodelist = nodes_available_for_job(job)
360 if db_current_time < @node_wait_deadline
366 cmd_args = ["salloc",
371 "--job-name=#{job.uuid}",
372 "--nodelist=#{nodelist.join(',')}"]
374 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
377 if Server::Application.config.crunch_job_user
378 cmd_args.unshift("sudo", "-E", "-u",
379 Server::Application.config.crunch_job_user,
380 "PATH=#{ENV['PATH']}",
381 "PERLLIB=#{ENV['PERLLIB']}",
382 "PYTHONPATH=#{ENV['PYTHONPATH']}",
383 "RUBYLIB=#{ENV['RUBYLIB']}",
384 "GEM_PATH=#{ENV['GEM_PATH']}")
387 ready = (get_authorization(job) and
388 get_commit(job.repository, job.script_version) and
389 tag_commit(job.script_version, job.uuid))
390 if ready and job.arvados_sdk_version
391 ready = (get_commit("arvados", job.arvados_sdk_version) and
392 tag_commit(job.arvados_sdk_version, "#{job.uuid}-arvados-sdk"))
396 cmd_args += [@crunch_job_bin,
397 '--job-api-token', @authorizations[job.uuid].api_token,
399 '--git-dir', @arvados_internal]
401 $stderr.puts "dispatch: #{cmd_args.join ' '}"
404 i, o, e, t = Open3.popen3(*cmd_args)
406 $stderr.puts "dispatch: popen3: #{$!}"
411 $stderr.puts "dispatch: job #{job.uuid}"
412 start_banner = "dispatch: child #{t.pid} start #{LogTime.now}"
413 $stderr.puts start_banner
415 @running[job.uuid] = {
421 buf: {stderr: '', stdout: ''},
424 job_auth: @authorizations[job.uuid],
425 stderr_buf_to_flush: '',
426 stderr_flushed_at: Time.new(0),
429 log_throttle_is_open: true,
430 log_throttle_reset_time: db_current_time + Rails.configuration.crunch_log_throttle_period,
431 log_throttle_bytes_so_far: 0,
432 log_throttle_lines_so_far: 0,
433 log_throttle_bytes_skipped: 0,
440 # Test for hard cap on total output and for log throttling. Returns whether
441 # the log line should go to output or not. Modifies "line" in place to
442 # replace it with an error if a logging limit is tripped.
443 def rate_limit running_job, line
446 if running_job[:log_throttle_is_open]
447 running_job[:log_throttle_lines_so_far] += 1
448 running_job[:log_throttle_bytes_so_far] += linesize
449 running_job[:bytes_logged] += linesize
451 if (running_job[:bytes_logged] >
452 Rails.configuration.crunch_limit_log_bytes_per_job)
453 message = "Exceeded log limit #{Rails.configuration.crunch_limit_log_bytes_per_job} bytes (crunch_limit_log_bytes_per_job). Log will be truncated."
454 running_job[:log_throttle_reset_time] = db_current_time + 100.years
455 running_job[:log_throttle_is_open] = false
457 elsif (running_job[:log_throttle_bytes_so_far] >
458 Rails.configuration.crunch_log_throttle_bytes)
459 remaining_time = running_job[:log_throttle_reset_time] - db_current_time
460 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"
461 running_job[:log_throttle_is_open] = false
463 elsif (running_job[:log_throttle_lines_so_far] >
464 Rails.configuration.crunch_log_throttle_lines)
465 remaining_time = running_job[:log_throttle_reset_time] - db_current_time
466 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"
467 running_job[:log_throttle_is_open] = false
471 if not running_job[:log_throttle_is_open]
472 # Don't log anything if any limit has been exceeded. Just count lossage.
473 running_job[:log_throttle_bytes_skipped] += linesize
477 # Yes, write to logs, but use our "rate exceeded" message
478 # instead of the log message that exceeded the limit.
482 running_job[:log_throttle_is_open]
487 @running.each do |job_uuid, j|
490 now = db_current_time
491 if now > j[:log_throttle_reset_time]
492 # It has been more than throttle_period seconds since the last
493 # checkpoint so reset the throttle
494 if j[:log_throttle_bytes_skipped] > 0
495 message = "#{job_uuid} ! Skipped #{j[:log_throttle_bytes_skipped]} bytes of log"
497 j[:stderr_buf_to_flush] << "#{LogTime.now} #{message}\n"
500 j[:log_throttle_reset_time] = now + Rails.configuration.crunch_log_throttle_period
501 j[:log_throttle_bytes_so_far] = 0
502 j[:log_throttle_lines_so_far] = 0
503 j[:log_throttle_bytes_skipped] = 0
504 j[:log_throttle_is_open] = true
507 j[:buf].each do |stream, streambuf|
508 # Read some data from the child stream
511 # It's important to use a big enough buffer here. When we're
512 # being flooded with logs, we must read and discard many
513 # bytes at once. Otherwise, we can easily peg a CPU with
514 # time-checking and other loop overhead. (Quick tests show a
515 # 1MiB buffer working 2.5x as fast as a 64 KiB buffer.)
517 # So don't reduce this buffer size!
518 buf = j[stream].read_nonblock(2**20)
519 rescue Errno::EAGAIN, EOFError
522 # Short circuit the counting code if we're just going to throw
523 # away the data anyway.
524 if not j[:log_throttle_is_open]
525 j[:log_throttle_bytes_skipped] += streambuf.size + buf.size
532 # Append to incomplete line from previous read, if any
536 streambuf.each_line do |line|
537 if not line.end_with? $/
538 if line.size > Rails.configuration.crunch_log_throttle_bytes
539 # Without a limit here, we'll use 2x an arbitrary amount
540 # of memory, and waste a lot of time copying strings
541 # around, all without providing any feedback to anyone
542 # about what's going on _or_ hitting any of our throttle
545 # Here we leave "line" alone, knowing it will never be
546 # sent anywhere: rate_limit() will reach
547 # crunch_log_throttle_bytes immediately. However, we'll
548 # leave [...] in bufend: if the trailing end of the long
549 # line does end up getting sent anywhere, it will have
550 # some indication that it is incomplete.
553 # If line length is sane, we'll wait for the rest of the
554 # line to appear in the next read_pipes() call.
559 # rate_limit returns true or false as to whether to actually log
560 # the line or not. It also modifies "line" in place to replace
561 # it with an error if a logging limit is tripped.
562 if rate_limit j, line
563 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
565 pub_msg = "#{LogTime.now} #{line.strip}\n"
566 j[:stderr_buf_to_flush] << pub_msg
570 # Leave the trailing incomplete line (if any) in streambuf for
572 streambuf.replace bufend
574 # Flush buffered logs to the logs table, if appropriate. We have
575 # to do this even if we didn't collect any new logs this time:
576 # otherwise, buffered data older than seconds_between_events
577 # won't get flushed until new data arrives.
583 return if 0 == @running.size
589 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
591 j_done = @running.values.
592 select { |j| j[:wait_thr].pid == pid_done }.
595 rescue SystemCallError
596 # I have @running processes but system reports I have no
597 # children. This is likely to happen repeatedly if it happens at
598 # all; I will log this no more than once per child process I
600 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
601 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
602 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
604 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
607 @running.each do |uuid, j|
608 if j[:wait_thr].status == false
609 pid_done = j[:wait_thr].pid
617 job_done = j_done[:job]
618 $stderr.puts "dispatch: child #{pid_done} exit"
619 $stderr.puts "dispatch: job #{job_done.uuid} end"
621 # Ensure every last drop of stdout and stderr is consumed.
623 # Reset flush timestamp to make sure log gets written.
624 j_done[:stderr_flushed_at] = Time.new(0)
625 # Write any remaining logs.
628 j_done[:buf].each do |stream, streambuf|
630 $stderr.puts streambuf + "\n"
634 # Wait the thread (returns a Process::Status)
635 exit_status = j_done[:wait_thr].value.exitstatus
637 jobrecord = Job.find_by_uuid(job_done.uuid)
638 if exit_status != 75 and jobrecord.state == "Running"
639 # crunch-job did not return exit code 75 (see below) and left the job in
640 # the "Running" state, which means there was an unhandled error. Fail
642 jobrecord.state = "Failed"
643 if not jobrecord.save
644 $stderr.puts "dispatch: jobrecord.save failed"
647 # Don't fail the job if crunch-job didn't even get as far as
648 # starting it. If the job failed to run due to an infrastructure
649 # issue with crunch-job or slurm, we want the job to stay in the
650 # queue. If crunch-job exited after losing a race to another
651 # crunch-job process, it exits 75 and we should leave the job
652 # record alone so the winner of the race do its thing.
654 # There is still an unhandled race condition: If our crunch-job
655 # process is about to lose a race with another crunch-job
656 # process, but crashes before getting to its "exit 75" (for
657 # example, "cannot fork" or "cannot reach API server") then we
658 # will assume incorrectly that it's our process's fault
659 # jobrecord.started_at is non-nil, and mark the job as failed
660 # even though the winner of the race is probably still doing
664 # Invalidate the per-job auth token, unless the job is still queued and we
665 # might want to try it again.
666 if jobrecord.state != "Queued"
667 j_done[:job_auth].update_attributes expires_at: db_current_time
670 @running.delete job_done.uuid
674 expire_tokens = @pipe_auth_tokens.dup
675 @todo_pipelines.each do |p|
676 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
677 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
679 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-pipeline-here --no-wait --instance #{p.uuid}`
680 expire_tokens.delete p.uuid
683 expire_tokens.each do |k, v|
684 v.update_attributes expires_at: db_current_time
685 @pipe_auth_tokens.delete k
691 $stderr.puts "dispatch: ready"
692 while !$signal[:term] or @running.size > 0
695 @running.each do |uuid, j|
696 if !j[:started] and j[:sent_int] < 2
698 Process.kill 'INT', j[:wait_thr].pid
700 # No such pid = race condition + desired result is
707 refresh_todo unless did_recently(:refresh_todo, 1.0)
708 update_node_status unless did_recently(:update_node_status, 1.0)
709 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
712 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
717 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
724 def did_recently(thing, min_interval)
725 current_time = db_current_time
726 if !@did_recently[thing] or @did_recently[thing] < current_time - min_interval
727 @did_recently[thing] = current_time
734 # send message to log table. we want these records to be transient
735 def write_log running_job
736 return if running_job[:stderr_buf_to_flush] == ''
738 # Send out to log event if buffer size exceeds the bytes per event or if
739 # it has been at least crunch_log_seconds_between_events seconds since
741 if running_job[:stderr_buf_to_flush].size > Rails.configuration.crunch_log_bytes_per_event or
742 (db_current_time - running_job[:stderr_flushed_at]) >= Rails.configuration.crunch_log_seconds_between_events
744 log = Log.new(object_uuid: running_job[:job].uuid,
745 event_type: 'stderr',
746 owner_uuid: running_job[:job].owner_uuid,
747 properties: {"text" => running_job[:stderr_buf_to_flush]})
749 running_job[:events_logged] += 1
751 $stderr.puts "Failed to write logs"
752 $stderr.puts exception.backtrace
754 running_job[:stderr_buf_to_flush] = ''
755 running_job[:stderr_flushed_at] = db_current_time
760 # This is how crunch-job child procs know where the "refresh" trigger file is
761 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger