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
10 include ArvadosModelUpdates
13 include CommonApiTemplate
14 include WhitelistUpdate
15 extend CurrentApiClient
19 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
20 # already know how to properly treat them.
21 attribute :secret_mounts, :jsonbHash, default: {}
22 attribute :runtime_status, :jsonbHash, default: {}
23 attribute :runtime_auth_scopes, :jsonbArray, default: []
24 attribute :output_storage_classes, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
25 attribute :output_properties, :jsonbHash, default: {}
27 serialize :environment, Hash
28 serialize :mounts, Hash
29 serialize :runtime_constraints, Hash
30 serialize :command, Array
31 serialize :scheduling_parameters, Hash
33 after_find :fill_container_defaults_after_find
34 before_validation :fill_field_defaults, :if => :new_record?
35 before_validation :set_timestamps
36 before_validation :check_lock
37 before_validation :check_unlock
38 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
39 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
40 validate :validate_runtime_status
41 validate :validate_state_change
42 validate :validate_change
43 validate :validate_lock
44 validate :validate_output
45 after_validation :assign_auth
46 before_save :sort_serialized_attrs
47 before_save :update_secret_mounts_md5
48 before_save :scrub_secrets
49 before_save :clear_runtime_status_when_queued
50 after_save :update_cr_logs
51 after_save :handle_completed
52 after_save :propagate_priority
54 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
55 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
57 api_accessible :user, extend: :common do |t|
59 t.add :container_image
71 t.add :runtime_constraints
76 t.add :scheduling_parameters
77 t.add :runtime_user_uuid
78 t.add :runtime_auth_scopes
80 t.add :gateway_address
81 t.add :interactive_session_started
82 t.add :output_storage_classes
83 t.add :output_properties
85 t.add :subrequests_cost
88 # Supported states for a container
93 (Running = 'Running'),
94 (Complete = 'Complete'),
95 (Cancelled = 'Cancelled')
100 Queued => [Locked, Cancelled],
101 Locked => [Queued, Running, Cancelled],
102 Running => [Complete, Cancelled],
103 Complete => [Cancelled]
106 def self.limit_index_columns_read
110 def self.full_text_searchable_columns
111 super - ["secret_mounts", "secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
114 def self.searchable_columns *args
115 super - ["secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
118 def logged_attributes
119 super.except('secret_mounts', 'runtime_token')
122 def state_transitions
126 # Container priority is the highest "computed priority" of any
127 # matching request. The computed priority of a container-submitted
128 # request is the priority of the submitting container. The computed
129 # priority of a user-submitted request is a function of
130 # user-assigned priority and request creation time.
132 return if ![Queued, Locked, Running].include?(state)
133 p = ContainerRequest.
134 where('container_uuid=? and priority>0 and state=?', uuid, ContainerRequest::Committed).
135 select("priority, requesting_container_uuid, created_at").
138 if cr.requesting_container_uuid
139 Container.where(uuid: cr.requesting_container_uuid).pluck(:priority).first
141 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
144 update_attributes!(priority: p)
147 def propagate_priority
148 return true unless saved_change_to_priority?
149 act_as_system_user do
150 # Update the priority of child container requests to match new
151 # priority of the parent container (ignoring requests with no
152 # container assigned, because their priority doesn't matter).
154 where('requesting_container_uuid = ? and state = ? and container_uuid is not null',
155 self.uuid, ContainerRequest::Committed).
156 pluck(:container_uuid).each do |container_uuid|
157 Container.find_by_uuid(container_uuid).update_priority!
162 # Create a new container (or find an existing one) to satisfy the
163 # given container request.
164 def self.resolve(req)
165 if req.runtime_token.nil?
166 runtime_user = if req.modified_by_user_uuid.nil?
169 User.find_by_uuid(req.modified_by_user_uuid)
171 runtime_auth_scopes = ["all"]
173 auth = ApiClientAuthorization.validate(token: req.runtime_token)
175 raise ArgumentError.new "Invalid runtime token"
177 runtime_user = User.find_by_id(auth.user_id)
178 runtime_auth_scopes = auth.scopes
180 c_attrs = act_as_user runtime_user do
182 command: req.command,
184 environment: req.environment,
185 output_path: req.output_path,
186 container_image: resolve_container_image(req.container_image),
187 mounts: resolve_mounts(req.mounts),
188 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
189 scheduling_parameters: req.scheduling_parameters,
190 secret_mounts: req.secret_mounts,
191 runtime_token: req.runtime_token,
192 runtime_user_uuid: runtime_user.uuid,
193 runtime_auth_scopes: runtime_auth_scopes,
194 output_storage_classes: req.output_storage_classes,
197 act_as_system_user do
198 if req.use_existing && (reusable = find_reusable(c_attrs))
201 Container.create!(c_attrs)
206 # Return a runtime_constraints hash that complies with requested but
207 # is suitable for saving in a container record, i.e., has specific
208 # values instead of ranges.
210 # Doing this as a step separate from other resolutions, like "git
211 # revision range to commit hash", makes sense only when there is no
212 # opportunity to reuse an existing container (e.g., container reuse
213 # is not implemented yet, or we have already found that no existing
214 # containers are suitable).
215 def self.resolve_runtime_constraints(runtime_constraints)
217 runtime_constraints.each do |k, v|
224 if rc['keep_cache_ram'] == 0
225 rc['keep_cache_ram'] = Rails.configuration.Containers.DefaultKeepCacheRAM
227 if rc['keep_cache_disk'] == 0 and rc['keep_cache_ram'] == 0
228 rc['keep_cache_disk'] = bound_keep_cache_disk(rc['ram'])
233 # Return a mounts hash suitable for a Container, i.e., with every
234 # readonly collection UUID resolved to a PDH.
235 def self.resolve_mounts(mounts)
237 mounts.each do |k, mount|
240 if mount['kind'] != 'collection'
244 uuid = mount.delete 'uuid'
246 if mount['portable_data_hash'].nil? and !uuid.nil?
247 # PDH not supplied, try by UUID
249 readable_by(current_user).
251 select(:portable_data_hash).
254 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
256 mount['portable_data_hash'] = c.portable_data_hash
262 # Return a container_image PDH suitable for a Container.
263 def self.resolve_container_image(container_image)
264 coll = Collection.for_latest_docker_image(container_image)
266 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
268 coll.portable_data_hash
271 def self.find_reusable(attrs)
272 log_reuse_info { "starting with #{Container.all.count} container records in database" }
273 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
274 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
276 candidates = candidates.where('cwd = ?', attrs[:cwd])
277 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
279 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
280 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
282 candidates = candidates.where('output_path = ?', attrs[:output_path])
283 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
285 image = resolve_container_image(attrs[:container_image])
286 candidates = candidates.where('container_image = ?', image)
287 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
289 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
290 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
292 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
293 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
294 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
296 resolved_runtime_constraints = resolve_runtime_constraints(attrs[:runtime_constraints])
297 # Ideally we would completely ignore Keep cache constraints when making
298 # reuse considerations, but our database structure makes that impractical.
299 # The best we can do is generate a search that matches on all likely values.
300 runtime_constraint_variations = {
302 # Check for constraints without keep_cache_disk
303 # (containers that predate the constraint)
305 # Containers that use keep_cache_ram instead
308 bound_keep_cache_disk(resolved_runtime_constraints['ram']),
309 # The minimum default bound
310 bound_keep_cache_disk(0),
311 # The maximum default bound (presumably)
312 bound_keep_cache_disk(1 << 60),
313 # The requested value
314 resolved_runtime_constraints.delete('keep_cache_disk'),
317 # Containers that use keep_cache_disk instead
320 Rails.configuration.Containers.DefaultKeepCacheRAM,
321 # The requested value
322 resolved_runtime_constraints.delete('keep_cache_ram'),
325 resolved_cuda = resolved_runtime_constraints['cuda']
326 if resolved_cuda.nil? or resolved_cuda['device_count'] == 0
327 runtime_constraint_variations[:cuda] = [
328 # Check for constraints without cuda
329 # (containers that predate the constraint)
331 # The default "don't need CUDA" value
334 'driver_version' => '',
335 'hardware_capability' => '',
337 # The requested value
338 resolved_runtime_constraints.delete('cuda')
341 reusable_runtime_constraints = hash_product(runtime_constraint_variations)
342 .map { |v| resolved_runtime_constraints.merge(v) }
344 candidates = candidates.where_serialized(:runtime_constraints, reusable_runtime_constraints, md5: true, multivalue: true)
345 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
347 log_reuse_info { "checking for state=Complete with readable output and log..." }
349 select_readable_pdh = Collection.
350 readable_by(current_user).
351 select(:portable_data_hash).
354 usable = candidates.where(state: Complete, exit_code: 0)
355 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
357 usable = usable.where("log IN (#{select_readable_pdh})")
358 log_reuse_info(usable) { "with readable log" }
360 usable = usable.where("output IN (#{select_readable_pdh})")
361 log_reuse_info(usable) { "with readable output" }
363 usable = usable.order('finished_at ASC').limit(1).first
365 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
369 # Check for non-failing Running candidates and return the most likely to finish sooner.
370 log_reuse_info { "checking for state=Running..." }
371 running = candidates.where(state: Running).
372 where("(runtime_status->'error') is null").
373 order('progress desc, started_at asc').
376 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
379 log_reuse_info { "have no containers in Running state" }
382 # Check for Locked or Queued ones and return the most likely to start first.
383 locked_or_queued = candidates.
384 where("state IN (?)", [Locked, Queued]).
385 order('state asc, priority desc, created_at asc').
388 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
389 return locked_or_queued
391 log_reuse_info { "have no containers in Locked or Queued state" }
394 log_reuse_info { "done, no reusable container found" }
400 if self.state != Queued
401 raise LockFailedError.new("cannot lock when #{self.state}")
403 self.update_attributes!(state: Locked)
408 if state_was == Queued and state == Locked
409 if self.priority <= 0
410 raise LockFailedError.new("cannot lock when priority<=0")
412 self.lock_count = self.lock_count+1
418 if self.state != Locked
419 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
421 self.update_attributes!(state: Queued)
426 if state_was == Locked and state == Queued
427 if self.locked_by_uuid != current_api_client_authorization.uuid
428 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
430 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
431 self.state = Cancelled
432 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
437 def self.readable_by(*users_list)
438 # Load optional keyword arguments, if they exist.
439 if users_list.last.is_a? Hash
440 kwargs = users_list.pop
444 if users_list.select { |u| u.is_admin }.any?
447 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
451 [Complete, Cancelled].include?(self.state)
454 def self.for_current_token
455 return if !current_api_client_authorization
456 _, _, _, container_uuid = Thread.current[:token].split('/')
457 if container_uuid.nil?
458 Container.where(auth_uuid: current_api_client_authorization.uuid).first
460 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
461 current_api_client_authorization.uuid,
463 current_api_client_authorization.token).first
469 def self.bound_keep_cache_disk(value)
475 elsif value > max_value
482 def self.hash_product(**kwargs)
483 # kwargs is a hash that maps parameters to an array of values.
484 # This function enumerates every possible hash where each key has one of
485 # the values from its array.
486 # The output keys are strings since that's what container hash attributes
488 # A nil value yields a hash without that key.
490 *kwargs.map { |(key, values)| [key.to_s].product(values) },
491 ).map { |param_pairs| Hash[param_pairs].compact }
494 def fill_field_defaults
495 self.state ||= Queued
496 self.environment ||= {}
497 self.runtime_constraints ||= {}
501 self.scheduling_parameters ||= {}
504 def permission_to_create
505 current_user.andand.is_admin
508 def permission_to_destroy
509 current_user.andand.is_admin
512 def ensure_owner_uuid_is_permitted
513 # validate_change ensures owner_uuid can't be changed at all --
514 # except during create, which requires admin privileges. Checking
515 # permission here would be superfluous.
520 if self.state_changed? and self.state == Running
521 self.started_at ||= db_current_time
524 if self.state_changed? and [Complete, Cancelled].include? self.state
525 self.finished_at ||= db_current_time
529 # Check that well-known runtime status keys have desired data types
530 def validate_runtime_status
532 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
534 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
535 errors.add(:runtime_status, "'#{k}' value must be a string")
542 final_attrs = [:finished_at]
543 progress_attrs = [:progress, :runtime_status, :subrequests_cost, :cost,
544 :log, :output, :output_properties, :exit_code]
547 permitted.push(:owner_uuid, :command, :container_image, :cwd,
548 :environment, :mounts, :output_path, :priority,
549 :runtime_constraints, :scheduling_parameters,
550 :secret_mounts, :runtime_token,
551 :runtime_user_uuid, :runtime_auth_scopes,
552 :output_storage_classes)
557 permitted.push :priority, :runtime_status, :log, :lock_count
560 permitted.push :priority
563 permitted.push :priority, :output_properties, :gateway_address, *progress_attrs
564 if self.state_changed?
565 permitted.push :started_at
567 if !self.interactive_session_started_was
568 permitted.push :interactive_session_started
572 if self.state_was == Running
573 permitted.push *final_attrs, *progress_attrs
579 permitted.push :finished_at, *progress_attrs
581 permitted.push :finished_at, :log, :runtime_status, :cost
585 # The state_transitions check will add an error message for this
589 if self.state_was == Running &&
590 !current_api_client_authorization.nil? &&
591 (current_api_client_authorization.uuid == self.auth_uuid ||
592 current_api_client_authorization.token == self.runtime_token)
593 # The contained process itself can write final attrs but can't
594 # change priority or log.
595 permitted.push *final_attrs
596 permitted = permitted - [:log, :priority]
597 elsif !current_user.andand.is_admin
598 raise PermissionDeniedError
599 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
600 # When locked, progress fields cannot be updated by the wrong
601 # dispatcher, even though it has admin privileges.
602 permitted = permitted - progress_attrs
604 check_update_whitelist permitted
608 if [Locked, Running].include? self.state
609 # If the Container was already locked, locked_by_uuid must not
610 # changes. Otherwise, the current auth gets the lock.
611 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
616 # The caller can provide a new value for locked_by_uuid, but only
617 # if it's exactly what we expect. This allows a caller to perform
618 # an update like {"state":"Unlocked","locked_by_uuid":null}.
619 if self.locked_by_uuid_changed?
620 if self.locked_by_uuid != need_lock
621 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
624 self.locked_by_uuid = need_lock
628 # Output must exist and be readable by the current user. This is so
629 # that a container cannot "claim" a collection that it doesn't otherwise
630 # have access to just by setting the output field to the collection PDH.
633 readable_by(current_user, {include_trash: true}).
634 where(portable_data_hash: self.output).
637 errors.add :output, "collection must exist and be readable by current user."
643 # If self.final?, this update is superfluous: the final log/output
644 # update will be done when handle_completed calls finalize! on
645 # each requesting CR.
646 return if self.final? || !saved_change_to_log?
647 leave_modified_by_user_alone do
648 ContainerRequest.where(container_uuid: self.uuid, state: ContainerRequest::Committed).each do |cr|
649 cr.update_collections(container: self, collections: ['log'])
656 if self.auth_uuid_changed?
657 return errors.add :auth_uuid, 'is readonly'
659 if not [Locked, Running].include? self.state
660 # Don't need one. If auth already exists, expire it.
662 # We use db_transaction_time here (not db_current_time) to
663 # ensure the token doesn't validate later in the same
664 # transaction (e.g., in a test case) by satisfying expires_at >
665 # transaction timestamp.
666 self.auth.andand.update_attributes(expires_at: db_transaction_time)
673 if self.runtime_token.nil?
674 if self.runtime_user_uuid.nil?
675 # legacy behavior, we don't have a runtime_user_uuid so get
676 # the user from the highest priority container request, needed
677 # when performing an upgrade and there are queued containers,
679 cr = ContainerRequest.
680 where('container_uuid=? and priority>0', self.uuid).
681 order('priority desc').
684 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
686 self.runtime_user_uuid = cr.modified_by_user_uuid
687 self.runtime_auth_scopes = ["all"]
690 # Generate a new token. This runs with admin credentials as it's done by a
691 # dispatcher user, so expires_at isn't enforced by API.MaxTokenLifetime.
692 self.auth = ApiClientAuthorization.
693 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
695 scopes: self.runtime_auth_scopes)
699 def sort_serialized_attrs
700 if self.environment_changed?
701 self.environment = self.class.deep_sort_hash(self.environment)
703 if self.mounts_changed?
704 self.mounts = self.class.deep_sort_hash(self.mounts)
706 if self.runtime_constraints_changed?
707 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
709 if self.scheduling_parameters_changed?
710 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
712 if self.runtime_auth_scopes_changed?
713 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
717 def update_secret_mounts_md5
718 if self.secret_mounts_changed?
719 self.secret_mounts_md5 = Digest::MD5.hexdigest(
720 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
725 # this runs after update_secret_mounts_md5, so the
726 # secret_mounts_md5 will still reflect the secrets that are being
728 if self.state_changed? && self.final?
729 self.secret_mounts = {}
730 self.runtime_token = nil
734 def clear_runtime_status_when_queued
735 # Avoid leaking status messages between different dispatch attempts
736 if self.state_was == Locked && self.state == Queued
737 self.runtime_status = {}
742 # This container is finished so finalize any associated container requests
743 # that are associated with this container.
744 if saved_change_to_state? and self.final?
745 # These get wiped out by with_lock (which reloads the record),
746 # so record them now in case we need to schedule a retry.
747 prev_secret_mounts = secret_mounts_before_last_save
748 prev_runtime_token = runtime_token_before_last_save
750 # Need to take a lock on the container to ensure that any
751 # concurrent container requests that might try to reuse this
752 # container will block until the container completion
753 # transaction finishes. This ensure that concurrent container
754 # requests that try to reuse this container are finalized (on
755 # Complete) or don't reuse it (on Cancelled).
757 act_as_system_user do
758 if self.state == Cancelled
759 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
761 retryable_requests = []
764 if retryable_requests.any?
765 scheduling_parameters = {
766 # partitions: empty if any are empty, else the union of all parameters
767 "partitions": retryable_requests
768 .map { |req| req.scheduling_parameters["partitions"] || [] }
769 .reduce { |cur, new| (cur.empty? or new.empty?) ? [] : (cur | new) },
771 # preemptible: true if all are true, else false
772 "preemptible": retryable_requests
773 .map { |req| req.scheduling_parameters["preemptible"] }
776 # supervisor: true if all any true, else false
777 "supervisor": retryable_requests
778 .map { |req| req.scheduling_parameters["supervisor"] }
781 # max_run_time: 0 if any are 0 (unlimited), else the maximum
782 "max_run_time": retryable_requests
783 .map { |req| req.scheduling_parameters["max_run_time"] || 0 }
784 .reduce do |cur, new|
785 if cur == 0 or new == 0
796 command: self.command,
798 environment: self.environment,
799 output_path: self.output_path,
800 container_image: self.container_image,
802 runtime_constraints: self.runtime_constraints,
803 scheduling_parameters: scheduling_parameters,
804 secret_mounts: prev_secret_mounts,
805 runtime_token: prev_runtime_token,
806 runtime_user_uuid: self.runtime_user_uuid,
807 runtime_auth_scopes: self.runtime_auth_scopes
809 c = Container.create! c_attrs
810 retryable_requests.each do |cr|
812 leave_modified_by_user_alone do
813 # Use row locking because this increments container_count
814 cr.cumulative_cost += self.cost + self.subrequests_cost
815 cr.container_uuid = c.uuid
822 # Notify container requests associated with this container
823 ContainerRequest.where(container_uuid: uuid,
824 state: ContainerRequest::Committed).each do |cr|
825 leave_modified_by_user_alone do
830 # Cancel outstanding container requests made by this container.
832 where(requesting_container_uuid: uuid,
833 state: ContainerRequest::Committed).
834 in_batches(of: 15).each_record do |cr|
835 leave_modified_by_user_alone do
837 container_state = Container.where(uuid: cr.container_uuid).pluck(:state).first
838 if container_state == Container::Queued || container_state == Container::Locked
839 # If the child container hasn't started yet, finalize the
840 # child CR now instead of leaving it "on hold", i.e.,
841 # Queued with priority 0. (OTOH, if the child is already
842 # running, leave it alone so it can get cancelled the
843 # usual way, get a copy of the log collection, etc.)
844 cr.update_attributes!(state: ContainerRequest::Final)