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 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
35 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
36 validate :validate_runtime_status
37 validate :validate_state_change
38 validate :validate_change
39 validate :validate_lock
40 validate :validate_output
41 after_validation :assign_auth
42 before_save :sort_serialized_attrs
43 before_save :update_secret_mounts_md5
44 before_save :scrub_secrets
45 before_save :clear_runtime_status_when_queued
46 after_save :update_cr_logs
47 after_save :handle_completed
48 after_save :propagate_priority
49 after_commit { UpdatePriority.run_update_thread }
51 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
52 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
54 api_accessible :user, extend: :common do |t|
56 t.add :container_image
68 t.add :runtime_constraints
73 t.add :scheduling_parameters
74 t.add :runtime_user_uuid
75 t.add :runtime_auth_scopes
78 # Supported states for a container
83 (Running = 'Running'),
84 (Complete = 'Complete'),
85 (Cancelled = 'Cancelled')
90 Queued => [Locked, Cancelled],
91 Locked => [Queued, Running, Cancelled],
92 Running => [Complete, Cancelled]
95 def self.limit_index_columns_read
99 def self.full_text_searchable_columns
100 super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
103 def self.searchable_columns *args
104 super - ["secret_mounts_md5", "runtime_token"]
107 def logged_attributes
108 super.except('secret_mounts', 'runtime_token')
111 def state_transitions
115 # Container priority is the highest "computed priority" of any
116 # matching request. The computed priority of a container-submitted
117 # request is the priority of the submitting container. The computed
118 # priority of a user-submitted request is a function of
119 # user-assigned priority and request creation time.
121 return if ![Queued, Locked, Running].include?(state)
122 p = ContainerRequest.
123 where('container_uuid=? and priority>0', uuid).
124 includes(:requesting_container).
127 if cr.requesting_container
128 cr.requesting_container.priority
130 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
133 update_attributes!(priority: p)
136 def propagate_priority
137 return true unless priority_changed?
138 act_as_system_user do
139 # Update the priority of child container requests to match new
140 # priority of the parent container (ignoring requests with no
141 # container assigned, because their priority doesn't matter).
143 where(requesting_container_uuid: self.uuid,
144 state: ContainerRequest::Committed).
145 where('container_uuid is not null').
146 includes(:container).
148 map(&:update_priority!)
152 # Create a new container (or find an existing one) to satisfy the
153 # given container request.
154 def self.resolve(req)
155 if req.runtime_token.nil?
156 runtime_user = if req.modified_by_user_uuid.nil?
159 User.find_by_uuid(req.modified_by_user_uuid)
161 runtime_auth_scopes = ["all"]
163 auth = ApiClientAuthorization.validate(token: req.runtime_token)
165 raise ArgumentError.new "Invalid runtime token"
167 runtime_user = User.find_by_id(auth.user_id)
168 runtime_auth_scopes = auth.scopes
170 c_attrs = act_as_user runtime_user do
172 command: req.command,
174 environment: req.environment,
175 output_path: req.output_path,
176 container_image: resolve_container_image(req.container_image),
177 mounts: resolve_mounts(req.mounts),
178 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
179 scheduling_parameters: req.scheduling_parameters,
180 secret_mounts: req.secret_mounts,
181 runtime_token: req.runtime_token,
182 runtime_user_uuid: runtime_user.uuid,
183 runtime_auth_scopes: runtime_auth_scopes
186 act_as_system_user do
187 if req.use_existing && (reusable = find_reusable(c_attrs))
190 Container.create!(c_attrs)
195 # Return a runtime_constraints hash that complies with requested but
196 # is suitable for saving in a container record, i.e., has specific
197 # values instead of ranges.
199 # Doing this as a step separate from other resolutions, like "git
200 # revision range to commit hash", makes sense only when there is no
201 # opportunity to reuse an existing container (e.g., container reuse
202 # is not implemented yet, or we have already found that no existing
203 # containers are suitable).
204 def self.resolve_runtime_constraints(runtime_constraints)
208 Rails.configuration.container_default_keep_cache_ram,
210 defaults.merge(runtime_constraints).each do |k, v|
220 # Return a mounts hash suitable for a Container, i.e., with every
221 # readonly collection UUID resolved to a PDH.
222 def self.resolve_mounts(mounts)
224 mounts.each do |k, mount|
227 if mount['kind'] != 'collection'
231 uuid = mount.delete 'uuid'
233 if mount['portable_data_hash'].nil? and !uuid.nil?
234 # PDH not supplied, try by UUID
236 readable_by(current_user).
238 select(:portable_data_hash).
241 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
243 mount['portable_data_hash'] = c.portable_data_hash
249 # Return a container_image PDH suitable for a Container.
250 def self.resolve_container_image(container_image)
251 coll = Collection.for_latest_docker_image(container_image)
253 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
255 coll.portable_data_hash
258 def self.find_reusable(attrs)
259 log_reuse_info { "starting with #{Container.all.count} container records in database" }
260 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
261 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
263 candidates = candidates.where('cwd = ?', attrs[:cwd])
264 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
266 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
267 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
269 candidates = candidates.where('output_path = ?', attrs[:output_path])
270 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
272 image = resolve_container_image(attrs[:container_image])
273 candidates = candidates.where('container_image = ?', image)
274 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
276 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
277 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
279 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
280 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
281 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
283 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
284 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
286 log_reuse_info { "checking for state=Complete with readable output and log..." }
288 select_readable_pdh = Collection.
289 readable_by(current_user).
290 select(:portable_data_hash).
293 usable = candidates.where(state: Complete, exit_code: 0)
294 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
296 usable = usable.where("log IN (#{select_readable_pdh})")
297 log_reuse_info(usable) { "with readable log" }
299 usable = usable.where("output IN (#{select_readable_pdh})")
300 log_reuse_info(usable) { "with readable output" }
302 usable = usable.order('finished_at ASC').limit(1).first
304 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
308 # Check for non-failing Running candidates and return the most likely to finish sooner.
309 log_reuse_info { "checking for state=Running..." }
310 running = candidates.where(state: Running).
311 where("(runtime_status->'error') is null").
312 order('progress desc, started_at asc').
315 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
318 log_reuse_info { "have no containers in Running state" }
321 # Check for Locked or Queued ones and return the most likely to start first.
322 locked_or_queued = candidates.
323 where("state IN (?)", [Locked, Queued]).
324 order('state asc, priority desc, created_at asc').
327 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
328 return locked_or_queued
330 log_reuse_info { "have no containers in Locked or Queued state" }
333 log_reuse_info { "done, no reusable container found" }
338 if self.state != Queued
339 raise LockFailedError.new("cannot lock when #{self.state}")
340 elsif self.priority <= 0
341 raise LockFailedError.new("cannot lock when priority<=0")
346 # Check invalid state transitions once before getting the lock
347 # (because it's cheaper that way) and once after getting the lock
348 # (because state might have changed while acquiring the lock).
353 update_attributes!(state: Locked, lock_count: self.lock_count+1)
357 def check_unlock_fail
358 if self.state != Locked
359 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
360 elsif self.locked_by_uuid != current_api_client_authorization.uuid
361 raise InvalidStateTransitionError.new("locked by a different token")
366 # Check invalid state transitions twice (see lock)
369 reload(lock: 'FOR UPDATE')
371 if self.lock_count < Rails.configuration.max_container_dispatch_attempts
372 update_attributes!(state: Queued)
374 update_attributes!(state: Cancelled,
376 error: "Container exceeded 'max_container_dispatch_attempts' (lock_count=#{self.lock_count}."
382 def self.readable_by(*users_list)
383 # Load optional keyword arguments, if they exist.
384 if users_list.last.is_a? Hash
385 kwargs = users_list.pop
389 if users_list.select { |u| u.is_admin }.any?
392 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
396 [Complete, Cancelled].include?(self.state)
399 def self.for_current_token
400 return if !current_api_client_authorization
401 _, _, _, container_uuid = Thread.current[:token].split('/')
402 if container_uuid.nil?
403 Container.where(auth_uuid: current_api_client_authorization.uuid).first
405 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
406 current_api_client_authorization.uuid,
408 current_api_client_authorization.token).first
414 def fill_field_defaults
415 self.state ||= Queued
416 self.environment ||= {}
417 self.runtime_constraints ||= {}
421 self.scheduling_parameters ||= {}
424 def permission_to_create
425 current_user.andand.is_admin
428 def ensure_owner_uuid_is_permitted
429 # validate_change ensures owner_uuid can't be changed at all --
430 # except during create, which requires admin privileges. Checking
431 # permission here would be superfluous.
436 if self.state_changed? and self.state == Running
437 self.started_at ||= db_current_time
440 if self.state_changed? and [Complete, Cancelled].include? self.state
441 self.finished_at ||= db_current_time
445 # Check that well-known runtime status keys have desired data types
446 def validate_runtime_status
448 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
450 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
451 errors.add(:runtime_status, "'#{k}' value must be a string")
458 progress_attrs = [:progress, :runtime_status, :log, :output]
459 final_attrs = [:exit_code, :finished_at]
462 permitted.push(:owner_uuid, :command, :container_image, :cwd,
463 :environment, :mounts, :output_path, :priority,
464 :runtime_constraints, :scheduling_parameters,
465 :secret_mounts, :runtime_token,
466 :runtime_user_uuid, :runtime_auth_scopes)
471 permitted.push :priority, :runtime_status, :log, :lock_count
474 permitted.push :priority
477 permitted.push :priority, *progress_attrs
478 if self.state_changed?
479 permitted.push :started_at
483 if self.state_was == Running
484 permitted.push *final_attrs, *progress_attrs
490 permitted.push :finished_at, *progress_attrs
492 permitted.push :finished_at, :log, :runtime_status
496 # The state_transitions check will add an error message for this
500 if self.state == Running &&
501 !current_api_client_authorization.nil? &&
502 (current_api_client_authorization.uuid == self.auth_uuid ||
503 current_api_client_authorization.token == self.runtime_token)
504 # The contained process itself can write final attrs but can't
505 # change priority or log.
506 permitted.push *final_attrs
507 permitted = permitted - [:log, :priority]
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 act_as_system_user do
650 if self.state == Cancelled
651 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
653 retryable_requests = []
656 if retryable_requests.any?
658 command: self.command,
660 environment: self.environment,
661 output_path: self.output_path,
662 container_image: self.container_image,
664 runtime_constraints: self.runtime_constraints,
665 scheduling_parameters: self.scheduling_parameters,
666 secret_mounts: self.secret_mounts_was,
667 runtime_token: self.runtime_token_was,
668 runtime_user_uuid: self.runtime_user_uuid,
669 runtime_auth_scopes: self.runtime_auth_scopes
671 c = Container.create! c_attrs
672 retryable_requests.each do |cr|
674 leave_modified_by_user_alone do
675 # Use row locking because this increments container_count
676 cr.container_uuid = c.uuid
683 # Notify container requests associated with this container
684 ContainerRequest.where(container_uuid: uuid,
685 state: ContainerRequest::Committed).each do |cr|
686 leave_modified_by_user_alone do
691 # Cancel outstanding container requests made by this container.
693 includes(:container).
694 where(requesting_container_uuid: uuid,
695 state: ContainerRequest::Committed).each do |cr|
696 leave_modified_by_user_alone do
697 cr.update_attributes!(priority: 0)
699 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
700 # If the child container hasn't started yet, finalize the
701 # child CR now instead of leaving it "on hold", i.e.,
702 # Queued with priority 0. (OTOH, if the child is already
703 # running, leave it alone so it can get cancelled the
704 # usual way, get a copy of the log collection, etc.)
705 cr.update_attributes!(state: ContainerRequest::Final)