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'
8 require 'update_priority'
10 class Container < ArvadosModel
11 include ArvadosModelUpdates
14 include CommonApiTemplate
15 include WhitelistUpdate
16 extend CurrentApiClient
20 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
21 # already know how to properly treat them.
22 attribute :secret_mounts, :jsonbHash, default: {}
23 attribute :runtime_status, :jsonbHash, default: {}
24 attribute :runtime_auth_scopes, :jsonbArray, default: []
25 attribute :output_storage_classes, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
26 attribute :output_properties, :jsonbHash, default: {}
28 serialize :environment, Hash
29 serialize :mounts, Hash
30 serialize :runtime_constraints, Hash
31 serialize :command, Array
32 serialize :scheduling_parameters, Hash
34 after_find :fill_container_defaults_after_find
35 before_validation :fill_field_defaults, :if => :new_record?
36 before_validation :set_timestamps
37 before_validation :check_lock
38 before_validation :check_unlock
39 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
40 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
41 validate :validate_runtime_status
42 validate :validate_state_change
43 validate :validate_change
44 validate :validate_lock
45 validate :validate_output
46 after_validation :assign_auth
47 before_save :sort_serialized_attrs
48 before_save :update_secret_mounts_md5
49 before_save :scrub_secrets
50 before_save :clear_runtime_status_when_queued
51 after_save :update_cr_logs
52 after_save :handle_completed
53 after_save :propagate_priority
54 after_commit { UpdatePriority.run_update_thread }
56 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
57 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
59 api_accessible :user, extend: :common do |t|
61 t.add :container_image
73 t.add :runtime_constraints
78 t.add :scheduling_parameters
79 t.add :runtime_user_uuid
80 t.add :runtime_auth_scopes
82 t.add :gateway_address
83 t.add :interactive_session_started
84 t.add :output_storage_classes
85 t.add :output_properties
87 t.add :subrequests_cost
90 # Supported states for a container
95 (Running = 'Running'),
96 (Complete = 'Complete'),
97 (Cancelled = 'Cancelled')
100 State_transitions = {
102 Queued => [Locked, Cancelled],
103 Locked => [Queued, Running, Cancelled],
104 Running => [Complete, Cancelled],
105 Complete => [Cancelled]
108 def self.limit_index_columns_read
112 def self.full_text_searchable_columns
113 super - ["secret_mounts", "secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
116 def self.searchable_columns *args
117 super - ["secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
120 def logged_attributes
121 super.except('secret_mounts', 'runtime_token')
124 def state_transitions
128 # Container priority is the highest "computed priority" of any
129 # matching request. The computed priority of a container-submitted
130 # request is the priority of the submitting container. The computed
131 # priority of a user-submitted request is a function of
132 # user-assigned priority and request creation time.
134 return if ![Queued, Locked, Running].include?(state)
135 p = ContainerRequest.
136 where('container_uuid=? and priority>0', uuid).
137 includes(:requesting_container).
140 if cr.requesting_container
141 cr.requesting_container.priority
143 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
146 update_attributes!(priority: p)
149 def propagate_priority
150 return true unless saved_change_to_priority?
151 act_as_system_user do
152 # Update the priority of child container requests to match new
153 # priority of the parent container (ignoring requests with no
154 # container assigned, because their priority doesn't matter).
156 where(requesting_container_uuid: self.uuid,
157 state: ContainerRequest::Committed).
158 where('container_uuid is not null').
159 includes(:container).
161 map(&:update_priority!)
165 # Create a new container (or find an existing one) to satisfy the
166 # given container request.
167 def self.resolve(req)
168 if req.runtime_token.nil?
169 runtime_user = if req.modified_by_user_uuid.nil?
172 User.find_by_uuid(req.modified_by_user_uuid)
174 runtime_auth_scopes = ["all"]
176 auth = ApiClientAuthorization.validate(token: req.runtime_token)
178 raise ArgumentError.new "Invalid runtime token"
180 runtime_user = User.find_by_id(auth.user_id)
181 runtime_auth_scopes = auth.scopes
183 c_attrs = act_as_user runtime_user do
185 command: req.command,
187 environment: req.environment,
188 output_path: req.output_path,
189 container_image: resolve_container_image(req.container_image),
190 mounts: resolve_mounts(req.mounts),
191 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
192 scheduling_parameters: req.scheduling_parameters,
193 secret_mounts: req.secret_mounts,
194 runtime_token: req.runtime_token,
195 runtime_user_uuid: runtime_user.uuid,
196 runtime_auth_scopes: runtime_auth_scopes,
197 output_storage_classes: req.output_storage_classes,
200 act_as_system_user do
201 if req.use_existing && (reusable = find_reusable(c_attrs))
204 Container.create!(c_attrs)
209 # Return a runtime_constraints hash that complies with requested but
210 # is suitable for saving in a container record, i.e., has specific
211 # values instead of ranges.
213 # Doing this as a step separate from other resolutions, like "git
214 # revision range to commit hash", makes sense only when there is no
215 # opportunity to reuse an existing container (e.g., container reuse
216 # is not implemented yet, or we have already found that no existing
217 # containers are suitable).
218 def self.resolve_runtime_constraints(runtime_constraints)
220 runtime_constraints.each do |k, v|
227 if rc['keep_cache_ram'] == 0
228 rc['keep_cache_ram'] = Rails.configuration.Containers.DefaultKeepCacheRAM
230 if rc['keep_cache_disk'] == 0 and rc['keep_cache_ram'] == 0
231 # If neither ram nor disk cache was specified and
232 # DefaultKeepCacheRAM==0, default to disk cache with size equal
233 # to RAM constraint (but at least 2 GiB and at most 32 GiB).
234 rc['keep_cache_disk'] = [[rc['ram'] || 0, 2 << 30].max, 32 << 30].min
239 # Return a mounts hash suitable for a Container, i.e., with every
240 # readonly collection UUID resolved to a PDH.
241 def self.resolve_mounts(mounts)
243 mounts.each do |k, mount|
246 if mount['kind'] != 'collection'
250 uuid = mount.delete 'uuid'
252 if mount['portable_data_hash'].nil? and !uuid.nil?
253 # PDH not supplied, try by UUID
255 readable_by(current_user).
257 select(:portable_data_hash).
260 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
262 mount['portable_data_hash'] = c.portable_data_hash
268 # Return a container_image PDH suitable for a Container.
269 def self.resolve_container_image(container_image)
270 coll = Collection.for_latest_docker_image(container_image)
272 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
274 coll.portable_data_hash
277 def self.find_reusable(attrs)
278 log_reuse_info { "starting with #{Container.all.count} container records in database" }
279 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
280 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
282 candidates = candidates.where('cwd = ?', attrs[:cwd])
283 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
285 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
286 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
288 candidates = candidates.where('output_path = ?', attrs[:output_path])
289 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
291 image = resolve_container_image(attrs[:container_image])
292 candidates = candidates.where('container_image = ?', image)
293 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
295 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
296 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
298 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
299 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
300 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
302 if attrs[:runtime_constraints]['cuda'].nil?
303 attrs[:runtime_constraints]['cuda'] = {
305 'driver_version' => '',
306 'hardware_capability' => '',
309 resolved_runtime_constraints = [resolve_runtime_constraints(attrs[:runtime_constraints])]
310 if resolved_runtime_constraints[0]['cuda']['device_count'] == 0
311 # If no CUDA requested, extend search to include older container
312 # records that don't have a 'cuda' section in runtime_constraints
313 resolved_runtime_constraints << resolved_runtime_constraints[0].except('cuda')
315 if resolved_runtime_constraints[0]['keep_cache_disk'] == 0
316 # If no disk cache requested, extend search to include older container
317 # records that don't have a 'keep_cache_disk' field in runtime_constraints
318 if resolved_runtime_constraints.length == 2
319 # exclude the one that also excludes CUDA
320 resolved_runtime_constraints << resolved_runtime_constraints[1].except('keep_cache_disk')
322 resolved_runtime_constraints << resolved_runtime_constraints[0].except('keep_cache_disk')
325 candidates = candidates.where_serialized(:runtime_constraints, resolved_runtime_constraints, md5: true, multivalue: true)
326 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
328 log_reuse_info { "checking for state=Complete with readable output and log..." }
330 select_readable_pdh = Collection.
331 readable_by(current_user).
332 select(:portable_data_hash).
335 usable = candidates.where(state: Complete, exit_code: 0)
336 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
338 usable = usable.where("log IN (#{select_readable_pdh})")
339 log_reuse_info(usable) { "with readable log" }
341 usable = usable.where("output IN (#{select_readable_pdh})")
342 log_reuse_info(usable) { "with readable output" }
344 usable = usable.order('finished_at ASC').limit(1).first
346 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
350 # Check for non-failing Running candidates and return the most likely to finish sooner.
351 log_reuse_info { "checking for state=Running..." }
352 running = candidates.where(state: Running).
353 where("(runtime_status->'error') is null").
354 order('progress desc, started_at asc').
357 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
360 log_reuse_info { "have no containers in Running state" }
363 # Check for Locked or Queued ones and return the most likely to start first.
364 locked_or_queued = candidates.
365 where("state IN (?)", [Locked, Queued]).
366 order('state asc, priority desc, created_at asc').
369 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
370 return locked_or_queued
372 log_reuse_info { "have no containers in Locked or Queued state" }
375 log_reuse_info { "done, no reusable container found" }
381 if self.state != Queued
382 raise LockFailedError.new("cannot lock when #{self.state}")
384 self.update_attributes!(state: Locked)
389 if state_was == Queued and state == Locked
390 if self.priority <= 0
391 raise LockFailedError.new("cannot lock when priority<=0")
393 self.lock_count = self.lock_count+1
399 if self.state != Locked
400 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
402 self.update_attributes!(state: Queued)
407 if state_was == Locked and state == Queued
408 if self.locked_by_uuid != current_api_client_authorization.uuid
409 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
411 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
412 self.state = Cancelled
413 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
418 def self.readable_by(*users_list)
419 # Load optional keyword arguments, if they exist.
420 if users_list.last.is_a? Hash
421 kwargs = users_list.pop
425 if users_list.select { |u| u.is_admin }.any?
428 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
432 [Complete, Cancelled].include?(self.state)
435 def self.for_current_token
436 return if !current_api_client_authorization
437 _, _, _, container_uuid = Thread.current[:token].split('/')
438 if container_uuid.nil?
439 Container.where(auth_uuid: current_api_client_authorization.uuid).first
441 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
442 current_api_client_authorization.uuid,
444 current_api_client_authorization.token).first
450 def fill_field_defaults
451 self.state ||= Queued
452 self.environment ||= {}
453 self.runtime_constraints ||= {}
457 self.scheduling_parameters ||= {}
460 def permission_to_create
461 current_user.andand.is_admin
464 def permission_to_destroy
465 current_user.andand.is_admin
468 def ensure_owner_uuid_is_permitted
469 # validate_change ensures owner_uuid can't be changed at all --
470 # except during create, which requires admin privileges. Checking
471 # permission here would be superfluous.
476 if self.state_changed? and self.state == Running
477 self.started_at ||= db_current_time
480 if self.state_changed? and [Complete, Cancelled].include? self.state
481 self.finished_at ||= db_current_time
485 # Check that well-known runtime status keys have desired data types
486 def validate_runtime_status
488 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
490 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
491 errors.add(:runtime_status, "'#{k}' value must be a string")
498 final_attrs = [:finished_at]
499 progress_attrs = [:progress, :runtime_status, :subrequests_cost, :cost,
500 :log, :output, :output_properties, :exit_code]
503 permitted.push(:owner_uuid, :command, :container_image, :cwd,
504 :environment, :mounts, :output_path, :priority,
505 :runtime_constraints, :scheduling_parameters,
506 :secret_mounts, :runtime_token,
507 :runtime_user_uuid, :runtime_auth_scopes,
508 :output_storage_classes)
513 permitted.push :priority, :runtime_status, :log, :lock_count
516 permitted.push :priority
519 permitted.push :priority, :output_properties, :gateway_address, *progress_attrs
520 if self.state_changed?
521 permitted.push :started_at
523 if !self.interactive_session_started_was
524 permitted.push :interactive_session_started
528 if self.state_was == Running
529 permitted.push *final_attrs, *progress_attrs
535 permitted.push :finished_at, *progress_attrs
537 permitted.push :finished_at, :log, :runtime_status, :cost
541 # The state_transitions check will add an error message for this
545 if self.state_was == Running &&
546 !current_api_client_authorization.nil? &&
547 (current_api_client_authorization.uuid == self.auth_uuid ||
548 current_api_client_authorization.token == self.runtime_token)
549 # The contained process itself can write final attrs but can't
550 # change priority or log.
551 permitted.push *final_attrs
552 permitted = permitted - [:log, :priority]
553 elsif !current_user.andand.is_admin
554 raise PermissionDeniedError
555 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
556 # When locked, progress fields cannot be updated by the wrong
557 # dispatcher, even though it has admin privileges.
558 permitted = permitted - progress_attrs
560 check_update_whitelist permitted
564 if [Locked, Running].include? self.state
565 # If the Container was already locked, locked_by_uuid must not
566 # changes. Otherwise, the current auth gets the lock.
567 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
572 # The caller can provide a new value for locked_by_uuid, but only
573 # if it's exactly what we expect. This allows a caller to perform
574 # an update like {"state":"Unlocked","locked_by_uuid":null}.
575 if self.locked_by_uuid_changed?
576 if self.locked_by_uuid != need_lock
577 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
580 self.locked_by_uuid = need_lock
584 # Output must exist and be readable by the current user. This is so
585 # that a container cannot "claim" a collection that it doesn't otherwise
586 # have access to just by setting the output field to the collection PDH.
589 readable_by(current_user, {include_trash: true}).
590 where(portable_data_hash: self.output).
593 errors.add :output, "collection must exist and be readable by current user."
599 # If self.final?, this update is superfluous: the final log/output
600 # update will be done when handle_completed calls finalize! on
601 # each requesting CR.
602 return if self.final? || !saved_change_to_log?
603 leave_modified_by_user_alone do
604 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
605 cr.update_collections(container: self, collections: ['log'])
612 if self.auth_uuid_changed?
613 return errors.add :auth_uuid, 'is readonly'
615 if not [Locked, Running].include? self.state
616 # Don't need one. If auth already exists, expire it.
618 # We use db_transaction_time here (not db_current_time) to
619 # ensure the token doesn't validate later in the same
620 # transaction (e.g., in a test case) by satisfying expires_at >
621 # transaction timestamp.
622 self.auth.andand.update_attributes(expires_at: db_transaction_time)
629 if self.runtime_token.nil?
630 if self.runtime_user_uuid.nil?
631 # legacy behavior, we don't have a runtime_user_uuid so get
632 # the user from the highest priority container request, needed
633 # when performing an upgrade and there are queued containers,
635 cr = ContainerRequest.
636 where('container_uuid=? and priority>0', self.uuid).
637 order('priority desc').
640 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
642 self.runtime_user_uuid = cr.modified_by_user_uuid
643 self.runtime_auth_scopes = ["all"]
646 # Generate a new token. This runs with admin credentials as it's done by a
647 # dispatcher user, so expires_at isn't enforced by API.MaxTokenLifetime.
648 self.auth = ApiClientAuthorization.
649 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
651 scopes: self.runtime_auth_scopes)
655 def sort_serialized_attrs
656 if self.environment_changed?
657 self.environment = self.class.deep_sort_hash(self.environment)
659 if self.mounts_changed?
660 self.mounts = self.class.deep_sort_hash(self.mounts)
662 if self.runtime_constraints_changed?
663 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
665 if self.scheduling_parameters_changed?
666 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
668 if self.runtime_auth_scopes_changed?
669 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
673 def update_secret_mounts_md5
674 if self.secret_mounts_changed?
675 self.secret_mounts_md5 = Digest::MD5.hexdigest(
676 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
681 # this runs after update_secret_mounts_md5, so the
682 # secret_mounts_md5 will still reflect the secrets that are being
684 if self.state_changed? && self.final?
685 self.secret_mounts = {}
686 self.runtime_token = nil
690 def clear_runtime_status_when_queued
691 # Avoid leaking status messages between different dispatch attempts
692 if self.state_was == Locked && self.state == Queued
693 self.runtime_status = {}
698 # This container is finished so finalize any associated container requests
699 # that are associated with this container.
700 if saved_change_to_state? and self.final?
701 # These get wiped out by with_lock (which reloads the record),
702 # so record them now in case we need to schedule a retry.
703 prev_secret_mounts = secret_mounts_before_last_save
704 prev_runtime_token = runtime_token_before_last_save
706 # Need to take a lock on the container to ensure that any
707 # concurrent container requests that might try to reuse this
708 # container will block until the container completion
709 # transaction finishes. This ensure that concurrent container
710 # requests that try to reuse this container are finalized (on
711 # Complete) or don't reuse it (on Cancelled).
713 act_as_system_user do
714 if self.state == Cancelled
715 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
717 retryable_requests = []
720 if retryable_requests.any?
721 scheduling_parameters = {
722 # partitions: empty if any are empty, else the union of all parameters
723 "partitions": retryable_requests
724 .map { |req| req.scheduling_parameters["partitions"] || [] }
725 .reduce { |cur, new| (cur.empty? or new.empty?) ? [] : (cur | new) },
727 # preemptible: true if all are true, else false
728 "preemptible": retryable_requests
729 .map { |req| req.scheduling_parameters["preemptible"] }
732 # max_run_time: 0 if any are 0 (unlimited), else the maximum
733 "max_run_time": retryable_requests
734 .map { |req| req.scheduling_parameters["max_run_time"] || 0 }
735 .reduce do |cur, new|
736 if cur == 0 or new == 0
747 command: self.command,
749 environment: self.environment,
750 output_path: self.output_path,
751 container_image: self.container_image,
753 runtime_constraints: self.runtime_constraints,
754 scheduling_parameters: scheduling_parameters,
755 secret_mounts: prev_secret_mounts,
756 runtime_token: prev_runtime_token,
757 runtime_user_uuid: self.runtime_user_uuid,
758 runtime_auth_scopes: self.runtime_auth_scopes
760 c = Container.create! c_attrs
761 retryable_requests.each do |cr|
763 leave_modified_by_user_alone do
764 # Use row locking because this increments container_count
765 cr.cumulative_cost += self.cost + self.subrequests_cost
766 cr.container_uuid = c.uuid
773 # Notify container requests associated with this container
774 ContainerRequest.where(container_uuid: uuid,
775 state: ContainerRequest::Committed).each do |cr|
776 leave_modified_by_user_alone do
781 # Cancel outstanding container requests made by this container.
783 includes(:container).
784 where(requesting_container_uuid: uuid,
785 state: ContainerRequest::Committed).each do |cr|
786 leave_modified_by_user_alone do
787 cr.update_attributes!(priority: 0)
789 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
790 # If the child container hasn't started yet, finalize the
791 # child CR now instead of leaving it "on hold", i.e.,
792 # Queued with priority 0. (OTOH, if the child is already
793 # running, leave it alone so it can get cancelled the
794 # usual way, get a copy of the log collection, etc.)
795 cr.update_attributes!(state: ContainerRequest::Final)