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]
69 def self.limit_index_columns_read
78 if [Queued, Locked, Running].include? self.state
79 # Update the priority of this container to the maximum priority of any of
80 # its committed container requests and save the record.
81 self.priority = ContainerRequest.
82 where(container_uuid: uuid,
83 state: ContainerRequest::Committed).
89 # Create a new container (or find an existing one) to satisfy the
90 # given container request.
95 environment: req.environment,
96 output_path: req.output_path,
97 container_image: resolve_container_image(req.container_image),
98 mounts: resolve_mounts(req.mounts),
99 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
100 scheduling_parameters: req.scheduling_parameters,
102 act_as_system_user do
103 if req.use_existing && (reusable = find_reusable(c_attrs))
106 Container.create!(c_attrs)
111 # Return a runtime_constraints hash that complies with requested but
112 # is suitable for saving in a container record, i.e., has specific
113 # values instead of ranges.
115 # Doing this as a step separate from other resolutions, like "git
116 # revision range to commit hash", makes sense only when there is no
117 # opportunity to reuse an existing container (e.g., container reuse
118 # is not implemented yet, or we have already found that no existing
119 # containers are suitable).
120 def self.resolve_runtime_constraints(runtime_constraints)
124 Rails.configuration.container_default_keep_cache_ram,
126 defaults.merge(runtime_constraints).each do |k, v|
136 # Return a mounts hash suitable for a Container, i.e., with every
137 # readonly collection UUID resolved to a PDH.
138 def self.resolve_mounts(mounts)
140 mounts.each do |k, mount|
143 if mount['kind'] != 'collection'
146 if (uuid = mount.delete 'uuid')
148 readable_by(current_user).
150 select(:portable_data_hash).
153 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
155 if mount['portable_data_hash'].nil?
156 # PDH not supplied by client
157 mount['portable_data_hash'] = c.portable_data_hash
158 elsif mount['portable_data_hash'] != c.portable_data_hash
159 # UUID and PDH supplied by client, but they don't agree
160 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"
167 # Return a container_image PDH suitable for a Container.
168 def self.resolve_container_image(container_image)
169 coll = Collection.for_latest_docker_image(container_image)
171 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
173 coll.portable_data_hash
176 def self.find_reusable(attrs)
177 candidates = Container.
178 where_serialized(:command, attrs[:command]).
179 where('cwd = ?', attrs[:cwd]).
180 where_serialized(:environment, attrs[:environment]).
181 where('output_path = ?', attrs[:output_path]).
182 where('container_image = ?', resolve_container_image(attrs[:container_image])).
183 where_serialized(:mounts, resolve_mounts(attrs[:mounts])).
184 where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
186 # Check for Completed candidates whose output and log are both readable.
187 select_readable_pdh = Collection.
188 readable_by(current_user).
189 select(:portable_data_hash).
192 where(state: Complete).
194 where("log IN (#{select_readable_pdh})").
195 where("output IN (#{select_readable_pdh})").
196 order('finished_at ASC').
199 return usable if usable
201 # Check for Running candidates and return the most likely to finish sooner.
202 running = candidates.where(state: Running).
203 order('progress desc, started_at asc').limit(1).first
204 return running if not running.nil?
206 # Check for Locked or Queued ones and return the most likely to start first.
207 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
208 order('state asc, priority desc, created_at asc').limit(1).first
209 return locked_or_queued if not locked_or_queued.nil?
211 # No suitable candidate found.
217 if self.state == Locked
218 raise AlreadyLockedError
227 if self.state == Queued
228 raise InvalidStateTransitionError
235 def self.readable_by(*users_list)
236 if users_list.select { |u| u.is_admin }.any?
239 user_uuids = users_list.map { |u| u.uuid }
240 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
242 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
243 joins(:container_requests).
244 where("container_requests.uuid IN #{permitted} OR "+
245 "container_requests.owner_uuid IN (:uuids)",
250 [Complete, Cancelled].include?(self.state)
255 def fill_field_defaults
256 self.state ||= Queued
257 self.environment ||= {}
258 self.runtime_constraints ||= {}
262 self.scheduling_parameters ||= {}
265 def permission_to_create
266 current_user.andand.is_admin
269 def permission_to_update
270 # Override base permission check to allow auth_uuid to set progress and
271 # output (only). Whether it is legal to set progress and output in the current
272 # state has already been checked in validate_change.
273 current_user.andand.is_admin ||
274 (!current_api_client_authorization.nil? and
275 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
278 def ensure_owner_uuid_is_permitted
279 # Override base permission check to allow auth_uuid to set progress and
280 # output (only). Whether it is legal to set progress and output in the current
281 # state has already been checked in validate_change.
282 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
283 check_update_whitelist [:progress, :output]
290 if self.state_changed? and self.state == Running
291 self.started_at ||= db_current_time
294 if self.state_changed? and [Complete, Cancelled].include? self.state
295 self.finished_at ||= db_current_time
303 permitted.push(:owner_uuid, :command, :container_image, :cwd,
304 :environment, :mounts, :output_path, :priority,
305 :runtime_constraints, :scheduling_parameters)
310 permitted.push :priority
313 permitted.push :priority, :progress, :output
314 if self.state_changed?
315 permitted.push :started_at
319 if self.state_was == Running
320 permitted.push :finished_at, :output, :log, :exit_code
326 permitted.push :finished_at, :output, :log
328 permitted.push :finished_at
332 # The state_transitions check will add an error message for this
336 check_update_whitelist permitted
340 if [Locked, Running].include? self.state
341 # If the Container was already locked, locked_by_uuid must not
342 # changes. Otherwise, the current auth gets the lock.
343 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
348 # The caller can provide a new value for locked_by_uuid, but only
349 # if it's exactly what we expect. This allows a caller to perform
350 # an update like {"state":"Unlocked","locked_by_uuid":null}.
351 if self.locked_by_uuid_changed?
352 if self.locked_by_uuid != need_lock
353 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
356 self.locked_by_uuid = need_lock
360 # Output must exist and be readable by the current user. This is so
361 # that a container cannot "claim" a collection that it doesn't otherwise
362 # have access to just by setting the output field to the collection PDH.
364 c = Collection.unscoped do
366 readable_by(current_user).
367 where(portable_data_hash: self.output).
371 errors.add :output, "collection must exist and be readable by current user."
377 if self.auth_uuid_changed?
378 return errors.add :auth_uuid, 'is readonly'
380 if not [Locked, Running].include? self.state
382 self.auth.andand.update_attributes(expires_at: db_current_time)
389 cr = ContainerRequest.
390 where('container_uuid=? and priority>0', self.uuid).
391 order('priority desc').
394 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
396 self.auth = ApiClientAuthorization.
397 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
401 def sort_serialized_attrs
402 if self.environment_changed?
403 self.environment = self.class.deep_sort_hash(self.environment)
405 if self.mounts_changed?
406 self.mounts = self.class.deep_sort_hash(self.mounts)
408 if self.runtime_constraints_changed?
409 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
411 if self.scheduling_parameters_changed?
412 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
417 # This container is finished so finalize any associated container requests
418 # that are associated with this container.
419 if self.state_changed? and self.final?
420 act_as_system_user do
422 if self.state == Cancelled
423 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
425 retryable_requests = []
428 if retryable_requests.any?
430 command: self.command,
432 environment: self.environment,
433 output_path: self.output_path,
434 container_image: self.container_image,
436 runtime_constraints: self.runtime_constraints,
437 scheduling_parameters: self.scheduling_parameters
439 c = Container.create! c_attrs
440 retryable_requests.each do |cr|
442 # Use row locking because this increments container_count
443 cr.container_uuid = c.uuid
449 # Notify container requests associated with this container
450 ContainerRequest.where(container_uuid: uuid,
451 state: ContainerRequest::Committed).each do |cr|
455 # Try to cancel any outstanding container requests made by this container.
456 ContainerRequest.where(requesting_container_uuid: uuid,
457 state: ContainerRequest::Committed).each do |cr|