+ def self.find_reusable(attrs)
+ candidates = Container.
+ where('command = ?', attrs[:command].to_yaml).
+ where('cwd = ?', attrs[:cwd]).
+ where('environment = ?', self.deep_sort_hash(attrs[:environment]).to_yaml).
+ where('output_path = ?', attrs[:output_path]).
+ where('container_image = ?', attrs[:container_image]).
+ where('mounts = ?', self.deep_sort_hash(attrs[:mounts]).to_yaml).
+ where('runtime_constraints = ?', self.deep_sort_hash(attrs[:runtime_constraints]).to_yaml)
+
+ # Check for Completed candidates that only had consistent outputs.
+ completed = candidates.where(state: Complete).where(exit_code: 0)
+ if completed.select("output").group('output').limit(2).length == 1
+ return completed.order('finished_at asc').limit(1).first
+ end
+
+ # Check for Running candidates and return the most likely to finish sooner.
+ running = candidates.where(state: Running).
+ order('progress desc, started_at asc').limit(1).first
+ return running if not running.nil?
+
+ # Check for Locked or Queued ones and return the most likely to start first.
+ locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
+ order('state asc, priority desc, created_at asc').limit(1).first
+ return locked_or_queued if not locked_or_queued.nil?
+
+ # No suitable candidate found.
+ nil
+ end
+
+ def lock
+ with_lock do
+ if self.state == Locked
+ raise AlreadyLockedError
+ end
+ self.state = Locked
+ self.save!
+ end
+ end
+
+ def unlock
+ with_lock do
+ if self.state == Queued
+ raise InvalidStateTransitionError
+ end
+ self.state = Queued
+ self.save!
+ end
+ end
+
+ def self.readable_by(*users_list)