1 require 'log_reuse_info'
2 require 'whitelist_update'
5 class Container < ArvadosModel
8 include CommonApiTemplate
9 include WhitelistUpdate
10 extend CurrentApiClient
14 serialize :environment, Hash
15 serialize :mounts, Hash
16 serialize :runtime_constraints, Hash
17 serialize :command, Array
18 serialize :scheduling_parameters, Hash
20 before_validation :fill_field_defaults, :if => :new_record?
21 before_validation :set_timestamps
22 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
23 validate :validate_state_change
24 validate :validate_change
25 validate :validate_lock
26 validate :validate_output
27 after_validation :assign_auth
28 before_save :sort_serialized_attrs
29 after_save :handle_completed
31 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
32 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
34 api_accessible :user, extend: :common do |t|
36 t.add :container_image
48 t.add :runtime_constraints
52 t.add :scheduling_parameters
55 # Supported states for a container
60 (Running = 'Running'),
61 (Complete = 'Complete'),
62 (Cancelled = 'Cancelled')
67 Queued => [Locked, Cancelled],
68 Locked => [Queued, Running, Cancelled],
69 Running => [Complete, Cancelled]
72 def self.limit_index_columns_read
81 if [Queued, Locked, Running].include? self.state
82 # Update the priority of this container to the maximum priority of any of
83 # its committed container requests and save the record.
84 self.priority = ContainerRequest.
85 where(container_uuid: uuid,
86 state: ContainerRequest::Committed).
92 # Create a new container (or find an existing one) to satisfy the
93 # given container request.
98 environment: req.environment,
99 output_path: req.output_path,
100 container_image: resolve_container_image(req.container_image),
101 mounts: resolve_mounts(req.mounts),
102 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
103 scheduling_parameters: req.scheduling_parameters,
105 act_as_system_user do
106 if req.use_existing && (reusable = find_reusable(c_attrs))
109 Container.create!(c_attrs)
114 # Return a runtime_constraints hash that complies with requested but
115 # is suitable for saving in a container record, i.e., has specific
116 # values instead of ranges.
118 # Doing this as a step separate from other resolutions, like "git
119 # revision range to commit hash", makes sense only when there is no
120 # opportunity to reuse an existing container (e.g., container reuse
121 # is not implemented yet, or we have already found that no existing
122 # containers are suitable).
123 def self.resolve_runtime_constraints(runtime_constraints)
127 Rails.configuration.container_default_keep_cache_ram,
129 defaults.merge(runtime_constraints).each do |k, v|
139 # Return a mounts hash suitable for a Container, i.e., with every
140 # readonly collection UUID resolved to a PDH.
141 def self.resolve_mounts(mounts)
143 mounts.each do |k, mount|
146 if mount['kind'] != 'collection'
149 if (uuid = mount.delete 'uuid')
151 readable_by(current_user).
153 select(:portable_data_hash).
156 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
158 if mount['portable_data_hash'].nil?
159 # PDH not supplied by client
160 mount['portable_data_hash'] = c.portable_data_hash
161 elsif mount['portable_data_hash'] != c.portable_data_hash
162 # UUID and PDH supplied by client, but they don't agree
163 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"
170 # Return a container_image PDH suitable for a Container.
171 def self.resolve_container_image(container_image)
172 coll = Collection.for_latest_docker_image(container_image)
174 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
176 coll.portable_data_hash
179 def self.find_reusable(attrs)
180 log_reuse_info { "starting with #{Container.all.count} container records in database" }
181 candidates = Container.where_serialized(:command, attrs[:command])
182 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
184 candidates = candidates.where('cwd = ?', attrs[:cwd])
185 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
187 candidates = candidates.where_serialized(:environment, attrs[:environment])
188 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
190 candidates = candidates.where('output_path = ?', attrs[:output_path])
191 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
193 image = resolve_container_image(attrs[:container_image])
194 candidates = candidates.where('container_image = ?', image)
195 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
197 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
198 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
200 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
201 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
203 log_reuse_info { "checking for state=Complete with readable output and log..." }
205 select_readable_pdh = Collection.
206 readable_by(current_user).
207 select(:portable_data_hash).
210 usable = candidates.where(state: Complete, exit_code: 0)
211 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
213 usable = usable.where("log IN (#{select_readable_pdh})")
214 log_reuse_info(usable) { "with readable log" }
216 usable = usable.where("output IN (#{select_readable_pdh})")
217 log_reuse_info(usable) { "with readable output" }
219 usable = usable.order('finished_at ASC').limit(1).first
221 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
225 # Check for Running candidates and return the most likely to finish sooner.
226 log_reuse_info { "checking for state=Running..." }
227 running = candidates.where(state: Running).
228 order('progress desc, started_at asc').
231 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
234 log_reuse_info { "have no containers in Running state" }
237 # Check for Locked or Queued ones and return the most likely to start first.
238 locked_or_queued = candidates.
239 where("state IN (?)", [Locked, Queued]).
240 order('state asc, priority desc, created_at asc').
243 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
244 return locked_or_queued
246 log_reuse_info { "have no containers in Locked or Queued state" }
249 log_reuse_info { "done, no reusable container found" }
254 if self.state != Queued
255 raise LockFailedError.new("cannot lock when #{self.state}")
256 elsif self.priority <= 0
257 raise LockFailedError.new("cannot lock when priority<=0")
262 # Check invalid state transitions once before getting the lock
263 # (because it's cheaper that way) and once after getting the lock
264 # (because state might have changed while acquiring the lock).
268 reload(lock: 'FOR UPDATE NOWAIT')
270 raise LockFailedError.new("cannot lock: other transaction in progress")
273 update_attributes!(state: Locked)
277 def check_unlock_fail
278 if self.state != Locked
279 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
280 elsif self.locked_by_uuid != current_api_client_authorization.uuid
281 raise InvalidStateTransitionError.new("locked by a different token")
286 # Check invalid state transitions twice (see lock)
289 reload(lock: 'FOR UPDATE')
291 update_attributes!(state: Queued)
295 def self.readable_by(*users_list)
296 if users_list.select { |u| u.is_admin }.any?
299 user_uuids = users_list.map { |u| u.uuid }
300 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
302 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
303 joins(:container_requests).
304 where("container_requests.uuid IN #{permitted} OR "+
305 "container_requests.owner_uuid IN (:uuids)",
310 [Complete, Cancelled].include?(self.state)
315 def fill_field_defaults
316 self.state ||= Queued
317 self.environment ||= {}
318 self.runtime_constraints ||= {}
322 self.scheduling_parameters ||= {}
325 def permission_to_create
326 current_user.andand.is_admin
329 def permission_to_update
330 # Override base permission check to allow auth_uuid to set progress and
331 # output (only). Whether it is legal to set progress and output in the current
332 # state has already been checked in validate_change.
333 current_user.andand.is_admin ||
334 (!current_api_client_authorization.nil? and
335 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
338 def ensure_owner_uuid_is_permitted
339 # Override base permission check to allow auth_uuid to set progress and
340 # output (only). Whether it is legal to set progress and output in the current
341 # state has already been checked in validate_change.
342 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
343 check_update_whitelist [:progress, :output]
350 if self.state_changed? and self.state == Running
351 self.started_at ||= db_current_time
354 if self.state_changed? and [Complete, Cancelled].include? self.state
355 self.finished_at ||= db_current_time
363 permitted.push(:owner_uuid, :command, :container_image, :cwd,
364 :environment, :mounts, :output_path, :priority,
365 :runtime_constraints, :scheduling_parameters)
370 permitted.push :priority
373 permitted.push :priority, :progress, :output
374 if self.state_changed?
375 permitted.push :started_at
379 if self.state_was == Running
380 permitted.push :finished_at, :output, :log, :exit_code
386 permitted.push :finished_at, :output, :log
388 permitted.push :finished_at
392 # The state_transitions check will add an error message for this
396 check_update_whitelist permitted
400 if [Locked, Running].include? self.state
401 # If the Container was already locked, locked_by_uuid must not
402 # changes. Otherwise, the current auth gets the lock.
403 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
408 # The caller can provide a new value for locked_by_uuid, but only
409 # if it's exactly what we expect. This allows a caller to perform
410 # an update like {"state":"Unlocked","locked_by_uuid":null}.
411 if self.locked_by_uuid_changed?
412 if self.locked_by_uuid != need_lock
413 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
416 self.locked_by_uuid = need_lock
420 # Output must exist and be readable by the current user. This is so
421 # that a container cannot "claim" a collection that it doesn't otherwise
422 # have access to just by setting the output field to the collection PDH.
424 c = Collection.unscoped do
426 readable_by(current_user).
427 where(portable_data_hash: self.output).
431 errors.add :output, "collection must exist and be readable by current user."
437 if self.auth_uuid_changed?
438 return errors.add :auth_uuid, 'is readonly'
440 if not [Locked, Running].include? self.state
442 self.auth.andand.update_attributes(expires_at: db_current_time)
449 cr = ContainerRequest.
450 where('container_uuid=? and priority>0', self.uuid).
451 order('priority desc').
454 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
456 self.auth = ApiClientAuthorization.
457 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
461 def sort_serialized_attrs
462 if self.environment_changed?
463 self.environment = self.class.deep_sort_hash(self.environment)
465 if self.mounts_changed?
466 self.mounts = self.class.deep_sort_hash(self.mounts)
468 if self.runtime_constraints_changed?
469 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
471 if self.scheduling_parameters_changed?
472 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
477 # This container is finished so finalize any associated container requests
478 # that are associated with this container.
479 if self.state_changed? and self.final?
480 act_as_system_user do
482 if self.state == Cancelled
483 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
485 retryable_requests = []
488 if retryable_requests.any?
490 command: self.command,
492 environment: self.environment,
493 output_path: self.output_path,
494 container_image: self.container_image,
496 runtime_constraints: self.runtime_constraints,
497 scheduling_parameters: self.scheduling_parameters
499 c = Container.create! c_attrs
500 retryable_requests.each do |cr|
502 # Use row locking because this increments container_count
503 cr.container_uuid = c.uuid
509 # Notify container requests associated with this container
510 ContainerRequest.where(container_uuid: uuid,
511 state: ContainerRequest::Committed).each do |cr|
515 # Try to cancel any outstanding container requests made by this container.
516 ContainerRequest.where(requesting_container_uuid: uuid,
517 state: ContainerRequest::Committed).each do |cr|