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 }
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
53 after_commit { UpdatePriority.run_update_thread }
55 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
56 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
58 api_accessible :user, extend: :common do |t|
60 t.add :container_image
72 t.add :runtime_constraints
77 t.add :scheduling_parameters
78 t.add :runtime_user_uuid
79 t.add :runtime_auth_scopes
81 t.add :gateway_address
82 t.add :interactive_session_started
83 t.add :output_storage_classes
86 # Supported states for a container
91 (Running = 'Running'),
92 (Complete = 'Complete'),
93 (Cancelled = 'Cancelled')
98 Queued => [Locked, Cancelled],
99 Locked => [Queued, Running, Cancelled],
100 Running => [Complete, Cancelled],
101 Complete => [Cancelled]
104 def self.limit_index_columns_read
108 def self.full_text_searchable_columns
109 super - ["secret_mounts", "secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
112 def self.searchable_columns *args
113 super - ["secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
116 def logged_attributes
117 super.except('secret_mounts', 'runtime_token')
120 def state_transitions
124 # Container priority is the highest "computed priority" of any
125 # matching request. The computed priority of a container-submitted
126 # request is the priority of the submitting container. The computed
127 # priority of a user-submitted request is a function of
128 # user-assigned priority and request creation time.
130 return if ![Queued, Locked, Running].include?(state)
131 p = ContainerRequest.
132 where('container_uuid=? and priority>0', uuid).
133 includes(:requesting_container).
136 if cr.requesting_container
137 cr.requesting_container.priority
139 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
142 update_attributes!(priority: p)
145 def propagate_priority
146 return true unless saved_change_to_priority?
147 act_as_system_user do
148 # Update the priority of child container requests to match new
149 # priority of the parent container (ignoring requests with no
150 # container assigned, because their priority doesn't matter).
152 where(requesting_container_uuid: self.uuid,
153 state: ContainerRequest::Committed).
154 where('container_uuid is not null').
155 includes(:container).
157 map(&:update_priority!)
161 # Create a new container (or find an existing one) to satisfy the
162 # given container request.
163 def self.resolve(req)
164 if req.runtime_token.nil?
165 runtime_user = if req.modified_by_user_uuid.nil?
168 User.find_by_uuid(req.modified_by_user_uuid)
170 runtime_auth_scopes = ["all"]
172 auth = ApiClientAuthorization.validate(token: req.runtime_token)
174 raise ArgumentError.new "Invalid runtime token"
176 runtime_user = User.find_by_id(auth.user_id)
177 runtime_auth_scopes = auth.scopes
179 c_attrs = act_as_user runtime_user do
181 command: req.command,
183 environment: req.environment,
184 output_path: req.output_path,
185 container_image: resolve_container_image(req.container_image),
186 mounts: resolve_mounts(req.mounts),
187 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
188 scheduling_parameters: req.scheduling_parameters,
189 secret_mounts: req.secret_mounts,
190 runtime_token: req.runtime_token,
191 runtime_user_uuid: runtime_user.uuid,
192 runtime_auth_scopes: runtime_auth_scopes,
193 output_storage_classes: req.output_storage_classes,
196 act_as_system_user do
197 if req.use_existing && (reusable = find_reusable(c_attrs))
200 Container.create!(c_attrs)
205 # Return a runtime_constraints hash that complies with requested but
206 # is suitable for saving in a container record, i.e., has specific
207 # values instead of ranges.
209 # Doing this as a step separate from other resolutions, like "git
210 # revision range to commit hash", makes sense only when there is no
211 # opportunity to reuse an existing container (e.g., container reuse
212 # is not implemented yet, or we have already found that no existing
213 # containers are suitable).
214 def self.resolve_runtime_constraints(runtime_constraints)
216 runtime_constraints.each do |k, v|
223 if rc['keep_cache_ram'] == 0
224 rc['keep_cache_ram'] = Rails.configuration.Containers.DefaultKeepCacheRAM
229 # Return a mounts hash suitable for a Container, i.e., with every
230 # readonly collection UUID resolved to a PDH.
231 def self.resolve_mounts(mounts)
233 mounts.each do |k, mount|
236 if mount['kind'] != 'collection'
240 uuid = mount.delete 'uuid'
242 if mount['portable_data_hash'].nil? and !uuid.nil?
243 # PDH not supplied, try by UUID
245 readable_by(current_user).
247 select(:portable_data_hash).
250 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
252 mount['portable_data_hash'] = c.portable_data_hash
258 # Return a container_image PDH suitable for a Container.
259 def self.resolve_container_image(container_image)
260 coll = Collection.for_latest_docker_image(container_image)
262 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
264 coll.portable_data_hash
267 def self.find_reusable(attrs)
268 log_reuse_info { "starting with #{Container.all.count} container records in database" }
269 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
270 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
272 candidates = candidates.where('cwd = ?', attrs[:cwd])
273 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
275 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
276 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
278 candidates = candidates.where('output_path = ?', attrs[:output_path])
279 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
281 image = resolve_container_image(attrs[:container_image])
282 candidates = candidates.where('container_image = ?', image)
283 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
285 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
286 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
288 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
289 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
290 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
292 if attrs[:runtime_constraints]['cuda'].nil?
293 attrs[:runtime_constraints]['cuda'] = {
295 'driver_version' => '',
296 'hardware_capability' => '',
300 candidates_inc_cuda = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
301 if candidates_inc_cuda.count == 0 and attrs[:runtime_constraints]['cuda']['device_count'] == 0
302 # Fallback search on containers introduced before CUDA support,
303 # exclude empty CUDA request from query
304 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints].except('cuda')), md5: true)
306 candidates = candidates_inc_cuda
308 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
310 log_reuse_info { "checking for state=Complete with readable output and log..." }
312 select_readable_pdh = Collection.
313 readable_by(current_user).
314 select(:portable_data_hash).
317 usable = candidates.where(state: Complete, exit_code: 0)
318 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
320 usable = usable.where("log IN (#{select_readable_pdh})")
321 log_reuse_info(usable) { "with readable log" }
323 usable = usable.where("output IN (#{select_readable_pdh})")
324 log_reuse_info(usable) { "with readable output" }
326 usable = usable.order('finished_at ASC').limit(1).first
328 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
332 # Check for non-failing Running candidates and return the most likely to finish sooner.
333 log_reuse_info { "checking for state=Running..." }
334 running = candidates.where(state: Running).
335 where("(runtime_status->'error') is null").
336 order('progress desc, started_at asc').
339 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
342 log_reuse_info { "have no containers in Running state" }
345 # Check for Locked or Queued ones and return the most likely to start first.
346 locked_or_queued = candidates.
347 where("state IN (?)", [Locked, Queued]).
348 order('state asc, priority desc, created_at asc').
351 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
352 return locked_or_queued
354 log_reuse_info { "have no containers in Locked or Queued state" }
357 log_reuse_info { "done, no reusable container found" }
363 if self.state != Queued
364 raise LockFailedError.new("cannot lock when #{self.state}")
366 self.update_attributes!(state: Locked)
371 if state_was == Queued and state == Locked
372 if self.priority <= 0
373 raise LockFailedError.new("cannot lock when priority<=0")
375 self.lock_count = self.lock_count+1
381 if self.state != Locked
382 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
384 self.update_attributes!(state: Queued)
389 if state_was == Locked and state == Queued
390 if self.locked_by_uuid != current_api_client_authorization.uuid
391 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
393 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
394 self.state = Cancelled
395 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
400 def self.readable_by(*users_list)
401 # Load optional keyword arguments, if they exist.
402 if users_list.last.is_a? Hash
403 kwargs = users_list.pop
407 if users_list.select { |u| u.is_admin }.any?
410 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
414 [Complete, Cancelled].include?(self.state)
417 def self.for_current_token
418 return if !current_api_client_authorization
419 _, _, _, container_uuid = Thread.current[:token].split('/')
420 if container_uuid.nil?
421 Container.where(auth_uuid: current_api_client_authorization.uuid).first
423 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
424 current_api_client_authorization.uuid,
426 current_api_client_authorization.token).first
432 def fill_field_defaults
433 self.state ||= Queued
434 self.environment ||= {}
435 self.runtime_constraints ||= {}
439 self.scheduling_parameters ||= {}
442 def permission_to_create
443 current_user.andand.is_admin
446 def permission_to_destroy
447 current_user.andand.is_admin
450 def ensure_owner_uuid_is_permitted
451 # validate_change ensures owner_uuid can't be changed at all --
452 # except during create, which requires admin privileges. Checking
453 # permission here would be superfluous.
458 if self.state_changed? and self.state == Running
459 self.started_at ||= db_current_time
462 if self.state_changed? and [Complete, Cancelled].include? self.state
463 self.finished_at ||= db_current_time
467 # Check that well-known runtime status keys have desired data types
468 def validate_runtime_status
470 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
472 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
473 errors.add(:runtime_status, "'#{k}' value must be a string")
480 progress_attrs = [:progress, :runtime_status, :log, :output]
481 final_attrs = [:exit_code, :finished_at]
484 permitted.push(:owner_uuid, :command, :container_image, :cwd,
485 :environment, :mounts, :output_path, :priority,
486 :runtime_constraints, :scheduling_parameters,
487 :secret_mounts, :runtime_token,
488 :runtime_user_uuid, :runtime_auth_scopes,
489 :output_storage_classes)
494 permitted.push :priority, :runtime_status, :log, :lock_count
497 permitted.push :priority
500 permitted.push :priority, *progress_attrs
501 if self.state_changed?
502 permitted.push :started_at, :gateway_address
504 if !self.interactive_session_started_was
505 permitted.push :interactive_session_started
509 if self.state_was == Running
510 permitted.push *final_attrs, *progress_attrs
516 permitted.push :finished_at, *progress_attrs
518 permitted.push :finished_at, :log, :runtime_status
522 # The state_transitions check will add an error message for this
526 if self.state_was == Running &&
527 !current_api_client_authorization.nil? &&
528 (current_api_client_authorization.uuid == self.auth_uuid ||
529 current_api_client_authorization.token == self.runtime_token)
530 # The contained process itself can write final attrs but can't
531 # change priority or log.
532 permitted.push *final_attrs
533 permitted = permitted - [:log, :priority]
534 elsif !current_user.andand.is_admin
535 raise PermissionDeniedError
536 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
537 # When locked, progress fields cannot be updated by the wrong
538 # dispatcher, even though it has admin privileges.
539 permitted = permitted - progress_attrs
541 check_update_whitelist permitted
545 if [Locked, Running].include? self.state
546 # If the Container was already locked, locked_by_uuid must not
547 # changes. Otherwise, the current auth gets the lock.
548 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
553 # The caller can provide a new value for locked_by_uuid, but only
554 # if it's exactly what we expect. This allows a caller to perform
555 # an update like {"state":"Unlocked","locked_by_uuid":null}.
556 if self.locked_by_uuid_changed?
557 if self.locked_by_uuid != need_lock
558 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
561 self.locked_by_uuid = need_lock
565 # Output must exist and be readable by the current user. This is so
566 # that a container cannot "claim" a collection that it doesn't otherwise
567 # have access to just by setting the output field to the collection PDH.
570 readable_by(current_user, {include_trash: true}).
571 where(portable_data_hash: self.output).
574 errors.add :output, "collection must exist and be readable by current user."
580 # If self.final?, this update is superfluous: the final log/output
581 # update will be done when handle_completed calls finalize! on
582 # each requesting CR.
583 return if self.final? || !saved_change_to_log?
584 leave_modified_by_user_alone do
585 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
586 cr.update_collections(container: self, collections: ['log'])
593 if self.auth_uuid_changed?
594 return errors.add :auth_uuid, 'is readonly'
596 if not [Locked, Running].include? self.state
597 # Don't need one. If auth already exists, expire it.
599 # We use db_transaction_time here (not db_current_time) to
600 # ensure the token doesn't validate later in the same
601 # transaction (e.g., in a test case) by satisfying expires_at >
602 # transaction timestamp.
603 self.auth.andand.update_attributes(expires_at: db_transaction_time)
610 if self.runtime_token.nil?
611 if self.runtime_user_uuid.nil?
612 # legacy behavior, we don't have a runtime_user_uuid so get
613 # the user from the highest priority container request, needed
614 # when performing an upgrade and there are queued containers,
616 cr = ContainerRequest.
617 where('container_uuid=? and priority>0', self.uuid).
618 order('priority desc').
621 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
623 self.runtime_user_uuid = cr.modified_by_user_uuid
624 self.runtime_auth_scopes = ["all"]
627 # Generate a new token. This runs with admin credentials as it's done by a
628 # dispatcher user, so expires_at isn't enforced by API.MaxTokenLifetime.
629 self.auth = ApiClientAuthorization.
630 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
632 scopes: self.runtime_auth_scopes)
636 def sort_serialized_attrs
637 if self.environment_changed?
638 self.environment = self.class.deep_sort_hash(self.environment)
640 if self.mounts_changed?
641 self.mounts = self.class.deep_sort_hash(self.mounts)
643 if self.runtime_constraints_changed?
644 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
646 if self.scheduling_parameters_changed?
647 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
649 if self.runtime_auth_scopes_changed?
650 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
654 def update_secret_mounts_md5
655 if self.secret_mounts_changed?
656 self.secret_mounts_md5 = Digest::MD5.hexdigest(
657 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
662 # this runs after update_secret_mounts_md5, so the
663 # secret_mounts_md5 will still reflect the secrets that are being
665 if self.state_changed? && self.final?
666 self.secret_mounts = {}
667 self.runtime_token = nil
671 def clear_runtime_status_when_queued
672 # Avoid leaking status messages between different dispatch attempts
673 if self.state_was == Locked && self.state == Queued
674 self.runtime_status = {}
679 # This container is finished so finalize any associated container requests
680 # that are associated with this container.
681 if saved_change_to_state? and self.final?
682 # These get wiped out by with_lock (which reloads the record),
683 # so record them now in case we need to schedule a retry.
684 prev_secret_mounts = secret_mounts_before_last_save
685 prev_runtime_token = runtime_token_before_last_save
687 # Need to take a lock on the container to ensure that any
688 # concurrent container requests that might try to reuse this
689 # container will block until the container completion
690 # transaction finishes. This ensure that concurrent container
691 # requests that try to reuse this container are finalized (on
692 # Complete) or don't reuse it (on Cancelled).
694 act_as_system_user do
695 if self.state == Cancelled
696 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
698 retryable_requests = []
701 if retryable_requests.any?
703 command: self.command,
705 environment: self.environment,
706 output_path: self.output_path,
707 container_image: self.container_image,
709 runtime_constraints: self.runtime_constraints,
710 scheduling_parameters: self.scheduling_parameters,
711 secret_mounts: prev_secret_mounts,
712 runtime_token: prev_runtime_token,
713 runtime_user_uuid: self.runtime_user_uuid,
714 runtime_auth_scopes: self.runtime_auth_scopes
716 c = Container.create! c_attrs
717 retryable_requests.each do |cr|
719 leave_modified_by_user_alone do
720 # Use row locking because this increments container_count
721 cr.container_uuid = c.uuid
728 # Notify container requests associated with this container
729 ContainerRequest.where(container_uuid: uuid,
730 state: ContainerRequest::Committed).each do |cr|
731 leave_modified_by_user_alone do
736 # Cancel outstanding container requests made by this container.
738 includes(:container).
739 where(requesting_container_uuid: uuid,
740 state: ContainerRequest::Committed).each do |cr|
741 leave_modified_by_user_alone do
742 cr.update_attributes!(priority: 0)
744 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
745 # If the child container hasn't started yet, finalize the
746 # child CR now instead of leaving it "on hold", i.e.,
747 # Queued with priority 0. (OTOH, if the child is already
748 # running, leave it alone so it can get cancelled the
749 # usual way, get a copy of the log collection, etc.)
750 cr.update_attributes!(state: ContainerRequest::Final)