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
34 after_save :propagate_priority
36 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
37 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
39 api_accessible :user, extend: :common do |t|
41 t.add :container_image
53 t.add :runtime_constraints
57 t.add :scheduling_parameters
60 # Supported states for a container
65 (Running = 'Running'),
66 (Complete = 'Complete'),
67 (Cancelled = 'Cancelled')
72 Queued => [Locked, Cancelled],
73 Locked => [Queued, Running, Cancelled],
74 Running => [Complete, Cancelled]
77 def self.limit_index_columns_read
86 if [Queued, Locked, Running].include? self.state
87 # Update the priority of this container to the maximum priority of any of
88 # its committed container requests and save the record.
89 self.priority = ContainerRequest.
90 where(container_uuid: uuid,
91 state: ContainerRequest::Committed).
97 def propagate_priority
98 if self.priority_changed?
100 # Update the priority of child container requests to match new priority
101 # of the parent container.
102 ContainerRequest.where(requesting_container_uuid: self.uuid,
103 state: ContainerRequest::Committed).each do |cr|
104 cr.priority = self.priority
111 # Create a new container (or find an existing one) to satisfy the
112 # given container request.
113 def self.resolve(req)
115 command: req.command,
117 environment: req.environment,
118 output_path: req.output_path,
119 container_image: resolve_container_image(req.container_image),
120 mounts: resolve_mounts(req.mounts),
121 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
122 scheduling_parameters: req.scheduling_parameters,
124 act_as_system_user do
125 if req.use_existing && (reusable = find_reusable(c_attrs))
128 Container.create!(c_attrs)
133 # Return a runtime_constraints hash that complies with requested but
134 # is suitable for saving in a container record, i.e., has specific
135 # values instead of ranges.
137 # Doing this as a step separate from other resolutions, like "git
138 # revision range to commit hash", makes sense only when there is no
139 # opportunity to reuse an existing container (e.g., container reuse
140 # is not implemented yet, or we have already found that no existing
141 # containers are suitable).
142 def self.resolve_runtime_constraints(runtime_constraints)
146 Rails.configuration.container_default_keep_cache_ram,
148 defaults.merge(runtime_constraints).each do |k, v|
158 # Return a mounts hash suitable for a Container, i.e., with every
159 # readonly collection UUID resolved to a PDH.
160 def self.resolve_mounts(mounts)
162 mounts.each do |k, mount|
165 if mount['kind'] != 'collection'
168 if (uuid = mount.delete 'uuid')
170 readable_by(current_user).
172 select(:portable_data_hash).
175 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
177 if mount['portable_data_hash'].nil?
178 # PDH not supplied by client
179 mount['portable_data_hash'] = c.portable_data_hash
180 elsif mount['portable_data_hash'] != c.portable_data_hash
181 # UUID and PDH supplied by client, but they don't agree
182 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"
189 # Return a container_image PDH suitable for a Container.
190 def self.resolve_container_image(container_image)
191 coll = Collection.for_latest_docker_image(container_image)
193 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
195 coll.portable_data_hash
198 def self.find_reusable(attrs)
199 log_reuse_info { "starting with #{Container.all.count} container records in database" }
200 candidates = Container.where_serialized(:command, attrs[:command])
201 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
203 candidates = candidates.where('cwd = ?', attrs[:cwd])
204 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
206 candidates = candidates.where_serialized(:environment, attrs[:environment])
207 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
209 candidates = candidates.where('output_path = ?', attrs[:output_path])
210 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
212 image = resolve_container_image(attrs[:container_image])
213 candidates = candidates.where('container_image = ?', image)
214 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
216 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
217 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
219 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
220 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
222 log_reuse_info { "checking for state=Complete with readable output and log..." }
224 select_readable_pdh = Collection.
225 readable_by(current_user).
226 select(:portable_data_hash).
229 usable = candidates.where(state: Complete, exit_code: 0)
230 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
232 usable = usable.where("log IN (#{select_readable_pdh})")
233 log_reuse_info(usable) { "with readable log" }
235 usable = usable.where("output IN (#{select_readable_pdh})")
236 log_reuse_info(usable) { "with readable output" }
238 usable = usable.order('finished_at ASC').limit(1).first
240 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
244 # Check for Running candidates and return the most likely to finish sooner.
245 log_reuse_info { "checking for state=Running..." }
246 running = candidates.where(state: Running).
247 order('progress desc, started_at asc').
250 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
253 log_reuse_info { "have no containers in Running state" }
256 # Check for Locked or Queued ones and return the most likely to start first.
257 locked_or_queued = candidates.
258 where("state IN (?)", [Locked, Queued]).
259 order('state asc, priority desc, created_at asc').
262 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
263 return locked_or_queued
265 log_reuse_info { "have no containers in Locked or Queued state" }
268 log_reuse_info { "done, no reusable container found" }
273 if self.state != Queued
274 raise LockFailedError.new("cannot lock when #{self.state}")
275 elsif self.priority <= 0
276 raise LockFailedError.new("cannot lock when priority<=0")
281 # Check invalid state transitions once before getting the lock
282 # (because it's cheaper that way) and once after getting the lock
283 # (because state might have changed while acquiring the lock).
287 reload(lock: 'FOR UPDATE NOWAIT')
289 raise LockFailedError.new("cannot lock: other transaction in progress")
292 update_attributes!(state: Locked)
296 def check_unlock_fail
297 if self.state != Locked
298 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
299 elsif self.locked_by_uuid != current_api_client_authorization.uuid
300 raise InvalidStateTransitionError.new("locked by a different token")
305 # Check invalid state transitions twice (see lock)
308 reload(lock: 'FOR UPDATE')
310 update_attributes!(state: Queued)
314 def self.readable_by(*users_list)
315 # Load optional keyword arguments, if they exist.
316 if users_list.last.is_a? Hash
317 kwargs = users_list.pop
321 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
325 [Complete, Cancelled].include?(self.state)
330 def fill_field_defaults
331 self.state ||= Queued
332 self.environment ||= {}
333 self.runtime_constraints ||= {}
337 self.scheduling_parameters ||= {}
340 def permission_to_create
341 current_user.andand.is_admin
344 def permission_to_update
345 # Override base permission check to allow auth_uuid to set progress and
346 # output (only). Whether it is legal to set progress and output in the current
347 # state has already been checked in validate_change.
348 current_user.andand.is_admin ||
349 (!current_api_client_authorization.nil? and
350 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
353 def ensure_owner_uuid_is_permitted
354 # Override base permission check to allow auth_uuid to set progress and
355 # output (only). Whether it is legal to set progress and output in the current
356 # state has already been checked in validate_change.
357 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
358 check_update_whitelist [:progress, :output]
365 if self.state_changed? and self.state == Running
366 self.started_at ||= db_current_time
369 if self.state_changed? and [Complete, Cancelled].include? self.state
370 self.finished_at ||= db_current_time
378 permitted.push(:owner_uuid, :command, :container_image, :cwd,
379 :environment, :mounts, :output_path, :priority,
380 :runtime_constraints, :scheduling_parameters)
385 permitted.push :priority
388 permitted.push :priority, :progress, :output
389 if self.state_changed?
390 permitted.push :started_at
394 if self.state_was == Running
395 permitted.push :finished_at, :output, :log, :exit_code
401 permitted.push :finished_at, :output, :log
403 permitted.push :finished_at, :log
407 # The state_transitions check will add an error message for this
411 check_update_whitelist permitted
415 if [Locked, Running].include? self.state
416 # If the Container was already locked, locked_by_uuid must not
417 # changes. Otherwise, the current auth gets the lock.
418 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
423 # The caller can provide a new value for locked_by_uuid, but only
424 # if it's exactly what we expect. This allows a caller to perform
425 # an update like {"state":"Unlocked","locked_by_uuid":null}.
426 if self.locked_by_uuid_changed?
427 if self.locked_by_uuid != need_lock
428 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
431 self.locked_by_uuid = need_lock
435 # Output must exist and be readable by the current user. This is so
436 # that a container cannot "claim" a collection that it doesn't otherwise
437 # have access to just by setting the output field to the collection PDH.
439 c = Collection.unscoped do
441 readable_by(current_user).
442 where(portable_data_hash: self.output).
446 errors.add :output, "collection must exist and be readable by current user."
452 if self.auth_uuid_changed?
453 return errors.add :auth_uuid, 'is readonly'
455 if not [Locked, Running].include? self.state
457 self.auth.andand.update_attributes(expires_at: db_current_time)
464 cr = ContainerRequest.
465 where('container_uuid=? and priority>0', self.uuid).
466 order('priority desc').
469 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
471 self.auth = ApiClientAuthorization.
472 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
476 def sort_serialized_attrs
477 if self.environment_changed?
478 self.environment = self.class.deep_sort_hash(self.environment)
480 if self.mounts_changed?
481 self.mounts = self.class.deep_sort_hash(self.mounts)
483 if self.runtime_constraints_changed?
484 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
486 if self.scheduling_parameters_changed?
487 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
492 # This container is finished so finalize any associated container requests
493 # that are associated with this container.
494 if self.state_changed? and self.final?
495 act_as_system_user do
497 if self.state == Cancelled
498 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
500 retryable_requests = []
503 if retryable_requests.any?
505 command: self.command,
507 environment: self.environment,
508 output_path: self.output_path,
509 container_image: self.container_image,
511 runtime_constraints: self.runtime_constraints,
512 scheduling_parameters: self.scheduling_parameters
514 c = Container.create! c_attrs
515 retryable_requests.each do |cr|
517 # Use row locking because this increments container_count
518 cr.container_uuid = c.uuid
524 # Notify container requests associated with this container
525 ContainerRequest.where(container_uuid: uuid,
526 state: ContainerRequest::Committed).each do |cr|
530 # Try to cancel any outstanding container requests made by this container.
531 ContainerRequest.where(requesting_container_uuid: uuid,
532 state: ContainerRequest::Committed).each do |cr|