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 serialize :environment, Hash
21 serialize :mounts, Hash
22 serialize :runtime_constraints, Hash
23 serialize :command, Array
24 serialize :scheduling_parameters, Hash
25 serialize :secret_mounts, Hash
26 serialize :runtime_status, Hash
28 before_validation :fill_field_defaults, :if => :new_record?
29 before_validation :set_timestamps
30 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
31 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
32 validate :validate_runtime_status
33 validate :validate_state_change
34 validate :validate_change
35 validate :validate_lock
36 validate :validate_output
37 after_validation :assign_auth
38 before_save :sort_serialized_attrs
39 before_save :update_secret_mounts_md5
40 before_save :scrub_secrets
41 before_save :clear_runtime_status_when_queued
42 after_save :update_cr_logs
43 after_save :handle_completed
44 after_save :propagate_priority
45 after_commit { UpdatePriority.run_update_thread }
47 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
48 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
50 api_accessible :user, extend: :common do |t|
52 t.add :container_image
64 t.add :runtime_constraints
69 t.add :scheduling_parameters
72 # Supported states for a container
77 (Running = 'Running'),
78 (Complete = 'Complete'),
79 (Cancelled = 'Cancelled')
84 Queued => [Locked, Cancelled],
85 Locked => [Queued, Running, Cancelled],
86 Running => [Complete, Cancelled]
89 def self.limit_index_columns_read
93 def self.full_text_searchable_columns
94 super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
97 def self.searchable_columns *args
98 super - ["secret_mounts_md5", "runtime_token"]
101 def logged_attributes
102 super.except('secret_mounts', 'runtime_token')
105 def state_transitions
109 # Container priority is the highest "computed priority" of any
110 # matching request. The computed priority of a container-submitted
111 # request is the priority of the submitting container. The computed
112 # priority of a user-submitted request is a function of
113 # user-assigned priority and request creation time.
115 return if ![Queued, Locked, Running].include?(state)
116 p = ContainerRequest.
117 where('container_uuid=? and priority>0', uuid).
118 includes(:requesting_container).
121 if cr.requesting_container
122 cr.requesting_container.priority
124 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
127 update_attributes!(priority: p)
130 def propagate_priority
131 return true unless priority_changed?
132 act_as_system_user do
133 # Update the priority of child container requests to match new
134 # priority of the parent container (ignoring requests with no
135 # container assigned, because their priority doesn't matter).
137 where(requesting_container_uuid: self.uuid,
138 state: ContainerRequest::Committed).
139 where('container_uuid is not null').
140 includes(:container).
142 map(&:update_priority!)
146 # Create a new container (or find an existing one) to satisfy the
147 # given container request.
148 def self.resolve(req)
149 if req.runtime_token.nil?
150 runtime_user = if req.modified_by_user_uuid.nil?
153 User.find_by_uuid(req.modified_by_user_uuid)
155 runtime_auth_scopes = ["all"]
157 auth = ApiClientAuthorization.validate(token: req.runtime_token)
159 raise ArgumentError.new "Invalid runtime token"
161 runtime_user = User.find_by_id(auth.user_id)
162 runtime_auth_scopes = auth.scopes
164 c_attrs = act_as_user runtime_user do
166 command: req.command,
168 environment: req.environment,
169 output_path: req.output_path,
170 container_image: resolve_container_image(req.container_image),
171 mounts: resolve_mounts(req.mounts),
172 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
173 scheduling_parameters: req.scheduling_parameters,
174 secret_mounts: req.secret_mounts,
175 runtime_token: req.runtime_token,
176 runtime_user_uuid: runtime_user.uuid,
177 runtime_auth_scopes: runtime_auth_scopes
180 act_as_system_user do
181 if req.use_existing && (reusable = find_reusable(c_attrs))
184 Container.create!(c_attrs)
189 # Return a runtime_constraints hash that complies with requested but
190 # is suitable for saving in a container record, i.e., has specific
191 # values instead of ranges.
193 # Doing this as a step separate from other resolutions, like "git
194 # revision range to commit hash", makes sense only when there is no
195 # opportunity to reuse an existing container (e.g., container reuse
196 # is not implemented yet, or we have already found that no existing
197 # containers are suitable).
198 def self.resolve_runtime_constraints(runtime_constraints)
202 Rails.configuration.container_default_keep_cache_ram,
204 defaults.merge(runtime_constraints).each do |k, v|
214 # Return a mounts hash suitable for a Container, i.e., with every
215 # readonly collection UUID resolved to a PDH.
216 def self.resolve_mounts(mounts)
218 mounts.each do |k, mount|
221 if mount['kind'] != 'collection'
224 if (uuid = mount.delete 'uuid')
226 readable_by(current_user).
228 select(:portable_data_hash).
231 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
233 if mount['portable_data_hash'].nil?
234 # PDH not supplied by client
235 mount['portable_data_hash'] = c.portable_data_hash
236 elsif mount['portable_data_hash'] != c.portable_data_hash
237 # UUID and PDH supplied by client, but they don't agree
238 raise ArgumentError.new "cannot mount collection #{uuid.inspect}: current portable_data_hash #{c.portable_data_hash.inspect} does not match #{c['portable_data_hash'].inspect} in request"
245 # Return a container_image PDH suitable for a Container.
246 def self.resolve_container_image(container_image)
247 coll = Collection.for_latest_docker_image(container_image)
249 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
251 coll.portable_data_hash
254 def self.find_reusable(attrs)
255 log_reuse_info { "starting with #{Container.all.count} container records in database" }
256 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
257 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
259 candidates = candidates.where('cwd = ?', attrs[:cwd])
260 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
262 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
263 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
265 candidates = candidates.where('output_path = ?', attrs[:output_path])
266 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
268 image = resolve_container_image(attrs[:container_image])
269 candidates = candidates.where('container_image = ?', image)
270 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
272 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
273 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
275 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
276 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
277 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
279 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
280 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
282 candidates = candidates.where('runtime_user_uuid = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
283 attrs[:runtime_user_uuid])
284 log_reuse_info(candidates) { "after filtering on runtime_user_uuid #{attrs[:runtime_user_uuid].inspect}" }
286 candidates = candidates.where('runtime_auth_scopes = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
287 SafeJSON.dump(attrs[:runtime_auth_scopes]))
288 log_reuse_info(candidates) { "after filtering on runtime_auth_scopes #{attrs[:runtime_auth_scopes].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" }
342 if self.state != Queued
343 raise LockFailedError.new("cannot lock when #{self.state}")
344 elsif self.priority <= 0
345 raise LockFailedError.new("cannot lock when priority<=0")
350 # Check invalid state transitions once before getting the lock
351 # (because it's cheaper that way) and once after getting the lock
352 # (because state might have changed while acquiring the lock).
357 update_attributes!(state: Locked)
361 def check_unlock_fail
362 if self.state != Locked
363 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
364 elsif self.locked_by_uuid != current_api_client_authorization.uuid
365 raise InvalidStateTransitionError.new("locked by a different token")
370 # Check invalid state transitions twice (see lock)
373 reload(lock: 'FOR UPDATE')
375 update_attributes!(state: Queued)
379 def self.readable_by(*users_list)
380 # Load optional keyword arguments, if they exist.
381 if users_list.last.is_a? Hash
382 kwargs = users_list.pop
386 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
390 [Complete, Cancelled].include?(self.state)
393 def self.for_current_token
394 _, _, _, container_uuid = Thread.current[:token].split('/')
395 if container_uuid.nil?
396 Container.where(auth_uuid: current_api_client_authorization.uuid)
398 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
399 current_api_client_authorization.uuid,
401 current_api_client_authorization.token)
407 def fill_field_defaults
408 self.state ||= Queued
409 self.environment ||= {}
410 self.runtime_constraints ||= {}
414 self.scheduling_parameters ||= {}
417 def permission_to_create
418 current_user.andand.is_admin
421 def ensure_owner_uuid_is_permitted
422 # validate_change ensures owner_uuid can't be changed at all --
423 # except during create, which requires admin privileges. Checking
424 # permission here would be superfluous.
429 if self.state_changed? and self.state == Running
430 self.started_at ||= db_current_time
433 if self.state_changed? and [Complete, Cancelled].include? self.state
434 self.finished_at ||= db_current_time
438 # Check that well-known runtime status keys have desired data types
439 def validate_runtime_status
441 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
443 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
444 errors.add(:runtime_status, "'#{k}' value must be a string")
451 progress_attrs = [:progress, :runtime_status, :log, :output]
452 final_attrs = [:exit_code, :finished_at]
455 permitted.push(:owner_uuid, :command, :container_image, :cwd,
456 :environment, :mounts, :output_path, :priority,
457 :runtime_constraints, :scheduling_parameters,
458 :secret_mounts, :runtime_token,
459 :runtime_user_uuid, :runtime_auth_scopes)
464 permitted.push :priority, :runtime_status, :log
467 permitted.push :priority
470 permitted.push :priority, *progress_attrs
471 if self.state_changed?
472 permitted.push :started_at
476 if self.state_was == Running
477 permitted.push *final_attrs, *progress_attrs
483 permitted.push :finished_at, *progress_attrs
485 permitted.push :finished_at, :log
489 # The state_transitions check will add an error message for this
493 if current_api_client_authorization.andand.uuid.andand == self.auth_uuid
494 # The contained process itself can update progress indicators,
495 # but can't change priority etc.
496 permitted = permitted & (progress_attrs + final_attrs + [:state] - [:log])
497 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
498 # When locked, progress fields cannot be updated by the wrong
499 # dispatcher, even though it has admin privileges.
500 permitted = permitted - progress_attrs
502 check_update_whitelist permitted
506 if [Locked, Running].include? self.state
507 # If the Container was already locked, locked_by_uuid must not
508 # changes. Otherwise, the current auth gets the lock.
509 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
514 # The caller can provide a new value for locked_by_uuid, but only
515 # if it's exactly what we expect. This allows a caller to perform
516 # an update like {"state":"Unlocked","locked_by_uuid":null}.
517 if self.locked_by_uuid_changed?
518 if self.locked_by_uuid != need_lock
519 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
522 self.locked_by_uuid = need_lock
526 # Output must exist and be readable by the current user. This is so
527 # that a container cannot "claim" a collection that it doesn't otherwise
528 # have access to just by setting the output field to the collection PDH.
531 readable_by(current_user, {include_trash: true}).
532 where(portable_data_hash: self.output).
535 errors.add :output, "collection must exist and be readable by current user."
541 # If self.final?, this update is superfluous: the final log/output
542 # update will be done when handle_completed calls finalize! on
543 # each requesting CR.
544 return if self.final? || !self.log_changed?
545 leave_modified_by_user_alone do
546 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
547 cr.update_collections(container: self, collections: ['log'])
554 if self.auth_uuid_changed?
555 return errors.add :auth_uuid, 'is readonly'
557 if not [Locked, Running].include? self.state
559 self.auth.andand.update_attributes(expires_at: db_current_time)
566 if self.runtime_token.nil?
567 if self.runtime_user_uuid.nil?
568 # legacy behavior, we don't have a runtime_user_uuid so get
569 # the user from the highest priority container request, needed
570 # when performing an upgrade and there are queued containers,
572 cr = ContainerRequest.
573 where('container_uuid=? and priority>0', self.uuid).
574 order('priority desc').
577 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
579 self.runtime_user_uuid = cr.modified_by_user_uuid
580 self.runtime_auth_scopes = ["all"]
583 # generate a new token
584 self.auth = ApiClientAuthorization.
585 create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
587 scopes: self.runtime_auth_scopes)
591 def sort_serialized_attrs
592 if self.environment_changed?
593 self.environment = self.class.deep_sort_hash(self.environment)
595 if self.mounts_changed?
596 self.mounts = self.class.deep_sort_hash(self.mounts)
598 if self.runtime_constraints_changed?
599 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
601 if self.scheduling_parameters_changed?
602 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
606 def update_secret_mounts_md5
607 if self.secret_mounts_changed?
608 self.secret_mounts_md5 = Digest::MD5.hexdigest(
609 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
614 # this runs after update_secret_mounts_md5, so the
615 # secret_mounts_md5 will still reflect the secrets that are being
617 if self.state_changed? && self.final?
618 self.secret_mounts = {}
619 self.runtime_token = nil
623 def clear_runtime_status_when_queued
624 # Avoid leaking status messages between different dispatch attempts
625 if self.state_was == Locked && self.state == Queued
626 self.runtime_status = {}
631 # This container is finished so finalize any associated container requests
632 # that are associated with this container.
633 if self.state_changed? and self.final?
634 act_as_system_user do
636 if self.state == Cancelled
637 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
639 retryable_requests = []
642 if retryable_requests.any?
644 command: self.command,
646 environment: self.environment,
647 output_path: self.output_path,
648 container_image: self.container_image,
650 runtime_constraints: self.runtime_constraints,
651 scheduling_parameters: self.scheduling_parameters
653 c = Container.create! c_attrs
654 retryable_requests.each do |cr|
656 leave_modified_by_user_alone do
657 # Use row locking because this increments container_count
658 cr.container_uuid = c.uuid
665 # Notify container requests associated with this container
666 ContainerRequest.where(container_uuid: uuid,
667 state: ContainerRequest::Committed).each do |cr|
668 leave_modified_by_user_alone do
673 # Cancel outstanding container requests made by this container.
675 includes(:container).
676 where(requesting_container_uuid: uuid,
677 state: ContainerRequest::Committed).each do |cr|
678 leave_modified_by_user_alone do
679 cr.update_attributes!(priority: 0)
681 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
682 # If the child container hasn't started yet, finalize the
683 # child CR now instead of leaving it "on hold", i.e.,
684 # Queued with priority 0. (OTOH, if the child is already
685 # running, leave it alone so it can get cancelled the
686 # usual way, get a copy of the log collection, etc.)
687 cr.update_attributes!(state: ContainerRequest::Final)