1 require 'whitelist_update'
4 class Container < ArvadosModel
7 include CommonApiTemplate
8 include WhitelistUpdate
9 extend CurrentApiClient
11 serialize :environment, Hash
12 serialize :mounts, Hash
13 serialize :runtime_constraints, Hash
14 serialize :command, Array
15 serialize :scheduling_parameters, Hash
17 before_validation :fill_field_defaults, :if => :new_record?
18 before_validation :set_timestamps
19 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
20 validate :validate_state_change
21 validate :validate_change
22 validate :validate_lock
23 validate :validate_output
24 after_validation :assign_auth
25 before_save :sort_serialized_attrs
26 after_save :handle_completed
28 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
29 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
31 api_accessible :user, extend: :common do |t|
33 t.add :container_image
45 t.add :runtime_constraints
49 t.add :scheduling_parameters
52 # Supported states for a container
57 (Running = 'Running'),
58 (Complete = 'Complete'),
59 (Cancelled = 'Cancelled')
64 Queued => [Locked, Cancelled],
65 Locked => [Queued, Running, Cancelled],
66 Running => [Complete, Cancelled]
74 if [Queued, Locked, Running].include? self.state
75 # Update the priority of this container to the maximum priority of any of
76 # its committed container requests and save the record.
77 self.priority = ContainerRequest.
78 where(container_uuid: uuid,
79 state: ContainerRequest::Committed).
85 def self.find_reusable(attrs)
86 candidates = Container.
87 where_serialized(:command, attrs[:command]).
88 where('cwd = ?', attrs[:cwd]).
89 where_serialized(:environment, attrs[:environment]).
90 where('output_path = ?', attrs[:output_path]).
91 where('container_image = ?', attrs[:container_image]).
92 where_serialized(:mounts, attrs[:mounts]).
93 where_serialized(:runtime_constraints, attrs[:runtime_constraints])
95 # Check for Completed candidates whose output and log are both readable.
96 select_readable_pdh = Collection.
97 readable_by(current_user).
98 select(:portable_data_hash).
101 where(state: Complete).
103 where("log IN (#{select_readable_pdh})").
104 where("output IN (#{select_readable_pdh})").
105 order('finished_at ASC').
108 return usable if usable
110 # Check for Running candidates and return the most likely to finish sooner.
111 running = candidates.where(state: Running).
112 order('progress desc, started_at asc').limit(1).first
113 return running if not running.nil?
115 # Check for Locked or Queued ones and return the most likely to start first.
116 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
117 order('state asc, priority desc, created_at asc').limit(1).first
118 return locked_or_queued if not locked_or_queued.nil?
120 # No suitable candidate found.
126 if self.state == Locked
127 raise AlreadyLockedError
136 if self.state == Queued
137 raise InvalidStateTransitionError
144 def self.readable_by(*users_list)
145 if users_list.select { |u| u.is_admin }.any?
148 user_uuids = users_list.map { |u| u.uuid }
149 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
151 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
152 joins(:container_requests).
153 where("container_requests.uuid IN #{permitted} OR "+
154 "container_requests.owner_uuid IN (:uuids)",
159 [Complete, Cancelled].include?(self.state)
164 def fill_field_defaults
165 self.state ||= Queued
166 self.environment ||= {}
167 self.runtime_constraints ||= {}
171 self.scheduling_parameters ||= {}
174 def permission_to_create
175 current_user.andand.is_admin
178 def permission_to_update
179 # Override base permission check to allow auth_uuid to set progress and
180 # output (only). Whether it is legal to set progress and output in the current
181 # state has already been checked in validate_change.
182 current_user.andand.is_admin ||
183 (!current_api_client_authorization.nil? and
184 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
187 def ensure_owner_uuid_is_permitted
188 # Override base permission check to allow auth_uuid to set progress and
189 # output (only). Whether it is legal to set progress and output in the current
190 # state has already been checked in validate_change.
191 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
192 check_update_whitelist [:progress, :output]
199 if self.state_changed? and self.state == Running
200 self.started_at ||= db_current_time
203 if self.state_changed? and [Complete, Cancelled].include? self.state
204 self.finished_at ||= db_current_time
212 permitted.push(:owner_uuid, :command, :container_image, :cwd,
213 :environment, :mounts, :output_path, :priority,
214 :runtime_constraints, :scheduling_parameters)
219 permitted.push :priority
222 permitted.push :priority, :progress, :output
223 if self.state_changed?
224 permitted.push :started_at
228 if self.state_was == Running
229 permitted.push :finished_at, :output, :log, :exit_code
235 permitted.push :finished_at, :output, :log
237 permitted.push :finished_at
241 # The state_transitions check will add an error message for this
245 check_update_whitelist permitted
249 if [Locked, Running].include? self.state
250 # If the Container was already locked, locked_by_uuid must not
251 # changes. Otherwise, the current auth gets the lock.
252 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
257 # The caller can provide a new value for locked_by_uuid, but only
258 # if it's exactly what we expect. This allows a caller to perform
259 # an update like {"state":"Unlocked","locked_by_uuid":null}.
260 if self.locked_by_uuid_changed?
261 if self.locked_by_uuid != need_lock
262 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
265 self.locked_by_uuid = need_lock
269 # Output must exist and be readable by the current user. This is so
270 # that a container cannot "claim" a collection that it doesn't otherwise
271 # have access to just by setting the output field to the collection PDH.
273 c = Collection.unscoped do
275 readable_by(current_user).
276 where(portable_data_hash: self.output).
280 errors.add :output, "collection must exist and be readable by current user."
286 if self.auth_uuid_changed?
287 return errors.add :auth_uuid, 'is readonly'
289 if not [Locked, Running].include? self.state
291 self.auth.andand.update_attributes(expires_at: db_current_time)
298 cr = ContainerRequest.
299 where('container_uuid=? and priority>0', self.uuid).
300 order('priority desc').
303 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
305 self.auth = ApiClientAuthorization.
306 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
310 def sort_serialized_attrs
311 if self.environment_changed?
312 self.environment = self.class.deep_sort_hash(self.environment)
314 if self.mounts_changed?
315 self.mounts = self.class.deep_sort_hash(self.mounts)
317 if self.runtime_constraints_changed?
318 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
320 if self.scheduling_parameters_changed?
321 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
326 # This container is finished so finalize any associated container requests
327 # that are associated with this container.
328 if self.state_changed? and self.final?
329 act_as_system_user do
331 if self.state == Cancelled
332 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
334 retryable_requests = []
337 if retryable_requests.any?
339 command: self.command,
341 environment: self.environment,
342 output_path: self.output_path,
343 container_image: self.container_image,
345 runtime_constraints: self.runtime_constraints,
346 scheduling_parameters: self.scheduling_parameters
348 c = Container.create! c_attrs
349 retryable_requests.each do |cr|
351 # Use row locking because this increments container_count
352 cr.container_uuid = c.uuid
358 # Notify container requests associated with this container
359 ContainerRequest.where(container_uuid: uuid,
360 state: ContainerRequest::Committed).each do |cr|
364 # Try to cancel any outstanding container requests made by this container.
365 ContainerRequest.where(requesting_container_uuid: uuid,
366 state: ContainerRequest::Committed).each do |cr|