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 # sinfo tells us about a node N times if it is shared by N partitions
75 next if node_seen[re[1]]
76 node_seen[re[1]] = true
78 # update our database (and cache) when a node's state changes
79 if @node_state[re[1]] != re[2]
80 @node_state[re[1]] = re[2]
81 node = Node.where('hostname=?', re[1]).first
83 $stderr.puts "dispatch: update #{re[1]} state to #{re[2]}"
84 node.info['slurm_state'] = re[2]
86 $stderr.puts "dispatch: failed to update #{node.uuid}: #{node.errors.messages}"
89 $stderr.puts "dispatch: sinfo reports '#{re[1]}' is not down, but no node has that name"
94 $stderr.puts "dispatch: error updating node status: #{error}"
99 def positive_int(raw_value, default=nil)
100 value = begin raw_value.to_i rescue 0 end
108 NODE_CONSTRAINT_MAP = {
109 # Map Job runtime_constraints keys to the corresponding Node info key.
110 'min_ram_mb_per_node' => 'total_ram_mb',
111 'min_scratch_mb_per_node' => 'total_scratch_mb',
112 'min_cores_per_node' => 'total_cpu_cores',
115 def nodes_available_for_job_now(job)
116 # Find Nodes that satisfy a Job's runtime constraints (by building
117 # a list of Procs and using them to test each Node). If there
118 # enough to run the Job, return an array of their names.
119 # Otherwise, return nil.
120 need_procs = NODE_CONSTRAINT_MAP.each_pair.map do |job_key, node_key|
122 positive_int(node.info[node_key], 0) >=
123 positive_int(job.runtime_constraints[job_key], 0)
126 min_node_count = positive_int(job.runtime_constraints['min_nodes'], 1)
128 Node.find_each do |node|
129 good_node = (node.info['slurm_state'] == 'idle')
130 need_procs.each { |node_test| good_node &&= node_test.call(node) }
133 if usable_nodes.count >= min_node_count
134 return usable_nodes.map { |node| node.hostname }
141 def nodes_available_for_job(job)
142 # Check if there are enough idle nodes with the Job's minimum
143 # hardware requirements to run it. If so, return an array of
144 # their names. If not, up to once per hour, signal start_jobs to
145 # hold off launching Jobs. This delay is meant to give the Node
146 # Manager an opportunity to make new resources available for new
149 # The exact timing parameters here might need to be adjusted for
150 # the best balance between helping the longest-waiting Jobs run,
151 # and making efficient use of immediately available resources.
152 # These are all just first efforts until we have more data to work
154 nodelist = nodes_available_for_job_now(job)
155 if nodelist.nil? and not did_recently(:wait_for_available_nodes, 3600)
156 $stderr.puts "dispatch: waiting for nodes for #{job.uuid}"
157 @node_wait_deadline = Time.now + 5.minutes
164 next if @running[job.uuid]
167 case Server::Application.config.crunch_job_wrapper
170 when :slurm_immediate
171 nodelist = nodes_available_for_job(job)
173 if Time.now < @node_wait_deadline
179 cmd_args = ["salloc",
184 "--job-name=#{job.uuid}",
185 "--nodelist=#{nodelist.join(',')}"]
187 raise "Unknown crunch_job_wrapper: #{Server::Application.config.crunch_job_wrapper}"
192 if Server::Application.config.crunch_job_user
193 cmd_args.unshift("sudo", "-E", "-u",
194 Server::Application.config.crunch_job_user,
195 "PATH=#{ENV['PATH']}",
196 "PERLLIB=#{ENV['PERLLIB']}",
197 "PYTHONPATH=#{ENV['PYTHONPATH']}",
198 "RUBYLIB=#{ENV['RUBYLIB']}",
199 "GEM_PATH=#{ENV['GEM_PATH']}")
202 job_auth = ApiClientAuthorization.
203 new(user: User.where('uuid=?', job.modified_by_user_uuid).first,
207 crunch_job_bin = (ENV['CRUNCH_JOB_BIN'] || `which arv-crunch-job`.strip)
208 if crunch_job_bin == ''
209 raise "No CRUNCH_JOB_BIN env var, and crunch-job not in path."
214 arvados_internal = Rails.configuration.git_internal_dir
215 if not File.exists? arvados_internal
216 $stderr.puts `mkdir -p #{arvados_internal.shellescape} && cd #{arvados_internal.shellescape} && git init --bare`
219 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository + '.git')
220 src_repo = File.join(Rails.configuration.git_repositories_dir, job.repository, '.git') unless File.exists? src_repo
223 $stderr.puts "dispatch: #{File.join Rails.configuration.git_repositories_dir, job.repository} doesn't exist"
229 $stderr.puts `cd #{arvados_internal.shellescape} && git fetch --no-tags #{src_repo.shellescape} && git tag #{job.uuid.shellescape} #{job.script_version.shellescape}`
231 cmd_args << crunch_job_bin
232 cmd_args << '--job-api-token'
233 cmd_args << job_auth.api_token
236 cmd_args << '--git-dir'
237 cmd_args << arvados_internal
239 $stderr.puts "dispatch: #{cmd_args.join ' '}"
242 i, o, e, t = Open3.popen3(*cmd_args)
244 $stderr.puts "dispatch: popen3: #{$!}"
250 $stderr.puts "dispatch: job #{job.uuid}"
251 start_banner = "dispatch: child #{t.pid} start #{Time.now.ctime.to_s}"
252 $stderr.puts start_banner
254 @running[job.uuid] = {
264 stderr_buf_to_flush: '',
265 stderr_flushed_at: 0,
276 # no-op -- let crunch-job take care of locking.
281 # no-op -- let crunch-job take care of locking.
286 @running.each do |job_uuid, j|
289 # Throw away child stdout
291 j[:stdout].read_nonblock(2**20)
292 rescue Errno::EAGAIN, EOFError
295 # Read whatever is available from child stderr
298 stderr_buf = j[:stderr].read_nonblock(2**20)
299 rescue Errno::EAGAIN, EOFError
303 j[:stderr_buf] << stderr_buf
304 if j[:stderr_buf].index "\n"
305 lines = j[:stderr_buf].lines("\n").to_a
306 if j[:stderr_buf][-1] == "\n"
309 j[:stderr_buf] = lines.pop
312 $stderr.print "#{job_uuid} ! " unless line.index(job_uuid)
314 pub_msg = "#{Time.now.ctime.to_s} #{line.strip} \n"
315 j[:stderr_buf_to_flush] << pub_msg
318 if (Rails.configuration.crunch_log_bytes_per_event < j[:stderr_buf_to_flush].size or
319 (j[:stderr_flushed_at] + Rails.configuration.crunch_log_seconds_between_events < Time.now.to_i))
328 return if 0 == @running.size
334 pid_done = waitpid(-1, Process::WNOHANG | Process::WUNTRACED)
336 j_done = @running.values.
337 select { |j| j[:wait_thr].pid == pid_done }.
340 rescue SystemCallError
341 # I have @running processes but system reports I have no
342 # children. This is likely to happen repeatedly if it happens at
343 # all; I will log this no more than once per child process I
345 if 0 < @running.select { |uuid,j| j[:warned_waitpid_error].nil? }.size
346 children = @running.values.collect { |j| j[:wait_thr].pid }.join ' '
347 $stderr.puts "dispatch: IPC bug: waitpid() error (#{$!}), but I have children #{children}"
349 @running.each do |uuid,j| j[:warned_waitpid_error] = true end
352 @running.each do |uuid, j|
353 if j[:wait_thr].status == false
354 pid_done = j[:wait_thr].pid
362 job_done = j_done[:job]
363 $stderr.puts "dispatch: child #{pid_done} exit"
364 $stderr.puts "dispatch: job #{job_done.uuid} end"
366 # Ensure every last drop of stdout and stderr is consumed
368 write_log j_done # write any remaining logs
370 if j_done[:stderr_buf] and j_done[:stderr_buf] != ''
371 $stderr.puts j_done[:stderr_buf] + "\n"
375 j_done[:wait_thr].value
377 jobrecord = Job.find_by_uuid(job_done.uuid)
378 if jobrecord.started_at
379 # Clean up state fields in case crunch-job exited without
380 # putting the job in a suitable "finished" state.
381 jobrecord.running = false
382 jobrecord.finished_at ||= Time.now
383 if jobrecord.success.nil?
384 jobrecord.success = false
388 # Don't fail the job if crunch-job didn't even get as far as
389 # starting it. If the job failed to run due to an infrastructure
390 # issue with crunch-job or slurm, we want the job to stay in the
394 # Invalidate the per-job auth token
395 j_done[:job_auth].update_attributes expires_at: Time.now
397 @running.delete job_done.uuid
401 expire_tokens = @pipe_auth_tokens.dup
402 @todo_pipelines.each do |p|
403 pipe_auth = (@pipe_auth_tokens[p.uuid] ||= ApiClientAuthorization.
404 create(user: User.where('uuid=?', p.modified_by_user_uuid).first,
406 puts `export ARVADOS_API_TOKEN=#{pipe_auth.api_token} && arv-run-pipeline-instance --run-here --no-wait --instance #{p.uuid}`
407 expire_tokens.delete p.uuid
410 expire_tokens.each do |k, v|
411 v.update_attributes expires_at: Time.now
412 @pipe_auth_tokens.delete k
419 @pipe_auth_tokens ||= { }
420 $stderr.puts "dispatch: ready"
421 while !$signal[:term] or @running.size > 0
424 @running.each do |uuid, j|
425 if !j[:started] and j[:sent_int] < 2
427 Process.kill 'INT', j[:wait_thr].pid
429 # No such pid = race condition + desired result is
436 refresh_todo unless did_recently(:refresh_todo, 1.0)
438 unless @todo.empty? or did_recently(:start_jobs, 1.0) or $signal[:term]
441 unless (@todo_pipelines.empty? and @pipe_auth_tokens.empty?) or did_recently(:update_pipelines, 5.0)
446 select(@running.values.collect { |j| [j[:stdout], j[:stderr]] }.flatten,
453 def too_many_bytes_logged_for_job(j)
454 return (j[:bytes_logged] + j[:stderr_buf_to_flush].size >
455 Rails.configuration.crunch_limit_log_event_bytes_per_job)
458 def too_many_events_logged_for_job(j)
459 return (j[:events_logged] >= Rails.configuration.crunch_limit_log_events_per_job)
462 def did_recently(thing, min_interval)
464 if !@did_recently[thing] or @did_recently[thing] < Time.now - min_interval
465 @did_recently[thing] = Time.now
472 # send message to log table. we want these records to be transient
473 def write_log running_job
475 if (running_job && running_job[:stderr_buf_to_flush] != '')
476 # Truncate logs if they exceed crunch_limit_log_event_bytes_per_job
477 # or crunch_limit_log_events_per_job.
478 if (too_many_bytes_logged_for_job(running_job))
479 return if running_job[:log_truncated]
480 running_job[:log_truncated] = true
481 running_job[:stderr_buf_to_flush] =
482 "Server configured limit reached (crunch_limit_log_event_bytes_per_job: #{Rails.configuration.crunch_limit_log_event_bytes_per_job}). Subsequent logs truncated"
483 elsif (too_many_events_logged_for_job(running_job))
484 return if running_job[:log_truncated]
485 running_job[:log_truncated] = true
486 running_job[:stderr_buf_to_flush] =
487 "Server configured limit reached (crunch_limit_log_events_per_job: #{Rails.configuration.crunch_limit_log_events_per_job}). Subsequent logs truncated"
489 log = Log.new(object_uuid: running_job[:job].uuid,
490 event_type: 'stderr',
491 owner_uuid: running_job[:job].owner_uuid,
492 properties: {"text" => running_job[:stderr_buf_to_flush]})
494 running_job[:bytes_logged] += running_job[:stderr_buf_to_flush].size
495 running_job[:events_logged] += 1
496 running_job[:stderr_buf_to_flush] = ''
497 running_job[:stderr_flushed_at] = Time.now.to_i
500 running_job[:stderr_buf] = "Failed to write logs \n"
501 running_job[:stderr_buf_to_flush] = ''
502 running_job[:stderr_flushed_at] = Time.now.to_i
508 # This is how crunch-job child procs know where the "refresh" trigger file is
509 ENV["CRUNCH_REFRESH_TRIGGER"] = Rails.configuration.crunch_refresh_trigger