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
57 EXIT_RETRY_UNLOCKED = 93
58 RETRY_UNLOCKED_LIMIT = 3
61 @crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
62 if @crunch_job_bin.empty?
63 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
66 @docker_bin = ENV['CRUNCH_JOB_DOCKER_BIN']
68 @arvados_internal = Rails.configuration.git_internal_dir
69 if not File.exists? @arvados_internal
70 $stderr.puts `mkdir -p #{@arvados_internal.shellescape} && git init --bare #{@arvados_internal.shellescape}`
71 raise "No internal git repository available" unless ($? == 0)
74 @repo_root = Rails.configuration.git_repositories_dir
75 @arvados_repo_path = Repository.where(name: "arvados").first.server_path
81 @pipe_auth_tokens = {}
84 @todo_job_retries = {}
85 @job_retry_counts = Hash.new(0)
90 return act_as_system_user
95 @todo = @todo_job_retries.values + Job.queue.select(&:repository)
97 if $options[:pipelines]
98 @todo_pipelines = PipelineInstance.queue
102 def each_slurm_line(cmd, outfmt, max_fields=nil)
103 max_fields ||= outfmt.split(":").size
104 max_fields += 1 # To accommodate the node field we add
105 @@slurm_version ||= Gem::Version.new(`sinfo --version`.match(/\b[\d\.]+\b/)[0])
106 if Gem::Version.new('2.3') <= @@slurm_version
107 `#{cmd} --noheader -o '%n:#{outfmt}'`.each_line do |line|
108 yield line.chomp.split(":", max_fields)
111 # Expand rows with hostname ranges (like "foo[1-3,5,9-12]:idle")
112 # into multiple rows with one hostname each.
113 `#{cmd} --noheader -o '%N:#{outfmt}'`.each_line do |line|
114 tokens = line.chomp.split(":", max_fields)
115 if (re = tokens[0].match /^(.*?)\[([-,\d]+)\]$/)
117 re[2].split(",").each do |range|
118 range = range.split("-").collect(&:to_i)
119 (range[0]..range[-1]).each do |n|
120 yield [re[1] + n.to_s] + tokens
132 each_slurm_line("sinfo", "%t") do |hostname, state|
133 # Treat nodes in idle* state as down, because the * means that slurm
134 # hasn't been able to communicate with it recently.
135 state.sub!(/^idle\*/, "down")
136 state.sub!(/\W+$/, "")
137 state = "down" unless %w(idle alloc down).include?(state)
138 slurm_nodes[hostname] = {state: state, job: nil}
140 each_slurm_line("squeue", "%j") do |hostname, job_uuid|
141 slurm_nodes[hostname][:job] = job_uuid if slurm_nodes[hostname]
146 def update_node_status
147 return unless Server::Application.config.crunch_job_wrapper.to_s.match /^slurm/
148 slurm_status.each_pair do |hostname, slurmdata|
149 next if @node_state[hostname] == slurmdata
151 node = Node.where('hostname=?', hostname).order(:last_ping_at).last
153 $stderr.puts "dispatch: update #{hostname} state to #{slurmdata}"
154 node.info["slurm_state"] = slurmdata[:state]
155 node.job_uuid = slurmdata[:job]
157 @node_state[hostname] = slurmdata
159 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
161 elsif slurmdata[:state] != 'down'
162 $stderr.puts "dispatch: SLURM reports '#{hostname}' is not down, but no node has that name"
165 $stderr.puts "dispatch: error updating #{hostname} node status: #{error}"
170 def positive_int(raw_value, default=nil)
171 value = begin raw_value.to_i rescue 0 end
179 NODE_CONSTRAINT_MAP = {
180 # Map Job runtime_constraints keys to the corresponding Node info key.
181 'min_ram_mb_per_node' => 'total_ram_mb',
182 'min_scratch_mb_per_node' => 'total_scratch_mb',
183 'min_cores_per_node' => 'total_cpu_cores',
186 def nodes_available_for_job_now(job)
187 # Find Nodes that satisfy a Job's runtime constraints (by building
188 # a list of Procs and using them to test each Node). If there
189 # enough to run the Job, return an array of their names.
190 # Otherwise, return nil.
191 need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
193 positive_int(node.info[node_key], 0) >=
194 positive_int(job.runtime_constraints[job_key], 0)
197 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
199 Node.find_each do |node|
200 good_node = (node.info['slurm_state'] == 'idle')
201 need_procs.each { |node_test| good_node &&= node_test.call(node) }
204 if usable_nodes.count >= min_node_count
205 return usable_nodes.map { |node| node.hostname }
212 def nodes_available_for_job(job)
213 # Check if there are enough idle nodes with the Job's minimum
214 # hardware requirements to run it. If so, return an array of
215 # their names. If not, up to once per hour, signal start_jobs to
216 # hold off launching Jobs. This delay is meant to give the Node
217 # Manager an opportunity to make new resources available for new
220 # The exact timing parameters here might need to be adjusted for
221 # the best balance between helping the longest-waiting Jobs run,
222 # and making efficient use of immediately available resources.
223 # These are all just first efforts until we have more data to work
225 nodelist = nodes_available_for_job_now(job)
226 if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
227 $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
228 @node_wait_deadline = Time.now + 5.minutes
233 def fail_job job, message
234 $stderr.puts "dispatch: #{job.uuid}: #{message}"
236 Log.new(object_uuid: job.uuid,
237 event_type: 'dispatch',
238 owner_uuid: job.owner_uuid,
240 properties: {"text" => message}).save!
242 $stderr.puts "dispatch: log.create failed"
246 job.lock @authorizations[job.uuid].user.uuid
249 $stderr.puts "dispatch: save failed setting job #{job.uuid} to failed"
251 rescue ArvadosModel::AlreadyLockedError
252 $stderr.puts "dispatch: tried to mark job #{job.uuid} as failed but it was already locked by someone else"
256 def stdout_s(cmd_a, opts={})
257 IO.popen(cmd_a, "r", opts) do |pipe|
258 return pipe.read.chomp
263 ["git", "--git-dir=#{@arvados_internal}"] + cmd_a
266 def get_authorization(job)
267 if @authorizations[job.uuid] and
268 @authorizations[job.uuid].user.uuid != job.modified_by_user_uuid
269 # We already made a token for this job, but we need a new one
270 # because modified_by_user_uuid has changed (the job will run
271 # as a different user).
272 @authorizations[job.uuid].update_attributes expires_at: Time.now
273 @authorizations[job.uuid] = nil
275 if not @authorizations[job.uuid]
276 auth = ApiClientAuthorization.
277 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
280 $stderr.puts "dispatch: auth.save failed for #{job.uuid}"
282 @authorizations[job.uuid] = auth
285 @authorizations[job.uuid]
288 def internal_repo_has_commit? sha1
289 if (not @fetched_commits[sha1] and
290 sha1 == stdout_s(git_cmd("rev-list", "-n1", sha1), err: "/dev/null") and
292 @fetched_commits[sha1] = true
294 return @fetched_commits[sha1]
297 def get_commit src_repo, sha1
298 return true if internal_repo_has_commit? sha1
300 # commit does not exist in internal repository, so import the
301 # source repository using git fetch-pack
302 cmd = git_cmd("fetch-pack", "--no-progress", "--all", src_repo)
303 $stderr.puts "dispatch: #{cmd}"
304 $stderr.puts(stdout_s(cmd))
305 @fetched_commits[sha1] = ($? == 0)
308 def tag_commit(commit_hash, tag_name)
309 # @git_tags[T]==V if we know commit V has been tagged T in the
310 # arvados_internal repository.
311 if not @git_tags[tag_name]
312 cmd = git_cmd("tag", tag_name, commit_hash)
313 $stderr.puts "dispatch: #{cmd}"
314 $stderr.puts(stdout_s(cmd, err: "/dev/null"))
316 # git tag failed. This may be because the tag already exists, so check for that.
317 tag_rev = stdout_s(git_cmd("rev-list", "-n1", tag_name))
319 # We got a revision back
320 if tag_rev != commit_hash
321 # Uh oh, the tag doesn't point to the revision we were expecting.
322 # Someone has been monkeying with the job record and/or git.
323 fail_job job, "Existing tag #{tag_name} points to commit #{tag_rev} but expected commit #{commit_hash}"
326 # we're okay (fall through to setting @git_tags below)
328 # git rev-list failed for some reason.
329 fail_job job, "'git tag' for #{tag_name} failed but did not find any existing tag using 'git rev-list'"
333 # 'git tag' was successful, or there is an existing tag that points to the same revision.
334 @git_tags[tag_name] = commit_hash
335 elsif @git_tags[tag_name] != commit_hash
336 fail_job job, "Existing tag #{tag_name} points to commit #{@git_tags[tag_name]} but this job uses commit #{commit_hash}"
344 next if @running[job.uuid]
347 case Server::Application.config.crunch_job_wrapper
350 # Don't run more than one at a time.
354 when :slurm_immediate
355 nodelist = nodes_available_for_job(job)
357 if Time.now < @node_wait_deadline
363 cmd_args = ["salloc",
368 "--job-name=#{job.uuid}",
369 "--nodelist=#{nodelist.join(',')}"]
371 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
374 if Server::Application.config.crunch_job_user
375 cmd_args.unshift("sudo", "-E", "-u",
376 Server::Application.config.crunch_job_user,
377 "LD_LIBRARY_PATH=#{ENV['LD_LIBRARY_PATH']}",
378 "PATH=#{ENV['PATH']}",
379 "PERLLIB=#{ENV['PERLLIB']}",
380 "PYTHONPATH=#{ENV['PYTHONPATH']}",
381 "RUBYLIB=#{ENV['RUBYLIB']}",
382 "GEM_PATH=#{ENV['GEM_PATH']}")
385 next unless get_authorization job
387 ready = internal_repo_has_commit? job.script_version
390 # Import the commit from the specified repository into the
391 # internal repository. This should have been done already when
392 # the job was created/updated; this code is obsolete except to
393 # avoid deployment races. Failing the job would be a
394 # reasonable thing to do at this point.
395 repo = Repository.where(name: job.repository).first
396 if repo.nil? or repo.server_path.nil?
397 fail_job "Repository #{job.repository} not found under #{@repo_root}"
400 ready &&= get_commit repo.server_path, job.script_version
401 ready &&= tag_commit job.script_version, job.uuid
404 # This should be unnecessary, because API server does it during
405 # job create/update, but it's still not a bad idea to verify the
406 # tag is correct before starting the job:
407 ready &&= tag_commit job.script_version, job.uuid
409 # The arvados_sdk_version doesn't support use of arbitrary
410 # remote URLs, so the requested version isn't necessarily copied
411 # into the internal repository yet.
412 if job.arvados_sdk_version
413 ready &&= get_commit @arvados_repo_path, job.arvados_sdk_version
414 ready &&= tag_commit job.arvados_sdk_version, "#{job.uuid}-arvados-sdk"
418 fail_job job, "commit not present in internal repository"
422 cmd_args += [@crunch_job_bin,
423 '--job-api-token', @authorizations[job.uuid].api_token,
425 '--git-dir', @arvados_internal]
428 cmd_args += ['--docker-bin', @docker_bin]
431 if @todo_job_retries.include?(job.uuid)
432 cmd_args << "--force-unlock"
435 $stderr.puts "dispatch: #{cmd_args.join ' '}"
438 i, o, e, t = Open3.popen3(*cmd_args)
440 $stderr.puts "dispatch: popen3: #{$!}"
445 $stderr.puts "dispatch: job #{job.uuid}"
446 start_banner = "dispatch: child #{t.pid} start #{LogTime.now}"
447 $stderr.puts start_banner
449 @running[job.uuid] = {
455 buf: {stderr: '', stdout: ''},
458 job_auth: @authorizations[job.uuid],
459 stderr_buf_to_flush: '',
460 stderr_flushed_at: Time.new(0),
463 log_throttle_is_open: true,
464 log_throttle_reset_time: Time.now + Rails.configuration.crunch_log_throttle_period,
465 log_throttle_bytes_so_far: 0,
466 log_throttle_lines_so_far: 0,
467 log_throttle_bytes_skipped: 0,
470 @todo_job_retries.delete(job.uuid)
475 # Test for hard cap on total output and for log throttling. Returns whether
476 # the log line should go to output or not. Modifies "line" in place to
477 # replace it with an error if a logging limit is tripped.
478 def rate_limit running_job, line
481 if running_job[:log_throttle_is_open]
482 running_job[:log_throttle_lines_so_far] += 1
483 running_job[:log_throttle_bytes_so_far] += linesize
484 running_job[:bytes_logged] += linesize
486 if (running_job[:bytes_logged] >
487 Rails.configuration.crunch_limit_log_bytes_per_job)
488 message = "Exceeded log limit #{Rails.configuration.crunch_limit_log_bytes_per_job} bytes (crunch_limit_log_bytes_per_job). Log will be truncated."
489 running_job[:log_throttle_reset_time] = Time.now + 100.years
490 running_job[:log_throttle_is_open] = false
492 elsif (running_job[:log_throttle_bytes_so_far] >
493 Rails.configuration.crunch_log_throttle_bytes)
494 remaining_time = running_job[:log_throttle_reset_time] - Time.now
495 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"
496 running_job[:log_throttle_is_open] = false
498 elsif (running_job[:log_throttle_lines_so_far] >
499 Rails.configuration.crunch_log_throttle_lines)
500 remaining_time = running_job[:log_throttle_reset_time] - Time.now
501 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"
502 running_job[:log_throttle_is_open] = false
506 if not running_job[:log_throttle_is_open]
507 # Don't log anything if any limit has been exceeded. Just count lossage.
508 running_job[:log_throttle_bytes_skipped] += linesize
512 # Yes, write to logs, but use our "rate exceeded" message
513 # instead of the log message that exceeded the limit.
517 running_job[:log_throttle_is_open]
522 @running.each do |job_uuid, j|
526 if now > j[:log_throttle_reset_time]
527 # It has been more than throttle_period seconds since the last
528 # checkpoint so reset the throttle
529 if j[:log_throttle_bytes_skipped] > 0
530 message = "#{job_uuid} ! Skipped #{j[:log_throttle_bytes_skipped]} bytes of log"
532 j[:stderr_buf_to_flush] << "#{LogTime.now} #{message}\n"
535 j[:log_throttle_reset_time] = now + Rails.configuration.crunch_log_throttle_period
536 j[:log_throttle_bytes_so_far] = 0
537 j[:log_throttle_lines_so_far] = 0
538 j[:log_throttle_bytes_skipped] = 0
539 j[:log_throttle_is_open] = true
542 j[:buf].each do |stream, streambuf|
543 # Read some data from the child stream
546 # It's important to use a big enough buffer here. When we're
547 # being flooded with logs, we must read and discard many
548 # bytes at once. Otherwise, we can easily peg a CPU with
549 # time-checking and other loop overhead. (Quick tests show a
550 # 1MiB buffer working 2.5x as fast as a 64 KiB buffer.)
552 # So don't reduce this buffer size!
553 buf = j[stream].read_nonblock(2**20)
554 rescue Errno::EAGAIN, EOFError
557 # Short circuit the counting code if we're just going to throw
558 # away the data anyway.
559 if not j[:log_throttle_is_open]
560 j[:log_throttle_bytes_skipped] += streambuf.size + buf.size
567 # Append to incomplete line from previous read, if any
571 streambuf.each_line do |line|
572 if not line.end_with? $/
573 if line.size > Rails.configuration.crunch_log_throttle_bytes
574 # Without a limit here, we'll use 2x an arbitrary amount
575 # of memory, and waste a lot of time copying strings
576 # around, all without providing any feedback to anyone
577 # about what's going on _or_ hitting any of our throttle
580 # Here we leave "line" alone, knowing it will never be
581 # sent anywhere: rate_limit() will reach
582 # crunch_log_throttle_bytes immediately. However, we'll
583 # leave [...] in bufend: if the trailing end of the long
584 # line does end up getting sent anywhere, it will have
585 # some indication that it is incomplete.
588 # If line length is sane, we'll wait for the rest of the
589 # line to appear in the next read_pipes() call.
594 # rate_limit returns true or false as to whether to actually log
595 # the line or not. It also modifies "line" in place to replace
596 # it with an error if a logging limit is tripped.
597 if rate_limit j, line
598 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
600 pub_msg = "#{LogTime.now} #{line.strip}\n"
601 j[:stderr_buf_to_flush] << pub_msg
605 # Leave the trailing incomplete line (if any) in streambuf for
607 streambuf.replace bufend
609 # Flush buffered logs to the logs table, if appropriate. We have
610 # to do this even if we didn't collect any new logs this time:
611 # otherwise, buffered data older than seconds_between_events
612 # won't get flushed until new data arrives.
618 return if 0 == @running.size
624 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
626 j_done = @running.values.
627 select { |j| j[:wait_thr].pid == pid_done }.
630 rescue SystemCallError
631 # I have @running processes but system reports I have no
632 # children. This is likely to happen repeatedly if it happens at
633 # all; I will log this no more than once per child process I
635 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
636 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
637 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
639 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
642 @running.each do |uuid, j|
643 if j[:wait_thr].status == false
644 pid_done = j[:wait_thr].pid
652 job_done = j_done[:job]
654 # Ensure every last drop of stdout and stderr is consumed.
656 # Reset flush timestamp to make sure log gets written.
657 j_done[:stderr_flushed_at] = Time.new(0)
658 # Write any remaining logs.
661 j_done[:buf].each do |stream, streambuf|
663 $stderr.puts streambuf + "\n"
667 # Wait the thread (returns a Process::Status)
668 exit_status = j_done[:wait_thr].value.exitstatus
669 exit_tempfail = exit_status == EXIT_TEMPFAIL
671 $stderr.puts "dispatch: child #{pid_done} exit #{exit_status}"
672 $stderr.puts "dispatch: job #{job_done.uuid} end"
674 jobrecord = Job.find_by_uuid(job_done.uuid)
676 if exit_status == EXIT_RETRY_UNLOCKED
677 # The job failed because all of the nodes allocated to it
678 # failed. Only this crunch-dispatch process can retry the job:
679 # it's already locked, and there's no way to put it back in the
680 # Queued state. Put it in our internal todo list unless the job
681 # has failed this way excessively.
682 @job_retry_counts[jobrecord.uuid] += 1
683 exit_tempfail = @job_retry_counts[jobrecord.uuid] <= RETRY_UNLOCKED_LIMIT
685 @todo_job_retries[jobrecord.uuid] = jobrecord
687 $stderr.puts("dispatch: job #{jobrecord.uuid} exceeded node failure retry limit -- giving up")
692 @job_retry_counts.delete(jobrecord.uuid)
693 if jobrecord.state == "Running"
694 # Apparently there was an unhandled error. That could potentially
695 # include "all allocated nodes failed" when we don't to retry
696 # because the job has already been retried RETRY_UNLOCKED_LIMIT
697 # times. Fail the job.
698 jobrecord.state = "Failed"
699 if not jobrecord.save
700 $stderr.puts "dispatch: jobrecord.save failed"
704 # If the job failed to run due to an infrastructure
705 # issue with crunch-job or slurm, we want the job to stay in the
706 # queue. If crunch-job exited after losing a race to another
707 # crunch-job process, it exits 75 and we should leave the job
708 # record alone so the winner of the race can do its thing.
709 # If crunch-job exited after all of its allocated nodes failed,
710 # it exits 93, and we want to retry it later (see the
711 # EXIT_RETRY_UNLOCKED `if` block).
713 # There is still an unhandled race condition: If our crunch-job
714 # process is about to lose a race with another crunch-job
715 # process, but crashes before getting to its "exit 75" (for
716 # example, "cannot fork" or "cannot reach API server") then we
717 # will assume incorrectly that it's our process's fault
718 # jobrecord.started_at is non-nil, and mark the job as failed
719 # even though the winner of the race is probably still doing
723 # Invalidate the per-job auth token, unless the job is still queued and we
724 # might want to try it again.
725 if jobrecord.state != "Queued" and !@todo_job_retries.include?(jobrecord.uuid)
726 j_done[:job_auth].update_attributes expires_at: Time.now
729 @running.delete job_done.uuid
733 expire_tokens = @pipe_auth_tokens.dup
734 @todo_pipelines.each do |p|
735 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
736 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
738 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-pipeline-here --no-wait --instance #{p.uuid}`
739 expire_tokens.delete p.uuid
742 expire_tokens.each do |k, v|
743 v.update_attributes expires_at: Time.now
744 @pipe_auth_tokens.delete k
750 $stderr.puts "dispatch: ready"
751 while !$signal[:term] or @running.size > 0
754 @running.each do |uuid, j|
755 if !j[:started] and j[:sent_int] < 2
757 Process.kill 'INT', j[:wait_thr].pid
759 # No such pid = race condition + desired result is
766 refresh_todo unless did_recently(:refresh_todo, 1.0)
767 update_node_status unless did_recently(:update_node_status, 1.0)
768 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
771 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
776 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
779 # If there are jobs we wanted to retry, we have to mark them as failed now.
780 # Other dispatchers can't pick them up because we hold their lock.
781 @todo_job_retries.each_key do |job_uuid|
782 job = Job.find_by_uuid(job_uuid)
783 if job.state == "Running"
784 fail_job(job, "crunch-dispatch was stopped during job's tempfail retry loop")
791 def did_recently(thing, min_interval)
792 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
793 @did_recently[thing] = Time.now
800 # send message to log table. we want these records to be transient
801 def write_log running_job
802 return if running_job[:stderr_buf_to_flush] == ''
804 # Send out to log event if buffer size exceeds the bytes per event or if
805 # it has been at least crunch_log_seconds_between_events seconds since
807 if running_job[:stderr_buf_to_flush].size > Rails.configuration.crunch_log_bytes_per_event or
808 (Time.now - running_job[:stderr_flushed_at]) >= Rails.configuration.crunch_log_seconds_between_events
810 log = Log.new(object_uuid: running_job[:job].uuid,
811 event_type: 'stderr',
812 owner_uuid: running_job[:job].owner_uuid,
813 properties: {"text" => running_job[:stderr_buf_to_flush]})
815 running_job[:events_logged] += 1
817 $stderr.puts "Failed to write logs"
818 $stderr.puts exception.backtrace
820 running_job[:stderr_buf_to_flush] = ''
821 running_job[:stderr_flushed_at] = Time.now
826 # This is how crunch-job child procs know where the "refresh" trigger file is
827 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger
829 # If salloc can't allocate resources immediately, make it use our temporary
830 # failure exit code. This ensures crunch-dispatch won't mark a job failed
831 # because of an issue with node allocation. This often happens when
832 # another dispatcher wins the race to allocate nodes.
833 ENV["SLURM_EXIT_IMMEDIATE"] = Dispatcher::EXIT_TEMPFAIL.to_s