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
81 # Supported states for a container
86 (Running = 'Running'),
87 (Complete = 'Complete'),
88 (Cancelled = 'Cancelled')
93 Queued => [Locked, Cancelled],
94 Locked => [Queued, Running, Cancelled],
95 Running => [Complete, Cancelled],
96 Complete => [Cancelled]
99 def self.limit_index_columns_read
103 def self.full_text_searchable_columns
104 super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
107 def self.searchable_columns *args
108 super - ["secret_mounts_md5", "runtime_token"]
111 def logged_attributes
112 super.except('secret_mounts', 'runtime_token')
115 def state_transitions
119 # Container priority is the highest "computed priority" of any
120 # matching request. The computed priority of a container-submitted
121 # request is the priority of the submitting container. The computed
122 # priority of a user-submitted request is a function of
123 # user-assigned priority and request creation time.
125 return if ![Queued, Locked, Running].include?(state)
126 p = ContainerRequest.
127 where('container_uuid=? and priority>0', uuid).
128 includes(:requesting_container).
131 if cr.requesting_container
132 cr.requesting_container.priority
134 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
137 update_attributes!(priority: p)
140 def propagate_priority
141 return true unless priority_changed?
142 act_as_system_user do
143 # Update the priority of child container requests to match new
144 # priority of the parent container (ignoring requests with no
145 # container assigned, because their priority doesn't matter).
147 where(requesting_container_uuid: self.uuid,
148 state: ContainerRequest::Committed).
149 where('container_uuid is not null').
150 includes(:container).
152 map(&:update_priority!)
156 # Create a new container (or find an existing one) to satisfy the
157 # given container request.
158 def self.resolve(req)
159 if req.runtime_token.nil?
160 runtime_user = if req.modified_by_user_uuid.nil?
163 User.find_by_uuid(req.modified_by_user_uuid)
165 runtime_auth_scopes = ["all"]
167 auth = ApiClientAuthorization.validate(token: req.runtime_token)
169 raise ArgumentError.new "Invalid runtime token"
171 runtime_user = User.find_by_id(auth.user_id)
172 runtime_auth_scopes = auth.scopes
174 c_attrs = act_as_user runtime_user do
176 command: req.command,
178 environment: req.environment,
179 output_path: req.output_path,
180 container_image: resolve_container_image(req.container_image),
181 mounts: resolve_mounts(req.mounts),
182 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
183 scheduling_parameters: req.scheduling_parameters,
184 secret_mounts: req.secret_mounts,
185 runtime_token: req.runtime_token,
186 runtime_user_uuid: runtime_user.uuid,
187 runtime_auth_scopes: runtime_auth_scopes
190 act_as_system_user do
191 if req.use_existing && (reusable = find_reusable(c_attrs))
194 Container.create!(c_attrs)
199 # Return a runtime_constraints hash that complies with requested but
200 # is suitable for saving in a container record, i.e., has specific
201 # values instead of ranges.
203 # Doing this as a step separate from other resolutions, like "git
204 # revision range to commit hash", makes sense only when there is no
205 # opportunity to reuse an existing container (e.g., container reuse
206 # is not implemented yet, or we have already found that no existing
207 # containers are suitable).
208 def self.resolve_runtime_constraints(runtime_constraints)
212 Rails.configuration.Containers.DefaultKeepCacheRAM,
214 defaults.merge(runtime_constraints).each do |k, v|
224 # Return a mounts hash suitable for a Container, i.e., with every
225 # readonly collection UUID resolved to a PDH.
226 def self.resolve_mounts(mounts)
228 mounts.each do |k, mount|
231 if mount['kind'] != 'collection'
235 uuid = mount.delete 'uuid'
237 if mount['portable_data_hash'].nil? and !uuid.nil?
238 # PDH not supplied, try by UUID
240 readable_by(current_user).
242 select(:portable_data_hash).
245 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
247 mount['portable_data_hash'] = c.portable_data_hash
253 # Return a container_image PDH suitable for a Container.
254 def self.resolve_container_image(container_image)
255 coll = Collection.for_latest_docker_image(container_image)
257 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
259 coll.portable_data_hash
262 def self.find_reusable(attrs)
263 log_reuse_info { "starting with #{Container.all.count} container records in database" }
264 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
265 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
267 candidates = candidates.where('cwd = ?', attrs[:cwd])
268 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
270 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
271 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
273 candidates = candidates.where('output_path = ?', attrs[:output_path])
274 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
276 image = resolve_container_image(attrs[:container_image])
277 candidates = candidates.where('container_image = ?', image)
278 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
280 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
281 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
283 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
284 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
285 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
287 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
288 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
290 log_reuse_info { "checking for state=Complete with readable output and log..." }
292 select_readable_pdh = Collection.
293 readable_by(current_user).
294 select(:portable_data_hash).
297 usable = candidates.where(state: Complete, exit_code: 0)
298 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
300 usable = usable.where("log IN (#{select_readable_pdh})")
301 log_reuse_info(usable) { "with readable log" }
303 usable = usable.where("output IN (#{select_readable_pdh})")
304 log_reuse_info(usable) { "with readable output" }
306 usable = usable.order('finished_at ASC').limit(1).first
308 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
312 # Check for non-failing Running candidates and return the most likely to finish sooner.
313 log_reuse_info { "checking for state=Running..." }
314 running = candidates.where(state: Running).
315 where("(runtime_status->'error') is null").
316 order('progress desc, started_at asc').
319 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
322 log_reuse_info { "have no containers in Running state" }
325 # Check for Locked or Queued ones and return the most likely to start first.
326 locked_or_queued = candidates.
327 where("state IN (?)", [Locked, Queued]).
328 order('state asc, priority desc, created_at asc').
331 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
332 return locked_or_queued
334 log_reuse_info { "have no containers in Locked or Queued state" }
337 log_reuse_info { "done, no reusable container found" }
343 if self.state != Queued
344 raise LockFailedError.new("cannot lock when #{self.state}")
346 self.update_attributes!(state: Locked)
351 if state_was == Queued and state == Locked
352 if self.priority <= 0
353 raise LockFailedError.new("cannot lock when priority<=0")
355 self.lock_count = self.lock_count+1
361 if self.state != Locked
362 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
364 self.update_attributes!(state: Queued)
369 if state_was == Locked and state == Queued
370 if self.locked_by_uuid != current_api_client_authorization.uuid
371 raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
373 if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
374 self.state = Cancelled
375 self.runtime_status = {error: "Failed to start container. Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
380 def self.readable_by(*users_list)
381 # Load optional keyword arguments, if they exist.
382 if users_list.last.is_a? Hash
383 kwargs = users_list.pop
387 if users_list.select { |u| u.is_admin }.any?
390 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
394 [Complete, Cancelled].include?(self.state)
397 def self.for_current_token
398 return if !current_api_client_authorization
399 _, _, _, container_uuid = Thread.current[:token].split('/')
400 if container_uuid.nil?
401 Container.where(auth_uuid: current_api_client_authorization.uuid).first
403 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
404 current_api_client_authorization.uuid,
406 current_api_client_authorization.token).first
412 def fill_field_defaults
413 self.state ||= Queued
414 self.environment ||= {}
415 self.runtime_constraints ||= {}
419 self.scheduling_parameters ||= {}
422 def permission_to_create
423 current_user.andand.is_admin
426 def ensure_owner_uuid_is_permitted
427 # validate_change ensures owner_uuid can't be changed at all --
428 # except during create, which requires admin privileges. Checking
429 # permission here would be superfluous.
434 if self.state_changed? and self.state == Running
435 self.started_at ||= db_current_time
438 if self.state_changed? and [Complete, Cancelled].include? self.state
439 self.finished_at ||= db_current_time
443 # Check that well-known runtime status keys have desired data types
444 def validate_runtime_status
446 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
448 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
449 errors.add(:runtime_status, "'#{k}' value must be a string")
456 progress_attrs = [:progress, :runtime_status, :log, :output]
457 final_attrs = [:exit_code, :finished_at]
460 permitted.push(:owner_uuid, :command, :container_image, :cwd,
461 :environment, :mounts, :output_path, :priority,
462 :runtime_constraints, :scheduling_parameters,
463 :secret_mounts, :runtime_token,
464 :runtime_user_uuid, :runtime_auth_scopes)
469 permitted.push :priority, :runtime_status, :log, :lock_count
472 permitted.push :priority
475 permitted.push :priority, *progress_attrs
476 if self.state_changed?
477 permitted.push :started_at
481 if self.state_was == Running
482 permitted.push *final_attrs, *progress_attrs
488 permitted.push :finished_at, *progress_attrs
490 permitted.push :finished_at, :log, :runtime_status
494 # The state_transitions check will add an error message for this
498 if self.state_was == Running &&
499 !current_api_client_authorization.nil? &&
500 (current_api_client_authorization.uuid == self.auth_uuid ||
501 current_api_client_authorization.token == self.runtime_token)
502 # The contained process itself can write final attrs but can't
503 # change priority or log.
504 permitted.push *final_attrs
505 permitted = permitted - [:log, :priority]
506 elsif !current_user.andand.is_admin
507 raise PermissionDeniedError
508 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
509 # When locked, progress fields cannot be updated by the wrong
510 # dispatcher, even though it has admin privileges.
511 permitted = permitted - progress_attrs
513 check_update_whitelist permitted
517 if [Locked, Running].include? self.state
518 # If the Container was already locked, locked_by_uuid must not
519 # changes. Otherwise, the current auth gets the lock.
520 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
525 # The caller can provide a new value for locked_by_uuid, but only
526 # if it's exactly what we expect. This allows a caller to perform
527 # an update like {"state":"Unlocked","locked_by_uuid":null}.
528 if self.locked_by_uuid_changed?
529 if self.locked_by_uuid != need_lock
530 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
533 self.locked_by_uuid = need_lock
537 # Output must exist and be readable by the current user. This is so
538 # that a container cannot "claim" a collection that it doesn't otherwise
539 # have access to just by setting the output field to the collection PDH.
542 readable_by(current_user, {include_trash: true}).
543 where(portable_data_hash: self.output).
546 errors.add :output, "collection must exist and be readable by current user."
552 # If self.final?, this update is superfluous: the final log/output
553 # update will be done when handle_completed calls finalize! on
554 # each requesting CR.
555 return if self.final? || !self.log_changed?
556 leave_modified_by_user_alone do
557 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
558 cr.update_collections(container: self, collections: ['log'])
565 if self.auth_uuid_changed?
566 return errors.add :auth_uuid, 'is readonly'
568 if not [Locked, Running].include? self.state
570 self.auth.andand.update_attributes(expires_at: db_current_time)
577 if self.runtime_token.nil?
578 if self.runtime_user_uuid.nil?
579 # legacy behavior, we don't have a runtime_user_uuid so get
580 # the user from the highest priority container request, needed
581 # when performing an upgrade and there are queued containers,
583 cr = ContainerRequest.
584 where('container_uuid=? and priority>0', self.uuid).
585 order('priority desc').
588 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
590 self.runtime_user_uuid = cr.modified_by_user_uuid
591 self.runtime_auth_scopes = ["all"]
594 # generate a new token
595 self.auth = ApiClientAuthorization.
596 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
598 scopes: self.runtime_auth_scopes)
602 def sort_serialized_attrs
603 if self.environment_changed?
604 self.environment = self.class.deep_sort_hash(self.environment)
606 if self.mounts_changed?
607 self.mounts = self.class.deep_sort_hash(self.mounts)
609 if self.runtime_constraints_changed?
610 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
612 if self.scheduling_parameters_changed?
613 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
615 if self.runtime_auth_scopes_changed?
616 self.runtime_auth_scopes = self.runtime_auth_scopes.sort
620 def update_secret_mounts_md5
621 if self.secret_mounts_changed?
622 self.secret_mounts_md5 = Digest::MD5.hexdigest(
623 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
628 # this runs after update_secret_mounts_md5, so the
629 # secret_mounts_md5 will still reflect the secrets that are being
631 if self.state_changed? && self.final?
632 self.secret_mounts = {}
633 self.runtime_token = nil
637 def clear_runtime_status_when_queued
638 # Avoid leaking status messages between different dispatch attempts
639 if self.state_was == Locked && self.state == Queued
640 self.runtime_status = {}
645 # This container is finished so finalize any associated container requests
646 # that are associated with this container.
647 if self.state_changed? and self.final?
648 # These get wiped out by with_lock (which reloads the record),
649 # so record them now in case we need to schedule a retry.
650 prev_secret_mounts = self.secret_mounts_was
651 prev_runtime_token = self.runtime_token_was
653 # Need to take a lock on the container to ensure that any
654 # concurrent container requests that might try to reuse this
655 # container will block until the container completion
656 # transaction finishes. This ensure that concurrent container
657 # requests that try to reuse this container are finalized (on
658 # Complete) or don't reuse it (on Cancelled).
660 act_as_system_user do
661 if self.state == Cancelled
662 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
664 retryable_requests = []
667 if retryable_requests.any?
669 command: self.command,
671 environment: self.environment,
672 output_path: self.output_path,
673 container_image: self.container_image,
675 runtime_constraints: self.runtime_constraints,
676 scheduling_parameters: self.scheduling_parameters,
677 secret_mounts: prev_secret_mounts,
678 runtime_token: prev_runtime_token,
679 runtime_user_uuid: self.runtime_user_uuid,
680 runtime_auth_scopes: self.runtime_auth_scopes
682 c = Container.create! c_attrs
683 retryable_requests.each do |cr|
685 leave_modified_by_user_alone do
686 # Use row locking because this increments container_count
687 cr.container_uuid = c.uuid
694 # Notify container requests associated with this container
695 ContainerRequest.where(container_uuid: uuid,
696 state: ContainerRequest::Committed).each do |cr|
697 leave_modified_by_user_alone do
702 # Cancel outstanding container requests made by this container.
704 includes(:container).
705 where(requesting_container_uuid: uuid,
706 state: ContainerRequest::Committed).each do |cr|
707 leave_modified_by_user_alone do
708 cr.update_attributes!(priority: 0)
710 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
711 # If the child container hasn't started yet, finalize the
712 # child CR now instead of leaving it "on hold", i.e.,
713 # Queued with priority 0. (OTOH, if the child is already
714 # running, leave it alone so it can get cancelled the
715 # usual way, get a copy of the log collection, etc.)
716 cr.update_attributes!(state: ContainerRequest::Final)