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 if users_list.select { |u| u.is_admin }.any?
303 user_uuids = users_list.map { |u| u.uuid }
304 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
306 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
307 joins(:container_requests).
308 where("container_requests.uuid IN #{permitted} OR "+
309 "container_requests.owner_uuid IN (:uuids)",
314 [Complete, Cancelled].include?(self.state)
319 def fill_field_defaults
320 self.state ||= Queued
321 self.environment ||= {}
322 self.runtime_constraints ||= {}
326 self.scheduling_parameters ||= {}
329 def permission_to_create
330 current_user.andand.is_admin
333 def permission_to_update
334 # Override base permission check to allow auth_uuid to set progress and
335 # output (only). Whether it is legal to set progress and output in the current
336 # state has already been checked in validate_change.
337 current_user.andand.is_admin ||
338 (!current_api_client_authorization.nil? and
339 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
342 def ensure_owner_uuid_is_permitted
343 # Override base permission check to allow auth_uuid to set progress and
344 # output (only). Whether it is legal to set progress and output in the current
345 # state has already been checked in validate_change.
346 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
347 check_update_whitelist [:progress, :output]
354 if self.state_changed? and self.state == Running
355 self.started_at ||= db_current_time
358 if self.state_changed? and [Complete, Cancelled].include? self.state
359 self.finished_at ||= db_current_time
367 permitted.push(:owner_uuid, :command, :container_image, :cwd,
368 :environment, :mounts, :output_path, :priority,
369 :runtime_constraints, :scheduling_parameters)
374 permitted.push :priority
377 permitted.push :priority, :progress, :output
378 if self.state_changed?
379 permitted.push :started_at
383 if self.state_was == Running
384 permitted.push :finished_at, :output, :log, :exit_code
390 permitted.push :finished_at, :output, :log
392 permitted.push :finished_at
396 # The state_transitions check will add an error message for this
400 check_update_whitelist permitted
404 if [Locked, Running].include? self.state
405 # If the Container was already locked, locked_by_uuid must not
406 # changes. Otherwise, the current auth gets the lock.
407 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
412 # The caller can provide a new value for locked_by_uuid, but only
413 # if it's exactly what we expect. This allows a caller to perform
414 # an update like {"state":"Unlocked","locked_by_uuid":null}.
415 if self.locked_by_uuid_changed?
416 if self.locked_by_uuid != need_lock
417 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
420 self.locked_by_uuid = need_lock
424 # Output must exist and be readable by the current user. This is so
425 # that a container cannot "claim" a collection that it doesn't otherwise
426 # have access to just by setting the output field to the collection PDH.
428 c = Collection.unscoped do
430 readable_by(current_user).
431 where(portable_data_hash: self.output).
435 errors.add :output, "collection must exist and be readable by current user."
441 if self.auth_uuid_changed?
442 return errors.add :auth_uuid, 'is readonly'
444 if not [Locked, Running].include? self.state
446 self.auth.andand.update_attributes(expires_at: db_current_time)
453 cr = ContainerRequest.
454 where('container_uuid=? and priority>0', self.uuid).
455 order('priority desc').
458 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
460 self.auth = ApiClientAuthorization.
461 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
465 def sort_serialized_attrs
466 if self.environment_changed?
467 self.environment = self.class.deep_sort_hash(self.environment)
469 if self.mounts_changed?
470 self.mounts = self.class.deep_sort_hash(self.mounts)
472 if self.runtime_constraints_changed?
473 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
475 if self.scheduling_parameters_changed?
476 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
481 # This container is finished so finalize any associated container requests
482 # that are associated with this container.
483 if self.state_changed? and self.final?
484 act_as_system_user do
486 if self.state == Cancelled
487 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
489 retryable_requests = []
492 if retryable_requests.any?
494 command: self.command,
496 environment: self.environment,
497 output_path: self.output_path,
498 container_image: self.container_image,
500 runtime_constraints: self.runtime_constraints,
501 scheduling_parameters: self.scheduling_parameters
503 c = Container.create! c_attrs
504 retryable_requests.each do |cr|
506 # Use row locking because this increments container_count
507 cr.container_uuid = c.uuid
513 # Notify container requests associated with this container
514 ContainerRequest.where(container_uuid: uuid,
515 state: ContainerRequest::Committed).each do |cr|
519 # Try to cancel any outstanding container requests made by this container.
520 ContainerRequest.where(requesting_container_uuid: uuid,
521 state: ContainerRequest::Committed).each do |cr|