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_state_change
33 validate :validate_change
34 validate :validate_lock
35 validate :validate_output
36 after_validation :assign_auth
37 before_save :sort_serialized_attrs
38 before_save :update_secret_mounts_md5
39 before_save :scrub_secret_mounts
40 before_save :clear_runtime_status_when_queued
41 after_save :handle_completed
42 after_save :propagate_priority
43 after_commit { UpdatePriority.run_update_thread }
45 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
46 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
48 api_accessible :user, extend: :common do |t|
50 t.add :container_image
62 t.add :runtime_constraints
66 t.add :scheduling_parameters
69 # Supported states for a container
74 (Running = 'Running'),
75 (Complete = 'Complete'),
76 (Cancelled = 'Cancelled')
81 Queued => [Locked, Cancelled],
82 Locked => [Queued, Running, Cancelled],
83 Running => [Complete, Cancelled]
86 def self.limit_index_columns_read
90 def self.full_text_searchable_columns
91 super - ["secret_mounts", "secret_mounts_md5"]
94 def self.searchable_columns *args
95 super - ["secret_mounts_md5"]
99 super.except('secret_mounts')
102 def state_transitions
106 # Container priority is the highest "computed priority" of any
107 # matching request. The computed priority of a container-submitted
108 # request is the priority of the submitting container. The computed
109 # priority of a user-submitted request is a function of
110 # user-assigned priority and request creation time.
112 return if ![Queued, Locked, Running].include?(state)
113 p = ContainerRequest.
114 where('container_uuid=? and priority>0', uuid).
115 includes(:requesting_container).
118 if cr.requesting_container
119 cr.requesting_container.priority
121 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
124 update_attributes!(priority: p)
127 def propagate_priority
128 return true unless priority_changed?
129 act_as_system_user do
130 # Update the priority of child container requests to match new
131 # priority of the parent container (ignoring requests with no
132 # container assigned, because their priority doesn't matter).
134 where(requesting_container_uuid: self.uuid,
135 state: ContainerRequest::Committed).
136 where('container_uuid is not null').
137 includes(:container).
139 map(&:update_priority!)
143 # Create a new container (or find an existing one) to satisfy the
144 # given container request.
145 def self.resolve(req)
147 command: req.command,
149 environment: req.environment,
150 output_path: req.output_path,
151 container_image: resolve_container_image(req.container_image),
152 mounts: resolve_mounts(req.mounts),
153 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
154 scheduling_parameters: req.scheduling_parameters,
155 secret_mounts: req.secret_mounts,
157 act_as_system_user do
158 if req.use_existing && (reusable = find_reusable(c_attrs))
161 Container.create!(c_attrs)
166 # Return a runtime_constraints hash that complies with requested but
167 # is suitable for saving in a container record, i.e., has specific
168 # values instead of ranges.
170 # Doing this as a step separate from other resolutions, like "git
171 # revision range to commit hash", makes sense only when there is no
172 # opportunity to reuse an existing container (e.g., container reuse
173 # is not implemented yet, or we have already found that no existing
174 # containers are suitable).
175 def self.resolve_runtime_constraints(runtime_constraints)
179 Rails.configuration.container_default_keep_cache_ram,
181 defaults.merge(runtime_constraints).each do |k, v|
191 # Return a mounts hash suitable for a Container, i.e., with every
192 # readonly collection UUID resolved to a PDH.
193 def self.resolve_mounts(mounts)
195 mounts.each do |k, mount|
198 if mount['kind'] != 'collection'
201 if (uuid = mount.delete 'uuid')
203 readable_by(current_user).
205 select(:portable_data_hash).
208 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
210 if mount['portable_data_hash'].nil?
211 # PDH not supplied by client
212 mount['portable_data_hash'] = c.portable_data_hash
213 elsif mount['portable_data_hash'] != c.portable_data_hash
214 # UUID and PDH supplied by client, but they don't agree
215 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"
222 # Return a container_image PDH suitable for a Container.
223 def self.resolve_container_image(container_image)
224 coll = Collection.for_latest_docker_image(container_image)
226 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
228 coll.portable_data_hash
231 def self.find_reusable(attrs)
232 log_reuse_info { "starting with #{Container.all.count} container records in database" }
233 candidates = Container.where_serialized(:command, attrs[:command])
234 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
236 candidates = candidates.where('cwd = ?', attrs[:cwd])
237 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
239 candidates = candidates.where_serialized(:environment, attrs[:environment])
240 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
242 candidates = candidates.where('output_path = ?', attrs[:output_path])
243 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
245 image = resolve_container_image(attrs[:container_image])
246 candidates = candidates.where('container_image = ?', image)
247 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
249 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
250 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
252 candidates = candidates.where('secret_mounts_md5 = ?', Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts]))))
253 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
255 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
256 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
258 log_reuse_info { "checking for state=Complete with readable output and log..." }
260 select_readable_pdh = Collection.
261 readable_by(current_user).
262 select(:portable_data_hash).
265 usable = candidates.where(state: Complete, exit_code: 0)
266 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
268 usable = usable.where("log IN (#{select_readable_pdh})")
269 log_reuse_info(usable) { "with readable log" }
271 usable = usable.where("output IN (#{select_readable_pdh})")
272 log_reuse_info(usable) { "with readable output" }
274 usable = usable.order('finished_at ASC').limit(1).first
276 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
280 # Check for non-failing Running candidates and return the most likely to finish sooner.
281 log_reuse_info { "checking for state=Running..." }
282 running = candidates.where(state: Running).
283 where("NOT (runtime_status ? 'error')").
284 order('progress desc, started_at asc').
287 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
290 log_reuse_info { "have no containers in Running state" }
293 # Check for Locked or Queued ones and return the most likely to start first.
294 locked_or_queued = candidates.
295 where("state IN (?)", [Locked, Queued]).
296 order('state asc, priority desc, created_at asc').
299 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
300 return locked_or_queued
302 log_reuse_info { "have no containers in Locked or Queued state" }
305 log_reuse_info { "done, no reusable container found" }
310 if self.state != Queued
311 raise LockFailedError.new("cannot lock when #{self.state}")
312 elsif self.priority <= 0
313 raise LockFailedError.new("cannot lock when priority<=0")
318 # Check invalid state transitions once before getting the lock
319 # (because it's cheaper that way) and once after getting the lock
320 # (because state might have changed while acquiring the lock).
325 update_attributes!(state: Locked)
329 def check_unlock_fail
330 if self.state != Locked
331 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
332 elsif self.locked_by_uuid != current_api_client_authorization.uuid
333 raise InvalidStateTransitionError.new("locked by a different token")
338 # Check invalid state transitions twice (see lock)
341 reload(lock: 'FOR UPDATE')
343 update_attributes!(state: Queued)
347 def self.readable_by(*users_list)
348 # Load optional keyword arguments, if they exist.
349 if users_list.last.is_a? Hash
350 kwargs = users_list.pop
354 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
358 [Complete, Cancelled].include?(self.state)
363 def fill_field_defaults
364 self.state ||= Queued
365 self.environment ||= {}
366 self.runtime_constraints ||= {}
370 self.scheduling_parameters ||= {}
373 def permission_to_create
374 current_user.andand.is_admin
377 def permission_to_update
378 # Override base permission check to allow auth_uuid to set progress and
379 # output (only). Whether it is legal to set progress and output in the current
380 # state has already been checked in validate_change.
381 current_user.andand.is_admin ||
382 (!current_api_client_authorization.nil? and
383 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
386 def ensure_owner_uuid_is_permitted
387 # Override base permission check to allow auth_uuid to set progress and
388 # output (only). Whether it is legal to set progress and output in the current
389 # state has already been checked in validate_change.
390 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
391 check_update_whitelist [:progress, :output]
398 if self.state_changed? and self.state == Running
399 self.started_at ||= db_current_time
402 if self.state_changed? and [Complete, Cancelled].include? self.state
403 self.finished_at ||= db_current_time
411 permitted.push(:owner_uuid, :command, :container_image, :cwd,
412 :environment, :mounts, :output_path, :priority,
413 :runtime_constraints, :scheduling_parameters,
419 permitted.push :priority, :runtime_status
422 permitted.push :priority
425 permitted.push :priority, :progress, :output, :runtime_status
426 if self.state_changed?
427 permitted.push :started_at
431 if self.state_was == Running
432 permitted.push :finished_at, :output, :log, :exit_code
438 permitted.push :finished_at, :output, :log
440 permitted.push :finished_at, :log
444 # The state_transitions check will add an error message for this
448 check_update_whitelist permitted
452 if [Locked, Running].include? self.state
453 # If the Container was already locked, locked_by_uuid must not
454 # changes. Otherwise, the current auth gets the lock.
455 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
460 # The caller can provide a new value for locked_by_uuid, but only
461 # if it's exactly what we expect. This allows a caller to perform
462 # an update like {"state":"Unlocked","locked_by_uuid":null}.
463 if self.locked_by_uuid_changed?
464 if self.locked_by_uuid != need_lock
465 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
468 self.locked_by_uuid = need_lock
472 # Output must exist and be readable by the current user. This is so
473 # that a container cannot "claim" a collection that it doesn't otherwise
474 # have access to just by setting the output field to the collection PDH.
477 readable_by(current_user, {include_trash: true}).
478 where(portable_data_hash: self.output).
481 errors.add :output, "collection must exist and be readable by current user."
487 if self.auth_uuid_changed?
488 return errors.add :auth_uuid, 'is readonly'
490 if not [Locked, Running].include? self.state
492 self.auth.andand.update_attributes(expires_at: db_current_time)
499 cr = ContainerRequest.
500 where('container_uuid=? and priority>0', self.uuid).
501 order('priority desc').
504 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
506 self.auth = ApiClientAuthorization.
507 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
511 def sort_serialized_attrs
512 if self.environment_changed?
513 self.environment = self.class.deep_sort_hash(self.environment)
515 if self.mounts_changed?
516 self.mounts = self.class.deep_sort_hash(self.mounts)
518 if self.runtime_constraints_changed?
519 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
521 if self.scheduling_parameters_changed?
522 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
526 def update_secret_mounts_md5
527 if self.secret_mounts_changed?
528 self.secret_mounts_md5 = Digest::MD5.hexdigest(
529 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
533 def scrub_secret_mounts
534 # this runs after update_secret_mounts_md5, so the
535 # secret_mounts_md5 will still reflect the secrets that are being
537 if self.state_changed? && self.final?
538 self.secret_mounts = {}
542 def clear_runtime_status_when_queued
543 # Avoid leaking status messages between different dispatch attempts
544 if self.state_was == Locked && self.state == Queued
545 self.runtime_status = {}
550 # This container is finished so finalize any associated container requests
551 # that are associated with this container.
552 if self.state_changed? and self.final?
553 act_as_system_user do
555 if self.state == Cancelled
556 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
558 retryable_requests = []
561 if retryable_requests.any?
563 command: self.command,
565 environment: self.environment,
566 output_path: self.output_path,
567 container_image: self.container_image,
569 runtime_constraints: self.runtime_constraints,
570 scheduling_parameters: self.scheduling_parameters
572 c = Container.create! c_attrs
573 retryable_requests.each do |cr|
575 leave_modified_by_user_alone do
576 # Use row locking because this increments container_count
577 cr.container_uuid = c.uuid
584 # Notify container requests associated with this container
585 ContainerRequest.where(container_uuid: uuid,
586 state: ContainerRequest::Committed).each do |cr|
587 leave_modified_by_user_alone do
592 # Cancel outstanding container requests made by this container.
594 includes(:container).
595 where(requesting_container_uuid: uuid,
596 state: ContainerRequest::Committed).each do |cr|
597 leave_modified_by_user_alone do
598 cr.update_attributes!(priority: 0)
600 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
601 # If the child container hasn't started yet, finalize the
602 # child CR now instead of leaving it "on hold", i.e.,
603 # Queued with priority 0. (OTOH, if the child is already
604 # running, leave it alone so it can get cancelled the
605 # usual way, get a copy of the log collection, etc.)
606 cr.update_attributes!(state: ContainerRequest::Final)