1 require 'whitelist_update'
3 class Container < ArvadosModel
6 include CommonApiTemplate
7 include WhitelistUpdate
8 extend CurrentApiClient
10 serialize :environment, Hash
11 serialize :mounts, Hash
12 serialize :runtime_constraints, Hash
13 serialize :command, Array
15 before_validation :fill_field_defaults, :if => :new_record?
16 before_validation :set_timestamps
17 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
18 validate :validate_state_change
19 validate :validate_change
20 validate :validate_lock
21 after_validation :assign_auth
22 before_save :sort_serialized_attrs
23 after_save :handle_completed
25 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
26 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
28 api_accessible :user, extend: :common do |t|
30 t.add :container_image
42 t.add :runtime_constraints
48 # Supported states for a container
53 (Running = 'Running'),
54 (Complete = 'Complete'),
55 (Cancelled = 'Cancelled')
60 Queued => [Locked, Cancelled],
61 Locked => [Queued, Running, Cancelled],
62 Running => [Complete, Cancelled]
70 if [Queued, Locked, Running].include? self.state
71 # Update the priority of this container to the maximum priority of any of
72 # its committed container requests and save the record.
73 self.priority = ContainerRequest.
74 where(container_uuid: uuid,
75 state: ContainerRequest::Committed).
81 def self.find_reusable(attrs)
82 candidates = Container.
83 where('command = ?', attrs[:command].to_yaml).
84 where('cwd = ?', attrs[:cwd]).
85 where('environment = ?', self.deep_sort_hash(attrs[:environment]).to_yaml).
86 where('output_path = ?', attrs[:output_path]).
87 where('container_image = ?', attrs[:container_image]).
88 where('mounts = ?', self.deep_sort_hash(attrs[:mounts]).to_yaml).
89 where('runtime_constraints = ?', self.deep_sort_hash(attrs[:runtime_constraints]).to_yaml)
91 # Check for Completed candidates that had consistent outputs.
92 completed = candidates.where(state: Complete).where(exit_code: 0)
93 outputs = completed.select('output').group('output').limit(2)
94 if outputs.count.count != 1
95 Rails.logger.debug("Found #{outputs.count.length} different outputs")
97 readable_by(current_user).
98 where(portable_data_hash: outputs.first.output).
100 Rails.logger.info("Found reusable container(s) " +
101 "but output #{outputs.first} is not readable " +
102 "by user #{current_user.uuid}")
104 # Return the oldest eligible container whose log is still
105 # present and readable by current_user.
106 readable_pdh = Collection.
107 readable_by(current_user).
108 select('portable_data_hash')
109 completed = completed.
110 where("log in (#{readable_pdh.to_sql})").
111 order('finished_at asc').
114 return completed.first
116 Rails.logger.info("Found reusable container(s) but none with a log " +
117 "readable by user #{current_user.uuid}")
121 # Check for Running candidates and return the most likely to finish sooner.
122 running = candidates.where(state: Running).
123 order('progress desc, started_at asc').limit(1).first
124 return running if not running.nil?
126 # Check for Locked or Queued ones and return the most likely to start first.
127 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
128 order('state asc, priority desc, created_at asc').limit(1).first
129 return locked_or_queued if not locked_or_queued.nil?
131 # No suitable candidate found.
137 if self.state == Locked
138 raise AlreadyLockedError
147 if self.state == Queued
148 raise InvalidStateTransitionError
155 def self.readable_by(*users_list)
156 if users_list.select { |u| u.is_admin }.any?
159 user_uuids = users_list.map { |u| u.uuid }
160 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
162 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
163 joins(:container_requests).
164 where("container_requests.uuid IN #{permitted} OR "+
165 "container_requests.owner_uuid IN (:uuids)",
170 [Complete, Cancelled].include?(self.state)
175 def fill_field_defaults
176 self.state ||= Queued
177 self.environment ||= {}
178 self.runtime_constraints ||= {}
184 def permission_to_create
185 current_user.andand.is_admin
188 def permission_to_update
189 current_user.andand.is_admin
193 if self.state_changed? and self.state == Running
194 self.started_at ||= db_current_time
197 if self.state_changed? and [Complete, Cancelled].include? self.state
198 self.finished_at ||= db_current_time
206 permitted.push(:owner_uuid, :command, :container_image, :cwd,
207 :environment, :mounts, :output_path, :priority,
208 :runtime_constraints)
213 permitted.push :priority
216 permitted.push :priority, :progress
217 if self.state_changed?
218 permitted.push :started_at
222 if self.state_was == Running
223 permitted.push :finished_at, :output, :log, :exit_code
229 permitted.push :finished_at, :output, :log
231 permitted.push :finished_at
235 # The state_transitions check will add an error message for this
239 check_update_whitelist permitted
243 # If the Container is already locked by someone other than the
244 # current api_client_auth, disallow all changes -- except
245 # priority, which needs to change to reflect max(priority) of
246 # relevant ContainerRequests.
247 if locked_by_uuid_was
248 if locked_by_uuid_was != Thread.current[:api_client_authorization].uuid
249 check_update_whitelist [:priority]
253 if [Locked, Running].include? self.state
254 # If the Container was already locked, locked_by_uuid must not
255 # changes. Otherwise, the current auth gets the lock.
256 need_lock = locked_by_uuid_was || Thread.current[:api_client_authorization].uuid
261 # The caller can provide a new value for locked_by_uuid, but only
262 # if it's exactly what we expect. This allows a caller to perform
263 # an update like {"state":"Unlocked","locked_by_uuid":null}.
264 if self.locked_by_uuid_changed?
265 if self.locked_by_uuid != need_lock
266 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
269 self.locked_by_uuid = need_lock
273 if self.auth_uuid_changed?
274 return errors.add :auth_uuid, 'is readonly'
276 if not [Locked, Running].include? self.state
278 self.auth.andand.update_attributes(expires_at: db_current_time)
285 cr = ContainerRequest.
286 where('container_uuid=? and priority>0', self.uuid).
287 order('priority desc').
290 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
292 self.auth = ApiClientAuthorization.
293 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
297 def sort_serialized_attrs
298 if self.environment_changed?
299 self.environment = self.class.deep_sort_hash(self.environment)
301 if self.mounts_changed?
302 self.mounts = self.class.deep_sort_hash(self.mounts)
304 if self.runtime_constraints_changed?
305 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
310 # This container is finished so finalize any associated container requests
311 # that are associated with this container.
312 if self.state_changed? and self.final?
313 act_as_system_user do
315 if self.state == Cancelled
316 retryable_requests = ContainerRequest.where("priority > 0 and state = 'Committed' and container_count < container_count_max")
318 retryable_requests = []
321 if retryable_requests.any?
323 command: self.command,
325 environment: self.environment,
326 output_path: self.output_path,
327 container_image: self.container_image,
329 runtime_constraints: self.runtime_constraints
331 c = Container.create! c_attrs
332 retryable_requests.each do |cr|
334 # Use row locking because this increments container_count
335 cr.container_uuid = c.uuid
341 # Notify container requests associated with this container
342 ContainerRequest.where(container_uuid: uuid,
343 state: ContainerRequest::Committed).each do |cr|
347 # Try to cancel any outstanding container requests made by this container.
348 ContainerRequest.where(requesting_container_uuid: uuid,
349 state: ContainerRequest::Committed).each do |cr|