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, :jsonbHash, default: {}
26 serialize :environment, Hash
27 serialize :mounts, Hash
28 serialize :runtime_constraints, Hash
29 serialize :command, Array
30 serialize :scheduling_parameters, Hash
32 before_validation :fill_field_defaults, :if => :new_record?
33 before_validation :set_timestamps
34 before_validation :check_lock
35 before_validation :check_unlock
36 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
37 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
38 validate :validate_runtime_status
39 validate :validate_state_change
40 validate :validate_change
41 validate :validate_lock
42 validate :validate_output
43 after_validation :assign_auth
44 before_save :sort_serialized_attrs
45 before_save :update_secret_mounts_md5
46 before_save :scrub_secrets
47 before_save :clear_runtime_status_when_queued
48 after_save :update_cr_logs
49 after_save :handle_completed
50 after_save :propagate_priority
51 after_commit { UpdatePriority.run_update_thread }
53 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
54 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
56 api_accessible :user, extend: :common do |t|
58 t.add :container_image
70 t.add :runtime_constraints
75 t.add :scheduling_parameters
76 t.add :runtime_user_uuid
77 t.add :runtime_auth_scopes
79 t.add :gateway_address
82 # Supported states for a container
87 (Running = 'Running'),
88 (Complete = 'Complete'),
89 (Cancelled = 'Cancelled')
94 Queued => [Locked, Cancelled],
95 Locked => [Queued, Running, Cancelled],
96 Running => [Complete, Cancelled],
97 Complete => [Cancelled]
100 def self.limit_index_columns_read
104 def self.full_text_searchable_columns
105 super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
108 def self.searchable_columns *args
109 super - ["secret_mounts_md5", "runtime_token"]
112 def logged_attributes
113 super.except('secret_mounts', 'runtime_token')
116 def state_transitions
120 # Container priority is the highest "computed priority" of any
121 # matching request. The computed priority of a container-submitted
122 # request is the priority of the submitting container. The computed
123 # priority of a user-submitted request is a function of
124 # user-assigned priority and request creation time.
126 return if ![Queued, Locked, Running].include?(state)
127 p = ContainerRequest.
128 where('container_uuid=? and priority>0', uuid).
129 includes(:requesting_container).
132 if cr.requesting_container
133 cr.requesting_container.priority
135 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
138 update_attributes!(priority: p)
141 def propagate_priority
142 return true unless saved_change_to_priority?
143 act_as_system_user do
144 # Update the priority of child container requests to match new
145 # priority of the parent container (ignoring requests with no
146 # container assigned, because their priority doesn't matter).
148 where(requesting_container_uuid: self.uuid,
149 state: ContainerRequest::Committed).
150 where('container_uuid is not null').
151 includes(:container).
153 map(&:update_priority!)
157 # Create a new container (or find an existing one) to satisfy the
158 # given container request.
159 def self.resolve(req)
160 if req.runtime_token.nil?
161 runtime_user = if req.modified_by_user_uuid.nil?
164 User.find_by_uuid(req.modified_by_user_uuid)
166 runtime_auth_scopes = ["all"]
168 auth = ApiClientAuthorization.validate(token: req.runtime_token)
170 raise ArgumentError.new "Invalid runtime token"
172 runtime_user = User.find_by_id(auth.user_id)
173 runtime_auth_scopes = auth.scopes
175 c_attrs = act_as_user runtime_user do
177 command: req.command,
179 environment: req.environment,
180 output_path: req.output_path,
181 container_image: resolve_container_image(req.container_image),
182 mounts: resolve_mounts(req.mounts),
183 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
184 scheduling_parameters: req.scheduling_parameters,
185 secret_mounts: req.secret_mounts,
186 runtime_token: req.runtime_token,
187 runtime_user_uuid: runtime_user.uuid,
188 runtime_auth_scopes: runtime_auth_scopes
191 act_as_system_user do
192 if req.use_existing && (reusable = find_reusable(c_attrs))
195 Container.create!(c_attrs)
200 # Return a runtime_constraints hash that complies with requested but
201 # is suitable for saving in a container record, i.e., has specific
202 # values instead of ranges.
204 # Doing this as a step separate from other resolutions, like "git
205 # revision range to commit hash", makes sense only when there is no
206 # opportunity to reuse an existing container (e.g., container reuse
207 # is not implemented yet, or we have already found that no existing
208 # containers are suitable).
209 def self.resolve_runtime_constraints(runtime_constraints)
213 Rails.configuration.Containers.DefaultKeepCacheRAM,
215 defaults.merge(runtime_constraints).each do |k, v|
225 # Return a mounts hash suitable for a Container, i.e., with every
226 # readonly collection UUID resolved to a PDH.
227 def self.resolve_mounts(mounts)
229 mounts.each do |k, mount|
232 if mount['kind'] != 'collection'
236 uuid = mount.delete 'uuid'
238 if mount['portable_data_hash'].nil? and !uuid.nil?
239 # PDH not supplied, try by UUID
241 readable_by(current_user).
243 select(:portable_data_hash).
246 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
248 mount['portable_data_hash'] = c.portable_data_hash
254 # Return a container_image PDH suitable for a Container.
255 def self.resolve_container_image(container_image)
256 coll = Collection.for_latest_docker_image(container_image)
258 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
260 coll.portable_data_hash
263 def self.find_reusable(attrs)
264 log_reuse_info { "starting with #{Container.all.count} container records in database" }
265 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
266 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
268 candidates = candidates.where('cwd = ?', attrs[:cwd])
269 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
271 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
272 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
274 candidates = candidates.where('output_path = ?', attrs[:output_path])
275 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
277 image = resolve_container_image(attrs[:container_image])
278 candidates = candidates.where('container_image = ?', image)
279 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
281 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
282 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
284 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
285 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
286 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
288 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
289 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
291 log_reuse_info { "checking for state=Complete with readable output and log..." }
293 select_readable_pdh = Collection.
294 readable_by(current_user).
295 select(:portable_data_hash).
298 usable = candidates.where(state: Complete, exit_code: 0)
299 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
301 usable = usable.where("log IN (#{select_readable_pdh})")
302 log_reuse_info(usable) { "with readable log" }
304 usable = usable.where("output IN (#{select_readable_pdh})")
305 log_reuse_info(usable) { "with readable output" }
307 usable = usable.order('finished_at ASC').limit(1).first
309 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
313 # Check for non-failing Running candidates and return the most likely to finish sooner.
314 log_reuse_info { "checking for state=Running..." }
315 running = candidates.where(state: Running).
316 where("(runtime_status->'error') is null").
317 order('progress desc, started_at asc').
320 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
323 log_reuse_info { "have no containers in Running state" }
326 # Check for Locked or Queued ones and return the most likely to start first.
327 locked_or_queued = candidates.
328 where("state IN (?)", [Locked, Queued]).
329 order('state asc, priority desc, created_at asc').
332 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
333 return locked_or_queued
335 log_reuse_info { "have no containers in Locked or Queued state" }
338 log_reuse_info { "done, no reusable container found" }
344 if self.state != Queued
345 raise LockFailedError.new("cannot lock when #{self.state}")
347 self.update_attributes!(state: Locked)
352 if state_was == Queued and state == Locked
353 if self.priority <= 0
354 raise LockFailedError.new("cannot lock when priority<=0")
356 self.lock_count = self.lock_count+1
362 if self.state != Locked
363 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
365 self.update_attributes!(state: Queued)
370 if state_was == Locked and state == Queued
371 if self.locked_by_uuid != current_api_client_authorization.uuid
372 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
374 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
375 self.state = Cancelled
376 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
381 def self.readable_by(*users_list)
382 # Load optional keyword arguments, if they exist.
383 if users_list.last.is_a? Hash
384 kwargs = users_list.pop
388 if users_list.select { |u| u.is_admin }.any?
391 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
395 [Complete, Cancelled].include?(self.state)
398 def self.for_current_token
399 return if !current_api_client_authorization
400 _, _, _, container_uuid = Thread.current[:token].split('/')
401 if container_uuid.nil?
402 Container.where(auth_uuid: current_api_client_authorization.uuid).first
404 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
405 current_api_client_authorization.uuid,
407 current_api_client_authorization.token).first
413 def fill_field_defaults
414 self.state ||= Queued
415 self.environment ||= {}
416 self.runtime_constraints ||= {}
420 self.scheduling_parameters ||= {}
423 def permission_to_create
424 current_user.andand.is_admin
427 def permission_to_destroy
428 current_user.andand.is_admin
431 def ensure_owner_uuid_is_permitted
432 # validate_change ensures owner_uuid can't be changed at all --
433 # except during create, which requires admin privileges. Checking
434 # permission here would be superfluous.
439 if self.state_changed? and self.state == Running
440 self.started_at ||= db_current_time
443 if self.state_changed? and [Complete, Cancelled].include? self.state
444 self.finished_at ||= db_current_time
448 # Check that well-known runtime status keys have desired data types
449 def validate_runtime_status
451 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
453 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
454 errors.add(:runtime_status, "'#{k}' value must be a string")
461 progress_attrs = [:progress, :runtime_status, :log, :output]
462 final_attrs = [:exit_code, :finished_at]
465 permitted.push(:owner_uuid, :command, :container_image, :cwd,
466 :environment, :mounts, :output_path, :priority,
467 :runtime_constraints, :scheduling_parameters,
468 :secret_mounts, :runtime_token,
469 :runtime_user_uuid, :runtime_auth_scopes)
474 permitted.push :priority, :runtime_status, :log, :lock_count
477 permitted.push :priority
480 permitted.push :priority, *progress_attrs
481 if self.state_changed?
482 permitted.push :started_at, :gateway_address
486 if self.state_was == Running
487 permitted.push *final_attrs, *progress_attrs
493 permitted.push :finished_at, *progress_attrs
495 permitted.push :finished_at, :log, :runtime_status
499 # The state_transitions check will add an error message for this
503 if self.state_was == Running &&
504 !current_api_client_authorization.nil? &&
505 (current_api_client_authorization.uuid == self.auth_uuid ||
506 current_api_client_authorization.token == self.runtime_token)
507 # The contained process itself can write final attrs but can't
508 # change priority or log.
509 permitted.push *final_attrs
510 permitted = permitted - [:log, :priority]
511 elsif !current_user.andand.is_admin
512 raise PermissionDeniedError
513 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
514 # When locked, progress fields cannot be updated by the wrong
515 # dispatcher, even though it has admin privileges.
516 permitted = permitted - progress_attrs
518 check_update_whitelist permitted
522 if [Locked, Running].include? self.state
523 # If the Container was already locked, locked_by_uuid must not
524 # changes. Otherwise, the current auth gets the lock.
525 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
530 # The caller can provide a new value for locked_by_uuid, but only
531 # if it's exactly what we expect. This allows a caller to perform
532 # an update like {"state":"Unlocked","locked_by_uuid":null}.
533 if self.locked_by_uuid_changed?
534 if self.locked_by_uuid != need_lock
535 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
538 self.locked_by_uuid = need_lock
542 # Output must exist and be readable by the current user. This is so
543 # that a container cannot "claim" a collection that it doesn't otherwise
544 # have access to just by setting the output field to the collection PDH.
547 readable_by(current_user, {include_trash: true}).
548 where(portable_data_hash: self.output).
551 errors.add :output, "collection must exist and be readable by current user."
557 # If self.final?, this update is superfluous: the final log/output
558 # update will be done when handle_completed calls finalize! on
559 # each requesting CR.
560 return if self.final? || !saved_change_to_log?
561 leave_modified_by_user_alone do
562 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
563 cr.update_collections(container: self, collections: ['log'])
570 if self.auth_uuid_changed?
571 return errors.add :auth_uuid, 'is readonly'
573 if not [Locked, Running].include? self.state
574 # Don't need one. If auth already exists, expire it.
576 # We use db_transaction_time here (not db_current_time) to
577 # ensure the token doesn't validate later in the same
578 # transaction (e.g., in a test case) by satisfying expires_at >
579 # transaction timestamp.
580 self.auth.andand.update_attributes(expires_at: db_transaction_time)
587 if self.runtime_token.nil?
588 if self.runtime_user_uuid.nil?
589 # legacy behavior, we don't have a runtime_user_uuid so get
590 # the user from the highest priority container request, needed
591 # when performing an upgrade and there are queued containers,
593 cr = ContainerRequest.
594 where('container_uuid=? and priority>0', self.uuid).
595 order('priority desc').
598 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
600 self.runtime_user_uuid = cr.modified_by_user_uuid
601 self.runtime_auth_scopes = ["all"]
604 # generate a new token
605 self.auth = ApiClientAuthorization.
606 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
608 scopes: self.runtime_auth_scopes)
612 def sort_serialized_attrs
613 if self.environment_changed?
614 self.environment = self.class.deep_sort_hash(self.environment)
616 if self.mounts_changed?
617 self.mounts = self.class.deep_sort_hash(self.mounts)
619 if self.runtime_constraints_changed?
620 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
622 if self.scheduling_parameters_changed?
623 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
625 if self.runtime_auth_scopes_changed?
626 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
630 def update_secret_mounts_md5
631 if self.secret_mounts_changed?
632 self.secret_mounts_md5 = Digest::MD5.hexdigest(
633 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
638 # this runs after update_secret_mounts_md5, so the
639 # secret_mounts_md5 will still reflect the secrets that are being
641 if self.state_changed? && self.final?
642 self.secret_mounts = {}
643 self.runtime_token = nil
647 def clear_runtime_status_when_queued
648 # Avoid leaking status messages between different dispatch attempts
649 if self.state_was == Locked && self.state == Queued
650 self.runtime_status = {}
655 # This container is finished so finalize any associated container requests
656 # that are associated with this container.
657 if saved_change_to_state? and self.final?
658 # These get wiped out by with_lock (which reloads the record),
659 # so record them now in case we need to schedule a retry.
660 prev_secret_mounts = secret_mounts_before_last_save
661 prev_runtime_token = runtime_token_before_last_save
663 # Need to take a lock on the container to ensure that any
664 # concurrent container requests that might try to reuse this
665 # container will block until the container completion
666 # transaction finishes. This ensure that concurrent container
667 # requests that try to reuse this container are finalized (on
668 # Complete) or don't reuse it (on Cancelled).
670 act_as_system_user do
671 if self.state == Cancelled
672 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
674 retryable_requests = []
677 if retryable_requests.any?
679 command: self.command,
681 environment: self.environment,
682 output_path: self.output_path,
683 container_image: self.container_image,
685 runtime_constraints: self.runtime_constraints,
686 scheduling_parameters: self.scheduling_parameters,
687 secret_mounts: prev_secret_mounts,
688 runtime_token: prev_runtime_token,
689 runtime_user_uuid: self.runtime_user_uuid,
690 runtime_auth_scopes: self.runtime_auth_scopes
692 c = Container.create! c_attrs
693 retryable_requests.each do |cr|
695 leave_modified_by_user_alone do
696 # Use row locking because this increments container_count
697 cr.container_uuid = c.uuid
704 # Notify container requests associated with this container
705 ContainerRequest.where(container_uuid: uuid,
706 state: ContainerRequest::Committed).each do |cr|
707 leave_modified_by_user_alone do
712 # Cancel outstanding container requests made by this container.
714 includes(:container).
715 where(requesting_container_uuid: uuid,
716 state: ContainerRequest::Committed).each do |cr|
717 leave_modified_by_user_alone do
718 cr.update_attributes!(priority: 0)
720 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
721 # If the child container hasn't started yet, finalize the
722 # child CR now instead of leaving it "on hold", i.e.,
723 # Queued with priority 0. (OTOH, if the child is already
724 # running, leave it alone so it can get cancelled the
725 # usual way, get a copy of the log collection, etc.)
726 cr.update_attributes!(state: ContainerRequest::Final)