1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'log_reuse_info'
6 require 'whitelist_update'
9 class Container < ArvadosModel
12 include CommonApiTemplate
13 include WhitelistUpdate
14 extend CurrentApiClient
18 serialize :environment, Hash
19 serialize :mounts, Hash
20 serialize :runtime_constraints, Hash
21 serialize :command, Array
22 serialize :scheduling_parameters, Hash
24 before_validation :fill_field_defaults, :if => :new_record?
25 before_validation :set_timestamps
26 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
27 validate :validate_state_change
28 validate :validate_change
29 validate :validate_lock
30 validate :validate_output
31 after_validation :assign_auth
32 before_save :sort_serialized_attrs
33 after_save :handle_completed
35 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
36 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
38 api_accessible :user, extend: :common do |t|
40 t.add :container_image
52 t.add :runtime_constraints
56 t.add :scheduling_parameters
59 # Supported states for a container
64 (Running = 'Running'),
65 (Complete = 'Complete'),
66 (Cancelled = 'Cancelled')
71 Queued => [Locked, Cancelled],
72 Locked => [Queued, Running, Cancelled],
73 Running => [Complete, Cancelled]
76 def self.limit_index_columns_read
85 if [Queued, Locked, Running].include? self.state
86 # Update the priority of this container to the maximum priority of any of
87 # its committed container requests and save the record.
88 self.priority = ContainerRequest.
89 where(container_uuid: uuid,
90 state: ContainerRequest::Committed).
96 # Create a new container (or find an existing one) to satisfy the
97 # given container request.
100 command: req.command,
102 environment: req.environment,
103 output_path: req.output_path,
104 container_image: resolve_container_image(req.container_image),
105 mounts: resolve_mounts(req.mounts),
106 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
107 scheduling_parameters: req.scheduling_parameters,
109 act_as_system_user do
110 if req.use_existing && (reusable = find_reusable(c_attrs))
113 Container.create!(c_attrs)
118 # Return a runtime_constraints hash that complies with requested but
119 # is suitable for saving in a container record, i.e., has specific
120 # values instead of ranges.
122 # Doing this as a step separate from other resolutions, like "git
123 # revision range to commit hash", makes sense only when there is no
124 # opportunity to reuse an existing container (e.g., container reuse
125 # is not implemented yet, or we have already found that no existing
126 # containers are suitable).
127 def self.resolve_runtime_constraints(runtime_constraints)
131 Rails.configuration.container_default_keep_cache_ram,
133 defaults.merge(runtime_constraints).each do |k, v|
143 # Return a mounts hash suitable for a Container, i.e., with every
144 # readonly collection UUID resolved to a PDH.
145 def self.resolve_mounts(mounts)
147 mounts.each do |k, mount|
150 if mount['kind'] != 'collection'
153 if (uuid = mount.delete 'uuid')
155 readable_by(current_user).
157 select(:portable_data_hash).
160 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
162 if mount['portable_data_hash'].nil?
163 # PDH not supplied by client
164 mount['portable_data_hash'] = c.portable_data_hash
165 elsif mount['portable_data_hash'] != c.portable_data_hash
166 # UUID and PDH supplied by client, but they don't agree
167 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"
174 # Return a container_image PDH suitable for a Container.
175 def self.resolve_container_image(container_image)
176 coll = Collection.for_latest_docker_image(container_image)
178 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
180 coll.portable_data_hash
183 def self.find_reusable(attrs)
184 log_reuse_info { "starting with #{Container.all.count} container records in database" }
185 candidates = Container.where_serialized(:command, attrs[:command])
186 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
188 candidates = candidates.where('cwd = ?', attrs[:cwd])
189 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
191 candidates = candidates.where_serialized(:environment, attrs[:environment])
192 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
194 candidates = candidates.where('output_path = ?', attrs[:output_path])
195 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
197 image = resolve_container_image(attrs[:container_image])
198 candidates = candidates.where('container_image = ?', image)
199 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
201 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
202 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
204 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
205 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
207 log_reuse_info { "checking for state=Complete with readable output and log..." }
209 select_readable_pdh = Collection.
210 readable_by(current_user).
211 select(:portable_data_hash).
214 usable = candidates.where(state: Complete, exit_code: 0)
215 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
217 usable = usable.where("log IN (#{select_readable_pdh})")
218 log_reuse_info(usable) { "with readable log" }
220 usable = usable.where("output IN (#{select_readable_pdh})")
221 log_reuse_info(usable) { "with readable output" }
223 usable = usable.order('finished_at ASC').limit(1).first
225 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
229 # Check for Running candidates and return the most likely to finish sooner.
230 log_reuse_info { "checking for state=Running..." }
231 running = candidates.where(state: Running).
232 order('progress desc, started_at asc').
235 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
238 log_reuse_info { "have no containers in Running state" }
241 # Check for Locked or Queued ones and return the most likely to start first.
242 locked_or_queued = candidates.
243 where("state IN (?)", [Locked, Queued]).
244 order('state asc, priority desc, created_at asc').
247 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
248 return locked_or_queued
250 log_reuse_info { "have no containers in Locked or Queued state" }
253 log_reuse_info { "done, no reusable container found" }
258 if self.state != Queued
259 raise LockFailedError.new("cannot lock when #{self.state}")
260 elsif self.priority <= 0
261 raise LockFailedError.new("cannot lock when priority<=0")
266 # Check invalid state transitions once before getting the lock
267 # (because it's cheaper that way) and once after getting the lock
268 # (because state might have changed while acquiring the lock).
272 reload(lock: 'FOR UPDATE NOWAIT')
274 raise LockFailedError.new("cannot lock: other transaction in progress")
277 update_attributes!(state: Locked)
281 def check_unlock_fail
282 if self.state != Locked
283 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
284 elsif self.locked_by_uuid != current_api_client_authorization.uuid
285 raise InvalidStateTransitionError.new("locked by a different token")
290 # Check invalid state transitions twice (see lock)
293 reload(lock: 'FOR UPDATE')
295 update_attributes!(state: Queued)
299 def self.readable_by(*users_list)
300 # Load optional keyword arguments, if they exist.
301 if users_list.last.is_a? Hash
302 kwargs = users_list.pop
306 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
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, :log
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|