1 require 'whitelist_update'
4 class Container < ArvadosModel
7 include CommonApiTemplate
8 include WhitelistUpdate
9 extend CurrentApiClient
12 serialize :environment, Hash
13 serialize :mounts, Hash
14 serialize :runtime_constraints, Hash
15 serialize :command, Array
16 serialize :scheduling_parameters, Hash
18 before_validation :fill_field_defaults, :if => :new_record?
19 before_validation :set_timestamps
20 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
21 validate :validate_state_change
22 validate :validate_change
23 validate :validate_lock
24 validate :validate_output
25 after_validation :assign_auth
26 before_save :sort_serialized_attrs
27 after_save :handle_completed
29 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
30 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
32 api_accessible :user, extend: :common do |t|
34 t.add :container_image
46 t.add :runtime_constraints
50 t.add :scheduling_parameters
53 # Supported states for a container
58 (Running = 'Running'),
59 (Complete = 'Complete'),
60 (Cancelled = 'Cancelled')
65 Queued => [Locked, Cancelled],
66 Locked => [Queued, Running, Cancelled],
67 Running => [Complete, Cancelled]
70 def self.limit_index_columns_read
79 if [Queued, Locked, Running].include? self.state
80 # Update the priority of this container to the maximum priority of any of
81 # its committed container requests and save the record.
82 self.priority = ContainerRequest.
83 where(container_uuid: uuid,
84 state: ContainerRequest::Committed).
90 # Create a new container (or find an existing one) to satisfy the
91 # given container request.
96 environment: req.environment,
97 output_path: req.output_path,
98 container_image: resolve_container_image(req.container_image),
99 mounts: resolve_mounts(req.mounts),
100 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
101 scheduling_parameters: req.scheduling_parameters,
103 act_as_system_user do
104 if req.use_existing && (reusable = find_reusable(c_attrs))
107 Container.create!(c_attrs)
112 # Return a runtime_constraints hash that complies with requested but
113 # is suitable for saving in a container record, i.e., has specific
114 # values instead of ranges.
116 # Doing this as a step separate from other resolutions, like "git
117 # revision range to commit hash", makes sense only when there is no
118 # opportunity to reuse an existing container (e.g., container reuse
119 # is not implemented yet, or we have already found that no existing
120 # containers are suitable).
121 def self.resolve_runtime_constraints(runtime_constraints)
125 Rails.configuration.container_default_keep_cache_ram,
127 defaults.merge(runtime_constraints).each do |k, v|
137 # Return a mounts hash suitable for a Container, i.e., with every
138 # readonly collection UUID resolved to a PDH.
139 def self.resolve_mounts(mounts)
141 mounts.each do |k, mount|
144 if mount['kind'] != 'collection'
147 if (uuid = mount.delete 'uuid')
149 readable_by(current_user).
151 select(:portable_data_hash).
154 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
156 if mount['portable_data_hash'].nil?
157 # PDH not supplied by client
158 mount['portable_data_hash'] = c.portable_data_hash
159 elsif mount['portable_data_hash'] != c.portable_data_hash
160 # UUID and PDH supplied by client, but they don't agree
161 raise ArgumentError.new "cannot mount collection #{uuid.inspect}: current portable_data_hash #{c.portable_data_hash.inspect} does not match #{c['portable_data_hash'].inspect} in request"
168 # Return a container_image PDH suitable for a Container.
169 def self.resolve_container_image(container_image)
170 coll = Collection.for_latest_docker_image(container_image)
172 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
174 coll.portable_data_hash
177 def self.find_reusable(attrs)
178 candidates = Container.
179 where_serialized(:command, attrs[:command]).
180 where('cwd = ?', attrs[:cwd]).
181 where_serialized(:environment, attrs[:environment]).
182 where('output_path = ?', attrs[:output_path]).
183 where('container_image = ?', resolve_container_image(attrs[:container_image])).
184 where_serialized(:mounts, resolve_mounts(attrs[:mounts])).
185 where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
187 # Check for Completed candidates whose output and log are both readable.
188 select_readable_pdh = Collection.
189 readable_by(current_user).
190 select(:portable_data_hash).
193 where(state: Complete).
195 where("log IN (#{select_readable_pdh})").
196 where("output IN (#{select_readable_pdh})").
197 order('finished_at ASC').
200 return usable if usable
202 # Check for Running candidates and return the most likely to finish sooner.
203 running = candidates.where(state: Running).
204 order('progress desc, started_at asc').limit(1).first
205 return running if not running.nil?
207 # Check for Locked or Queued ones and return the most likely to start first.
208 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
209 order('state asc, priority desc, created_at asc').limit(1).first
210 return locked_or_queued if not locked_or_queued.nil?
212 # No suitable candidate found.
217 if self.state != Queued
218 raise LockFailedError.new("cannot lock when #{self.state}")
219 elsif self.priority <= 0
220 raise LockFailedError.new("cannot lock when priority<=0")
225 # Check invalid state transitions once before getting the lock
226 # (because it's cheaper that way) and once after getting the lock
227 # (because state might have changed while acquiring the lock).
230 reload(lock: 'FOR UPDATE NOWAIT')
232 raise LockFailedError.new("cannot lock: other transaction in progress")
235 update_attributes!(state: Locked)
238 def check_unlock_fail
239 if self.state != Locked
240 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
241 elsif self.locked_by_uuid != current_api_client_authorization.uuid
242 raise InvalidStateTransitionError.new("locked by a different token")
247 # Check invalid state transitions twice (see lock)
249 reload(lock: 'FOR UPDATE')
251 update_attributes!(state: Queued)
254 def self.readable_by(*users_list)
255 if users_list.select { |u| u.is_admin }.any?
258 user_uuids = users_list.map { |u| u.uuid }
259 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
261 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
262 joins(:container_requests).
263 where("container_requests.uuid IN #{permitted} OR "+
264 "container_requests.owner_uuid IN (:uuids)",
269 [Complete, Cancelled].include?(self.state)
274 def fill_field_defaults
275 self.state ||= Queued
276 self.environment ||= {}
277 self.runtime_constraints ||= {}
281 self.scheduling_parameters ||= {}
284 def permission_to_create
285 current_user.andand.is_admin
288 def permission_to_update
289 # Override base permission check to allow auth_uuid to set progress and
290 # output (only). Whether it is legal to set progress and output in the current
291 # state has already been checked in validate_change.
292 current_user.andand.is_admin ||
293 (!current_api_client_authorization.nil? and
294 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
297 def ensure_owner_uuid_is_permitted
298 # Override base permission check to allow auth_uuid to set progress and
299 # output (only). Whether it is legal to set progress and output in the current
300 # state has already been checked in validate_change.
301 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
302 check_update_whitelist [:progress, :output]
309 if self.state_changed? and self.state == Running
310 self.started_at ||= db_current_time
313 if self.state_changed? and [Complete, Cancelled].include? self.state
314 self.finished_at ||= db_current_time
322 permitted.push(:owner_uuid, :command, :container_image, :cwd,
323 :environment, :mounts, :output_path, :priority,
324 :runtime_constraints, :scheduling_parameters)
329 permitted.push :priority
332 permitted.push :priority, :progress, :output
333 if self.state_changed?
334 permitted.push :started_at
338 if self.state_was == Running
339 permitted.push :finished_at, :output, :log, :exit_code
345 permitted.push :finished_at, :output, :log
347 permitted.push :finished_at
351 # The state_transitions check will add an error message for this
355 check_update_whitelist permitted
359 if [Locked, Running].include? self.state
360 # If the Container was already locked, locked_by_uuid must not
361 # changes. Otherwise, the current auth gets the lock.
362 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
367 # The caller can provide a new value for locked_by_uuid, but only
368 # if it's exactly what we expect. This allows a caller to perform
369 # an update like {"state":"Unlocked","locked_by_uuid":null}.
370 if self.locked_by_uuid_changed?
371 if self.locked_by_uuid != need_lock
372 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
375 self.locked_by_uuid = need_lock
379 # Output must exist and be readable by the current user. This is so
380 # that a container cannot "claim" a collection that it doesn't otherwise
381 # have access to just by setting the output field to the collection PDH.
383 c = Collection.unscoped do
385 readable_by(current_user).
386 where(portable_data_hash: self.output).
390 errors.add :output, "collection must exist and be readable by current user."
396 if self.auth_uuid_changed?
397 return errors.add :auth_uuid, 'is readonly'
399 if not [Locked, Running].include? self.state
401 self.auth.andand.update_attributes(expires_at: db_current_time)
408 cr = ContainerRequest.
409 where('container_uuid=? and priority>0', self.uuid).
410 order('priority desc').
413 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
415 self.auth = ApiClientAuthorization.
416 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
420 def sort_serialized_attrs
421 if self.environment_changed?
422 self.environment = self.class.deep_sort_hash(self.environment)
424 if self.mounts_changed?
425 self.mounts = self.class.deep_sort_hash(self.mounts)
427 if self.runtime_constraints_changed?
428 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
430 if self.scheduling_parameters_changed?
431 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
436 # This container is finished so finalize any associated container requests
437 # that are associated with this container.
438 if self.state_changed? and self.final?
439 act_as_system_user do
441 if self.state == Cancelled
442 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
444 retryable_requests = []
447 if retryable_requests.any?
449 command: self.command,
451 environment: self.environment,
452 output_path: self.output_path,
453 container_image: self.container_image,
455 runtime_constraints: self.runtime_constraints,
456 scheduling_parameters: self.scheduling_parameters
458 c = Container.create! c_attrs
459 retryable_requests.each do |cr|
461 # Use row locking because this increments container_count
462 cr.container_uuid = c.uuid
468 # Notify container requests associated with this container
469 ContainerRequest.where(container_uuid: uuid,
470 state: ContainerRequest::Committed).each do |cr|
474 # Try to cancel any outstanding container requests made by this container.
475 ContainerRequest.where(requesting_container_uuid: uuid,
476 state: ContainerRequest::Committed).each do |cr|