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
70 t.add :runtime_user_uuid
71 t.add :runtime_auth_scopes
74 # Supported states for a container
79 (Running = 'Running'),
80 (Complete = 'Complete'),
81 (Cancelled = 'Cancelled')
86 Queued => [Locked, Cancelled],
87 Locked => [Queued, Running, Cancelled],
88 Running => [Complete, Cancelled]
91 def self.limit_index_columns_read
95 def self.full_text_searchable_columns
96 super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
99 def self.searchable_columns *args
100 super - ["secret_mounts_md5", "runtime_token"]
103 def logged_attributes
104 super.except('secret_mounts', 'runtime_token')
107 def state_transitions
111 # Container priority is the highest "computed priority" of any
112 # matching request. The computed priority of a container-submitted
113 # request is the priority of the submitting container. The computed
114 # priority of a user-submitted request is a function of
115 # user-assigned priority and request creation time.
117 return if ![Queued, Locked, Running].include?(state)
118 p = ContainerRequest.
119 where('container_uuid=? and priority>0', uuid).
120 includes(:requesting_container).
123 if cr.requesting_container
124 cr.requesting_container.priority
126 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
129 update_attributes!(priority: p)
132 def propagate_priority
133 return true unless priority_changed?
134 act_as_system_user do
135 # Update the priority of child container requests to match new
136 # priority of the parent container (ignoring requests with no
137 # container assigned, because their priority doesn't matter).
139 where(requesting_container_uuid: self.uuid,
140 state: ContainerRequest::Committed).
141 where('container_uuid is not null').
142 includes(:container).
144 map(&:update_priority!)
148 # Create a new container (or find an existing one) to satisfy the
149 # given container request.
150 def self.resolve(req)
151 if req.runtime_token.nil?
152 runtime_user = if req.modified_by_user_uuid.nil?
155 User.find_by_uuid(req.modified_by_user_uuid)
157 runtime_auth_scopes = ["all"]
159 auth = ApiClientAuthorization.validate(token: req.runtime_token)
161 raise ArgumentError.new "Invalid runtime token"
163 runtime_user = User.find_by_id(auth.user_id)
164 runtime_auth_scopes = auth.scopes
166 c_attrs = act_as_user runtime_user do
168 command: req.command,
170 environment: req.environment,
171 output_path: req.output_path,
172 container_image: resolve_container_image(req.container_image),
173 mounts: resolve_mounts(req.mounts),
174 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
175 scheduling_parameters: req.scheduling_parameters,
176 secret_mounts: req.secret_mounts,
177 runtime_token: req.runtime_token,
178 runtime_user_uuid: runtime_user.uuid,
179 runtime_auth_scopes: runtime_auth_scopes
182 act_as_system_user do
183 if req.use_existing && (reusable = find_reusable(c_attrs))
186 Container.create!(c_attrs)
191 # Return a runtime_constraints hash that complies with requested but
192 # is suitable for saving in a container record, i.e., has specific
193 # values instead of ranges.
195 # Doing this as a step separate from other resolutions, like "git
196 # revision range to commit hash", makes sense only when there is no
197 # opportunity to reuse an existing container (e.g., container reuse
198 # is not implemented yet, or we have already found that no existing
199 # containers are suitable).
200 def self.resolve_runtime_constraints(runtime_constraints)
204 Rails.configuration.container_default_keep_cache_ram,
206 defaults.merge(runtime_constraints).each do |k, v|
216 # Return a mounts hash suitable for a Container, i.e., with every
217 # readonly collection UUID resolved to a PDH.
218 def self.resolve_mounts(mounts)
220 mounts.each do |k, mount|
223 if mount['kind'] != 'collection'
227 pdh = mount['portable_data_hash']
230 # Prioritize PDH over UUID for mount selection
233 readable_by(current_user).
234 where(portable_data_hash: pdh)
236 if uuid && c.where(uuid: uuid).count == 0
237 raise ArgumentError.new "cannot mount collection #{uuid.inspect}: current portable_data_hash #{pdh.inspect} does not match #{c.first.portable_data_hash.inspect} in request"
239 # mount.delete 'uuid'
242 raise ArgumentError.new "cannot mount collection #{pdh.inspect}: not found"
245 # PDH not supplied, try by UUID
248 readable_by(current_user).
250 select(:portable_data_hash).
253 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
255 mount['portable_data_hash'] = c.portable_data_hash
261 # Return a container_image PDH suitable for a Container.
262 def self.resolve_container_image(container_image)
263 coll = Collection.for_latest_docker_image(container_image)
265 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
267 coll.portable_data_hash
270 def self.find_reusable(attrs)
271 log_reuse_info { "starting with #{Container.all.count} container records in database" }
272 candidates = Container.where_serialized(:command, attrs[:command], md5: true)
273 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
275 candidates = candidates.where('cwd = ?', attrs[:cwd])
276 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
278 candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
279 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
281 candidates = candidates.where('output_path = ?', attrs[:output_path])
282 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
284 image = resolve_container_image(attrs[:container_image])
285 candidates = candidates.where('container_image = ?', image)
286 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
288 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
289 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
291 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
292 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
293 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
295 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
296 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
298 candidates = candidates.where('runtime_user_uuid = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
299 attrs[:runtime_user_uuid])
300 log_reuse_info(candidates) { "after filtering on runtime_user_uuid #{attrs[:runtime_user_uuid].inspect}" }
302 candidates = candidates.where('runtime_auth_scopes = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
303 SafeJSON.dump(attrs[:runtime_auth_scopes].sort))
304 log_reuse_info(candidates) { "after filtering on runtime_auth_scopes #{attrs[:runtime_auth_scopes].inspect}" }
306 log_reuse_info { "checking for state=Complete with readable output and log..." }
308 select_readable_pdh = Collection.
309 readable_by(current_user).
310 select(:portable_data_hash).
313 usable = candidates.where(state: Complete, exit_code: 0)
314 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
316 usable = usable.where("log IN (#{select_readable_pdh})")
317 log_reuse_info(usable) { "with readable log" }
319 usable = usable.where("output IN (#{select_readable_pdh})")
320 log_reuse_info(usable) { "with readable output" }
322 usable = usable.order('finished_at ASC').limit(1).first
324 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
328 # Check for non-failing Running candidates and return the most likely to finish sooner.
329 log_reuse_info { "checking for state=Running..." }
330 running = candidates.where(state: Running).
331 where("(runtime_status->'error') is null").
332 order('progress desc, started_at asc').
335 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
338 log_reuse_info { "have no containers in Running state" }
341 # Check for Locked or Queued ones and return the most likely to start first.
342 locked_or_queued = candidates.
343 where("state IN (?)", [Locked, Queued]).
344 order('state asc, priority desc, created_at asc').
347 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
348 return locked_or_queued
350 log_reuse_info { "have no containers in Locked or Queued state" }
353 log_reuse_info { "done, no reusable container found" }
358 if self.state != Queued
359 raise LockFailedError.new("cannot lock when #{self.state}")
360 elsif self.priority <= 0
361 raise LockFailedError.new("cannot lock when priority<=0")
366 # Check invalid state transitions once before getting the lock
367 # (because it's cheaper that way) and once after getting the lock
368 # (because state might have changed while acquiring the lock).
373 update_attributes!(state: Locked)
377 def check_unlock_fail
378 if self.state != Locked
379 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
380 elsif self.locked_by_uuid != current_api_client_authorization.uuid
381 raise InvalidStateTransitionError.new("locked by a different token")
386 # Check invalid state transitions twice (see lock)
389 reload(lock: 'FOR UPDATE')
391 update_attributes!(state: Queued)
395 def self.readable_by(*users_list)
396 # Load optional keyword arguments, if they exist.
397 if users_list.last.is_a? Hash
398 kwargs = users_list.pop
402 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
406 [Complete, Cancelled].include?(self.state)
409 def self.for_current_token
410 return if !current_api_client_authorization
411 _, _, _, container_uuid = Thread.current[:token].split('/')
412 if container_uuid.nil?
413 Container.where(auth_uuid: current_api_client_authorization.uuid).first
415 Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
416 current_api_client_authorization.uuid,
418 current_api_client_authorization.token).first
424 def fill_field_defaults
425 self.state ||= Queued
426 self.environment ||= {}
427 self.runtime_constraints ||= {}
431 self.scheduling_parameters ||= {}
434 def permission_to_create
435 current_user.andand.is_admin
438 def ensure_owner_uuid_is_permitted
439 # validate_change ensures owner_uuid can't be changed at all --
440 # except during create, which requires admin privileges. Checking
441 # permission here would be superfluous.
446 if self.state_changed? and self.state == Running
447 self.started_at ||= db_current_time
450 if self.state_changed? and [Complete, Cancelled].include? self.state
451 self.finished_at ||= db_current_time
455 # Check that well-known runtime status keys have desired data types
456 def validate_runtime_status
458 'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
460 if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
461 errors.add(:runtime_status, "'#{k}' value must be a string")
468 progress_attrs = [:progress, :runtime_status, :log, :output]
469 final_attrs = [:exit_code, :finished_at]
472 permitted.push(:owner_uuid, :command, :container_image, :cwd,
473 :environment, :mounts, :output_path, :priority,
474 :runtime_constraints, :scheduling_parameters,
475 :secret_mounts, :runtime_token,
476 :runtime_user_uuid, :runtime_auth_scopes)
481 permitted.push :priority, :runtime_status, :log
484 permitted.push :priority
487 permitted.push :priority, *progress_attrs
488 if self.state_changed?
489 permitted.push :started_at
493 if self.state_was == Running
494 permitted.push *final_attrs, *progress_attrs
500 permitted.push :finished_at, *progress_attrs
502 permitted.push :finished_at, :log
506 # The state_transitions check will add an error message for this
510 if self.state == Running &&
511 !current_api_client_authorization.nil? &&
512 (current_api_client_authorization.uuid == self.auth_uuid ||
513 current_api_client_authorization.token == self.runtime_token)
514 # The contained process itself can write final attrs but can't
515 # change priority or log.
516 permitted.push *final_attrs
517 permitted = permitted - [:log, :priority]
518 elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
519 # When locked, progress fields cannot be updated by the wrong
520 # dispatcher, even though it has admin privileges.
521 permitted = permitted - progress_attrs
523 check_update_whitelist permitted
527 if [Locked, Running].include? self.state
528 # If the Container was already locked, locked_by_uuid must not
529 # changes. Otherwise, the current auth gets the lock.
530 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
535 # The caller can provide a new value for locked_by_uuid, but only
536 # if it's exactly what we expect. This allows a caller to perform
537 # an update like {"state":"Unlocked","locked_by_uuid":null}.
538 if self.locked_by_uuid_changed?
539 if self.locked_by_uuid != need_lock
540 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
543 self.locked_by_uuid = need_lock
547 # Output must exist and be readable by the current user. This is so
548 # that a container cannot "claim" a collection that it doesn't otherwise
549 # have access to just by setting the output field to the collection PDH.
552 readable_by(current_user, {include_trash: true}).
553 where(portable_data_hash: self.output).
556 errors.add :output, "collection must exist and be readable by current user."
562 # If self.final?, this update is superfluous: the final log/output
563 # update will be done when handle_completed calls finalize! on
564 # each requesting CR.
565 return if self.final? || !self.log_changed?
566 leave_modified_by_user_alone do
567 ContainerRequest.where(container_uuid: self.uuid).each do |cr|
568 cr.update_collections(container: self, collections: ['log'])
575 if self.auth_uuid_changed?
576 return errors.add :auth_uuid, 'is readonly'
578 if not [Locked, Running].include? self.state
580 self.auth.andand.update_attributes(expires_at: db_current_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 self.state_changed? and self.final?
658 act_as_system_user do
660 if self.state == Cancelled
661 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
663 retryable_requests = []
666 if retryable_requests.any?
668 command: self.command,
670 environment: self.environment,
671 output_path: self.output_path,
672 container_image: self.container_image,
674 runtime_constraints: self.runtime_constraints,
675 scheduling_parameters: self.scheduling_parameters,
676 secret_mounts: self.secret_mounts_was,
677 runtime_token: self.runtime_token_was,
678 runtime_user_uuid: self.runtime_user_uuid,
679 runtime_auth_scopes: self.runtime_auth_scopes
681 c = Container.create! c_attrs
682 retryable_requests.each do |cr|
684 leave_modified_by_user_alone do
685 # Use row locking because this increments container_count
686 cr.container_uuid = c.uuid
693 # Notify container requests associated with this container
694 ContainerRequest.where(container_uuid: uuid,
695 state: ContainerRequest::Committed).each do |cr|
696 leave_modified_by_user_alone do
701 # Cancel outstanding container requests made by this container.
703 includes(:container).
704 where(requesting_container_uuid: uuid,
705 state: ContainerRequest::Committed).each do |cr|
706 leave_modified_by_user_alone do
707 cr.update_attributes!(priority: 0)
709 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
710 # If the child container hasn't started yet, finalize the
711 # child CR now instead of leaving it "on hold", i.e.,
712 # Queued with priority 0. (OTOH, if the child is already
713 # running, leave it alone so it can get cancelled the
714 # usual way, get a copy of the log collection, etc.)
715 cr.update_attributes!(state: ContainerRequest::Final)