- # Multiple candidates found, search for the best one:
- # The most recent completed container
- winner = candidates.select {|c| c.state == 'Complete'}.sort_by {|c| c.finished_at}.last
- winner if not winner.nil?
- # The running container that's most likely to finish sooner.
- winner = candidates.select {|c| c.state == 'Running'}.
- sort {|a, b| [b.progress, a.started_at] <=> [a.progress, b.started_at]}.first
- winner if not winner.nil?
- # The locked container that's most likely to start sooner.
- winner = candidates.select {|c| c.state == 'Locked'}.
- sort {|a, b| [b.priority, a.created_at] <=> [a.priority, b.created_at]}.first
- winner if not winner.nil?
- # The queued container that's most likely to start sooner.
- winner = candidates.select {|c| c.state == 'Queued'}.
- sort {|a, b| [b.priority, a.created_at] <=> [a.priority, b.created_at]}.first
- winner if not winner.nil?
+ # Return the oldest eligible container whose log is still
+ # present and readable by current_user.
+ readable_pdh = Collection.
+ readable_by(current_user).
+ select('portable_data_hash')
+ completed = completed.
+ where("log in (#{readable_pdh.to_sql})").
+ order('finished_at asc').
+ limit(1)
+ if completed.first
+ return completed.first
+ else
+ Rails.logger.info("Found reusable container(s) but none with a log " +
+ "readable by user #{current_user.uuid}")
+ end