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', uuid).
135 includes(:requesting_container).
138 if cr.requesting_container
139 cr.requesting_container.priority
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: self.uuid,
155 state: ContainerRequest::Committed).
156 where('container_uuid is not null').
157 includes(:container).
159 map(&:update_priority!)
163 # Create a new container (or find an existing one) to satisfy the
164 # given container request.
165 def self.resolve(req)
166 if req.runtime_token.nil?
167 runtime_user = if req.modified_by_user_uuid.nil?
170 User.find_by_uuid(req.modified_by_user_uuid)
172 runtime_auth_scopes = ["all"]
174 auth = ApiClientAuthorization.validate(token: req.runtime_token)
176 raise ArgumentError.new "Invalid runtime token"
178 runtime_user = User.find_by_id(auth.user_id)
179 runtime_auth_scopes = auth.scopes
181 c_attrs = act_as_user runtime_user do
183 command: req.command,
185 environment: req.environment,
186 output_path: req.output_path,
187 container_image: resolve_container_image(req.container_image),
188 mounts: resolve_mounts(req.mounts),
189 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
190 scheduling_parameters: req.scheduling_parameters,
191 secret_mounts: req.secret_mounts,
192 runtime_token: req.runtime_token,
193 runtime_user_uuid: runtime_user.uuid,
194 runtime_auth_scopes: runtime_auth_scopes,
195 output_storage_classes: req.output_storage_classes,
198 act_as_system_user do
199 if req.use_existing && (reusable = find_reusable(c_attrs))
202 Container.create!(c_attrs)
207 # Return a runtime_constraints hash that complies with requested but
208 # is suitable for saving in a container record, i.e., has specific
209 # values instead of ranges.
211 # Doing this as a step separate from other resolutions, like "git
212 # revision range to commit hash", makes sense only when there is no
213 # opportunity to reuse an existing container (e.g., container reuse
214 # is not implemented yet, or we have already found that no existing
215 # containers are suitable).
216 def self.resolve_runtime_constraints(runtime_constraints)
218 runtime_constraints.each do |k, v|
225 if rc['keep_cache_ram'] == 0
226 rc['keep_cache_ram'] = Rails.configuration.Containers.DefaultKeepCacheRAM
228 if rc['keep_cache_disk'] == 0 and rc['keep_cache_ram'] == 0
229 rc['keep_cache_disk'] = bound_keep_cache_disk(rc['ram'])
234 # Return a mounts hash suitable for a Container, i.e., with every
235 # readonly collection UUID resolved to a PDH.
236 def self.resolve_mounts(mounts)
238 mounts.each do |k, mount|
241 if mount['kind'] != 'collection'
245 uuid = mount.delete 'uuid'
247 if mount['portable_data_hash'].nil? and !uuid.nil?
248 # PDH not supplied, try by UUID
250 readable_by(current_user).
252 select(:portable_data_hash).
255 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
257 mount['portable_data_hash'] = c.portable_data_hash
263 # Return a container_image PDH suitable for a Container.
264 def self.resolve_container_image(container_image)
265 coll = Collection.for_latest_docker_image(container_image)
267 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
269 coll.portable_data_hash
272 def self.find_reusable(attrs)
273 log_reuse_info { "starting with #{Container.all.count} container records in database" }
274 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
275 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
277 candidates = candidates.where('cwd = ?', attrs[:cwd])
278 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
280 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
281 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
283 candidates = candidates.where('output_path = ?', attrs[:output_path])
284 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
286 image = resolve_container_image(attrs[:container_image])
287 candidates = candidates.where('container_image = ?', image)
288 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
290 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
291 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
293 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
294 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
295 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
297 resolved_runtime_constraints = resolve_runtime_constraints(attrs[:runtime_constraints])
298 # Ideally we would completely ignore Keep cache constraints when making
299 # reuse considerations, but our database structure makes that impractical.
300 # The best we can do is generate a search that matches on all likely values.
301 runtime_constraint_variations = {
303 # Check for constraints without keep_cache_disk
304 # (containers that predate the constraint)
306 # Containers that use keep_cache_ram instead
309 bound_keep_cache_disk(resolved_runtime_constraints['ram']),
310 # The minimum default bound
311 bound_keep_cache_disk(0),
312 # The maximum default bound (presumably)
313 bound_keep_cache_disk(1 << 60),
314 # The requested value
315 resolved_runtime_constraints.delete('keep_cache_disk'),
318 # Containers that use keep_cache_disk instead
321 Rails.configuration.Containers.DefaultKeepCacheRAM,
322 # The requested value
323 resolved_runtime_constraints.delete('keep_cache_ram'),
326 resolved_cuda = resolved_runtime_constraints['cuda']
327 if resolved_cuda.nil? or resolved_cuda['device_count'] == 0
328 runtime_constraint_variations[:cuda] = [
329 # Check for constraints without cuda
330 # (containers that predate the constraint)
332 # The default "don't need CUDA" value
335 'driver_version' => '',
336 'hardware_capability' => '',
338 # The requested value
339 resolved_runtime_constraints.delete('cuda')
342 reusable_runtime_constraints = hash_product(runtime_constraint_variations)
343 .map { |v| resolved_runtime_constraints.merge(v) }
345 candidates = candidates.where_serialized(:runtime_constraints, reusable_runtime_constraints, md5: true, multivalue: true)
346 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
348 log_reuse_info { "checking for state=Complete with readable output and log..." }
350 select_readable_pdh = Collection.
351 readable_by(current_user).
352 select(:portable_data_hash).
355 usable = candidates.where(state: Complete, exit_code: 0)
356 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
358 usable = usable.where("log IN (#{select_readable_pdh})")
359 log_reuse_info(usable) { "with readable log" }
361 usable = usable.where("output IN (#{select_readable_pdh})")
362 log_reuse_info(usable) { "with readable output" }
364 usable = usable.order('finished_at ASC').limit(1).first
366 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
370 # Check for non-failing Running candidates and return the most likely to finish sooner.
371 log_reuse_info { "checking for state=Running..." }
372 running = candidates.where(state: Running).
373 where("(runtime_status->'error') is null").
374 order('progress desc, started_at asc').
377 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
380 log_reuse_info { "have no containers in Running state" }
383 # Check for Locked or Queued ones and return the most likely to start first.
384 locked_or_queued = candidates.
385 where("state IN (?)", [Locked, Queued]).
386 order('state asc, priority desc, created_at asc').
389 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
390 return locked_or_queued
392 log_reuse_info { "have no containers in Locked or Queued state" }
395 log_reuse_info { "done, no reusable container found" }
401 if self.state != Queued
402 raise LockFailedError.new("cannot lock when #{self.state}")
404 self.update_attributes!(state: Locked)
409 if state_was == Queued and state == Locked
410 if self.priority <= 0
411 raise LockFailedError.new("cannot lock when priority<=0")
413 self.lock_count = self.lock_count+1
419 if self.state != Locked
420 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
422 self.update_attributes!(state: Queued)
427 if state_was == Locked and state == Queued
428 if self.locked_by_uuid != current_api_client_authorization.uuid
429 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
431 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
432 self.state = Cancelled
433 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
438 def self.readable_by(*users_list)
439 # Load optional keyword arguments, if they exist.
440 if users_list.last.is_a? Hash
441 kwargs = users_list.pop
445 if users_list.select { |u| u.is_admin }.any?
448 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
452 [Complete, Cancelled].include?(self.state)
455 def self.for_current_token
456 return if !current_api_client_authorization
457 _, _, _, container_uuid = Thread.current[:token].split('/')
458 if container_uuid.nil?
459 Container.where(auth_uuid: current_api_client_authorization.uuid).first
461 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
462 current_api_client_authorization.uuid,
464 current_api_client_authorization.token).first
470 def self.bound_keep_cache_disk(value)
476 elsif value > max_value
483 def self.hash_product(**kwargs)
484 # kwargs is a hash that maps parameters to an array of values.
485 # This function enumerates every possible hash where each key has one of
486 # the values from its array.
487 # The output keys are strings since that's what container hash attributes
489 # A nil value yields a hash without that key.
491 *kwargs.map { |(key, values)| [key.to_s].product(values) },
492 ).map { |param_pairs| Hash[param_pairs].compact }
495 def fill_field_defaults
496 self.state ||= Queued
497 self.environment ||= {}
498 self.runtime_constraints ||= {}
502 self.scheduling_parameters ||= {}
505 def permission_to_create
506 current_user.andand.is_admin
509 def permission_to_destroy
510 current_user.andand.is_admin
513 def ensure_owner_uuid_is_permitted
514 # validate_change ensures owner_uuid can't be changed at all --
515 # except during create, which requires admin privileges. Checking
516 # permission here would be superfluous.
521 if self.state_changed? and self.state == Running
522 self.started_at ||= db_current_time
525 if self.state_changed? and [Complete, Cancelled].include? self.state
526 self.finished_at ||= db_current_time
530 # Check that well-known runtime status keys have desired data types
531 def validate_runtime_status
533 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
535 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
536 errors.add(:runtime_status, "'#{k}' value must be a string")
543 final_attrs = [:finished_at]
544 progress_attrs = [:progress, :runtime_status, :subrequests_cost, :cost,
545 :log, :output, :output_properties, :exit_code]
548 permitted.push(:owner_uuid, :command, :container_image, :cwd,
549 :environment, :mounts, :output_path, :priority,
550 :runtime_constraints, :scheduling_parameters,
551 :secret_mounts, :runtime_token,
552 :runtime_user_uuid, :runtime_auth_scopes,
553 :output_storage_classes)
558 permitted.push :priority, :runtime_status, :log, :lock_count
561 permitted.push :priority
564 permitted.push :priority, :output_properties, :gateway_address, *progress_attrs
565 if self.state_changed?
566 permitted.push :started_at
568 if !self.interactive_session_started_was
569 permitted.push :interactive_session_started
573 if self.state_was == Running
574 permitted.push *final_attrs, *progress_attrs
580 permitted.push :finished_at, *progress_attrs
582 permitted.push :finished_at, :log, :runtime_status, :cost
586 # The state_transitions check will add an error message for this
590 if self.state_was == Running &&
591 !current_api_client_authorization.nil? &&
592 (current_api_client_authorization.uuid == self.auth_uuid ||
593 current_api_client_authorization.token == self.runtime_token)
594 # The contained process itself can write final attrs but can't
595 # change priority or log.
596 permitted.push *final_attrs
597 permitted = permitted - [:log, :priority]
598 elsif !current_user.andand.is_admin
599 raise PermissionDeniedError
600 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
601 # When locked, progress fields cannot be updated by the wrong
602 # dispatcher, even though it has admin privileges.
603 permitted = permitted - progress_attrs
605 check_update_whitelist permitted
609 if [Locked, Running].include? self.state
610 # If the Container was already locked, locked_by_uuid must not
611 # changes. Otherwise, the current auth gets the lock.
612 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
617 # The caller can provide a new value for locked_by_uuid, but only
618 # if it's exactly what we expect. This allows a caller to perform
619 # an update like {"state":"Unlocked","locked_by_uuid":null}.
620 if self.locked_by_uuid_changed?
621 if self.locked_by_uuid != need_lock
622 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
625 self.locked_by_uuid = need_lock
629 # Output must exist and be readable by the current user. This is so
630 # that a container cannot "claim" a collection that it doesn't otherwise
631 # have access to just by setting the output field to the collection PDH.
634 readable_by(current_user, {include_trash: true}).
635 where(portable_data_hash: self.output).
638 errors.add :output, "collection must exist and be readable by current user."
644 # If self.final?, this update is superfluous: the final log/output
645 # update will be done when handle_completed calls finalize! on
646 # each requesting CR.
647 return if self.final? || !saved_change_to_log?
648 leave_modified_by_user_alone do
649 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
650 cr.update_collections(container: self, collections: ['log'])
657 if self.auth_uuid_changed?
658 return errors.add :auth_uuid, 'is readonly'
660 if not [Locked, Running].include? self.state
661 # Don't need one. If auth already exists, expire it.
663 # We use db_transaction_time here (not db_current_time) to
664 # ensure the token doesn't validate later in the same
665 # transaction (e.g., in a test case) by satisfying expires_at >
666 # transaction timestamp.
667 self.auth.andand.update_attributes(expires_at: db_transaction_time)
674 if self.runtime_token.nil?
675 if self.runtime_user_uuid.nil?
676 # legacy behavior, we don't have a runtime_user_uuid so get
677 # the user from the highest priority container request, needed
678 # when performing an upgrade and there are queued containers,
680 cr = ContainerRequest.
681 where('container_uuid=? and priority>0', self.uuid).
682 order('priority desc').
685 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
687 self.runtime_user_uuid = cr.modified_by_user_uuid
688 self.runtime_auth_scopes = ["all"]
691 # Generate a new token. This runs with admin credentials as it's done by a
692 # dispatcher user, so expires_at isn't enforced by API.MaxTokenLifetime.
693 self.auth = ApiClientAuthorization.
694 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
696 scopes: self.runtime_auth_scopes)
700 def sort_serialized_attrs
701 if self.environment_changed?
702 self.environment = self.class.deep_sort_hash(self.environment)
704 if self.mounts_changed?
705 self.mounts = self.class.deep_sort_hash(self.mounts)
707 if self.runtime_constraints_changed?
708 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
710 if self.scheduling_parameters_changed?
711 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
713 if self.runtime_auth_scopes_changed?
714 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
718 def update_secret_mounts_md5
719 if self.secret_mounts_changed?
720 self.secret_mounts_md5 = Digest::MD5.hexdigest(
721 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
726 # this runs after update_secret_mounts_md5, so the
727 # secret_mounts_md5 will still reflect the secrets that are being
729 if self.state_changed? && self.final?
730 self.secret_mounts = {}
731 self.runtime_token = nil
735 def clear_runtime_status_when_queued
736 # Avoid leaking status messages between different dispatch attempts
737 if self.state_was == Locked && self.state == Queued
738 self.runtime_status = {}
743 # This container is finished so finalize any associated container requests
744 # that are associated with this container.
745 if saved_change_to_state? and self.final?
746 # These get wiped out by with_lock (which reloads the record),
747 # so record them now in case we need to schedule a retry.
748 prev_secret_mounts = secret_mounts_before_last_save
749 prev_runtime_token = runtime_token_before_last_save
751 # Need to take a lock on the container to ensure that any
752 # concurrent container requests that might try to reuse this
753 # container will block until the container completion
754 # transaction finishes. This ensure that concurrent container
755 # requests that try to reuse this container are finalized (on
756 # Complete) or don't reuse it (on Cancelled).
758 act_as_system_user do
759 if self.state == Cancelled
760 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
762 retryable_requests = []
765 if retryable_requests.any?
766 scheduling_parameters = {
767 # partitions: empty if any are empty, else the union of all parameters
768 "partitions": retryable_requests
769 .map { |req| req.scheduling_parameters["partitions"] || [] }
770 .reduce { |cur, new| (cur.empty? or new.empty?) ? [] : (cur | new) },
772 # preemptible: true if all are true, else false
773 "preemptible": retryable_requests
774 .map { |req| req.scheduling_parameters["preemptible"] }
777 # supervisor: true if all any true, else false
778 "supervisor": retryable_requests
779 .map { |req| req.scheduling_parameters["supervisor"] }
782 # max_run_time: 0 if any are 0 (unlimited), else the maximum
783 "max_run_time": retryable_requests
784 .map { |req| req.scheduling_parameters["max_run_time"] || 0 }
785 .reduce do |cur, new|
786 if cur == 0 or new == 0
797 command: self.command,
799 environment: self.environment,
800 output_path: self.output_path,
801 container_image: self.container_image,
803 runtime_constraints: self.runtime_constraints,
804 scheduling_parameters: scheduling_parameters,
805 secret_mounts: prev_secret_mounts,
806 runtime_token: prev_runtime_token,
807 runtime_user_uuid: self.runtime_user_uuid,
808 runtime_auth_scopes: self.runtime_auth_scopes
810 c = Container.create! c_attrs
811 retryable_requests.each do |cr|
813 leave_modified_by_user_alone do
814 # Use row locking because this increments container_count
815 cr.cumulative_cost += self.cost + self.subrequests_cost
816 cr.container_uuid = c.uuid
823 # Notify container requests associated with this container
824 ContainerRequest.where(container_uuid: uuid,
825 state: ContainerRequest::Committed).each do |cr|
826 leave_modified_by_user_alone do
831 # Cancel outstanding container requests made by this container.
833 includes(:container).
834 where(requesting_container_uuid: uuid,
835 state: ContainerRequest::Committed).each do |cr|
836 leave_modified_by_user_alone do
837 cr.update_attributes!(priority: 0)
839 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
840 # If the child container hasn't started yet, finalize the
841 # child CR now instead of leaving it "on hold", i.e.,
842 # Queued with priority 0. (OTOH, if the child is already
843 # running, leave it alone so it can get cancelled the
844 # usual way, get a copy of the log collection, etc.)
845 cr.update_attributes!(state: ContainerRequest::Final)