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
27 before_validation :fill_field_defaults, :if => :new_record?
28 before_validation :set_timestamps
29 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
30 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
31 validate :validate_state_change
32 validate :validate_change
33 validate :validate_lock
34 validate :validate_output
35 after_validation :assign_auth
36 before_save :sort_serialized_attrs
37 before_save :update_secret_mounts_md5
38 before_save :scrub_secret_mounts
39 after_save :handle_completed
40 after_save :propagate_priority
41 after_commit { UpdatePriority.run_update_thread }
43 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
44 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
46 api_accessible :user, extend: :common do |t|
48 t.add :container_image
60 t.add :runtime_constraints
64 t.add :scheduling_parameters
67 # Supported states for a container
72 (Running = 'Running'),
73 (Complete = 'Complete'),
74 (Cancelled = 'Cancelled')
79 Queued => [Locked, Cancelled],
80 Locked => [Queued, Running, Cancelled],
81 Running => [Complete, Cancelled]
84 def self.limit_index_columns_read
88 def self.full_text_searchable_columns
89 super - ["secret_mounts", "secret_mounts_md5"]
92 def self.searchable_columns *args
93 super - ["secret_mounts_md5"]
97 super.except('secret_mounts')
100 def state_transitions
104 # Container priority is the highest "computed priority" of any
105 # matching request. The computed priority of a container-submitted
106 # request is the priority of the submitting container. The computed
107 # priority of a user-submitted request is a function of
108 # user-assigned priority and request creation time.
110 return if ![Queued, Locked, Running].include?(state)
111 p = ContainerRequest.
112 where('container_uuid=? and priority>0', uuid).
113 includes(:requesting_container).
116 if cr.requesting_container
117 cr.requesting_container.priority
119 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
122 update_attributes!(priority: p)
125 def propagate_priority
126 return true unless priority_changed?
127 act_as_system_user do
128 # Update the priority of child container requests to match new
129 # priority of the parent container (ignoring requests with no
130 # container assigned, because their priority doesn't matter).
132 where(requesting_container_uuid: self.uuid,
133 state: ContainerRequest::Committed).
134 where('container_uuid is not null').
135 includes(:container).
137 map(&:update_priority!)
141 # Create a new container (or find an existing one) to satisfy the
142 # given container request.
143 def self.resolve(req)
145 command: req.command,
147 environment: req.environment,
148 output_path: req.output_path,
149 container_image: resolve_container_image(req.container_image),
150 mounts: resolve_mounts(req.mounts),
151 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
152 scheduling_parameters: req.scheduling_parameters,
153 secret_mounts: req.secret_mounts,
155 act_as_system_user do
156 if req.use_existing && (reusable = find_reusable(c_attrs))
159 Container.create!(c_attrs)
164 # Return a runtime_constraints hash that complies with requested but
165 # is suitable for saving in a container record, i.e., has specific
166 # values instead of ranges.
168 # Doing this as a step separate from other resolutions, like "git
169 # revision range to commit hash", makes sense only when there is no
170 # opportunity to reuse an existing container (e.g., container reuse
171 # is not implemented yet, or we have already found that no existing
172 # containers are suitable).
173 def self.resolve_runtime_constraints(runtime_constraints)
177 Rails.configuration.container_default_keep_cache_ram,
179 defaults.merge(runtime_constraints).each do |k, v|
189 # Return a mounts hash suitable for a Container, i.e., with every
190 # readonly collection UUID resolved to a PDH.
191 def self.resolve_mounts(mounts)
193 mounts.each do |k, mount|
196 if mount['kind'] != 'collection'
199 if (uuid = mount.delete 'uuid')
201 readable_by(current_user).
203 select(:portable_data_hash).
206 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
208 if mount['portable_data_hash'].nil?
209 # PDH not supplied by client
210 mount['portable_data_hash'] = c.portable_data_hash
211 elsif mount['portable_data_hash'] != c.portable_data_hash
212 # UUID and PDH supplied by client, but they don't agree
213 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"
220 # Return a container_image PDH suitable for a Container.
221 def self.resolve_container_image(container_image)
222 coll = Collection.for_latest_docker_image(container_image)
224 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
226 coll.portable_data_hash
229 def self.find_reusable(attrs)
230 log_reuse_info { "starting with #{Container.all.count} container records in database" }
231 candidates = Container.where_serialized(:command, attrs[:command])
232 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
234 candidates = candidates.where('cwd = ?', attrs[:cwd])
235 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
237 candidates = candidates.where_serialized(:environment, attrs[:environment])
238 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
240 candidates = candidates.where('output_path = ?', attrs[:output_path])
241 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
243 image = resolve_container_image(attrs[:container_image])
244 candidates = candidates.where('container_image = ?', image)
245 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
247 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
248 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
250 candidates = candidates.where('secret_mounts_md5 = ?', Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts]))))
251 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
253 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
254 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
256 log_reuse_info { "checking for state=Complete with readable output and log..." }
258 select_readable_pdh = Collection.
259 readable_by(current_user).
260 select(:portable_data_hash).
263 usable = candidates.where(state: Complete, exit_code: 0)
264 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
266 usable = usable.where("log IN (#{select_readable_pdh})")
267 log_reuse_info(usable) { "with readable log" }
269 usable = usable.where("output IN (#{select_readable_pdh})")
270 log_reuse_info(usable) { "with readable output" }
272 usable = usable.order('finished_at ASC').limit(1).first
274 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
278 # Check for Running candidates and return the most likely to finish sooner.
279 log_reuse_info { "checking for state=Running..." }
280 running = candidates.where(state: Running).
281 order('progress desc, started_at asc').
284 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
287 log_reuse_info { "have no containers in Running state" }
290 # Check for Locked or Queued ones and return the most likely to start first.
291 locked_or_queued = candidates.
292 where("state IN (?)", [Locked, Queued]).
293 order('state asc, priority desc, created_at asc').
296 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
297 return locked_or_queued
299 log_reuse_info { "have no containers in Locked or Queued state" }
302 log_reuse_info { "done, no reusable container found" }
307 if self.state != Queued
308 raise LockFailedError.new("cannot lock when #{self.state}")
309 elsif self.priority <= 0
310 raise LockFailedError.new("cannot lock when priority<=0")
315 # Check invalid state transitions once before getting the lock
316 # (because it's cheaper that way) and once after getting the lock
317 # (because state might have changed while acquiring the lock).
322 update_attributes!(state: Locked)
326 def check_unlock_fail
327 if self.state != Locked
328 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
329 elsif self.locked_by_uuid != current_api_client_authorization.uuid
330 raise InvalidStateTransitionError.new("locked by a different token")
335 # Check invalid state transitions twice (see lock)
338 reload(lock: 'FOR UPDATE')
340 update_attributes!(state: Queued)
344 def self.readable_by(*users_list)
345 # Load optional keyword arguments, if they exist.
346 if users_list.last.is_a? Hash
347 kwargs = users_list.pop
351 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
355 [Complete, Cancelled].include?(self.state)
360 def fill_field_defaults
361 self.state ||= Queued
362 self.environment ||= {}
363 self.runtime_constraints ||= {}
367 self.scheduling_parameters ||= {}
370 def permission_to_create
371 current_user.andand.is_admin
374 def permission_to_update
375 # Override base permission check to allow auth_uuid to set progress and
376 # output (only). Whether it is legal to set progress and output in the current
377 # state has already been checked in validate_change.
378 current_user.andand.is_admin ||
379 (!current_api_client_authorization.nil? and
380 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
383 def ensure_owner_uuid_is_permitted
384 # Override base permission check to allow auth_uuid to set progress and
385 # output (only). Whether it is legal to set progress and output in the current
386 # state has already been checked in validate_change.
387 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
388 check_update_whitelist [:progress, :output]
395 if self.state_changed? and self.state == Running
396 self.started_at ||= db_current_time
399 if self.state_changed? and [Complete, Cancelled].include? self.state
400 self.finished_at ||= db_current_time
408 permitted.push(:owner_uuid, :command, :container_image, :cwd,
409 :environment, :mounts, :output_path, :priority,
410 :runtime_constraints, :scheduling_parameters,
416 permitted.push :priority
419 permitted.push :priority, :progress, :output
420 if self.state_changed?
421 permitted.push :started_at
425 if self.state_was == Running
426 permitted.push :finished_at, :output, :log, :exit_code
432 permitted.push :finished_at, :output, :log
434 permitted.push :finished_at, :log
438 # The state_transitions check will add an error message for this
442 check_update_whitelist permitted
446 if [Locked, Running].include? self.state
447 # If the Container was already locked, locked_by_uuid must not
448 # changes. Otherwise, the current auth gets the lock.
449 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
454 # The caller can provide a new value for locked_by_uuid, but only
455 # if it's exactly what we expect. This allows a caller to perform
456 # an update like {"state":"Unlocked","locked_by_uuid":null}.
457 if self.locked_by_uuid_changed?
458 if self.locked_by_uuid != need_lock
459 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
462 self.locked_by_uuid = need_lock
466 # Output must exist and be readable by the current user. This is so
467 # that a container cannot "claim" a collection that it doesn't otherwise
468 # have access to just by setting the output field to the collection PDH.
471 readable_by(current_user, {include_trash: true}).
472 where(portable_data_hash: self.output).
475 errors.add :output, "collection must exist and be readable by current user."
481 if self.auth_uuid_changed?
482 return errors.add :auth_uuid, 'is readonly'
484 if not [Locked, Running].include? self.state
486 self.auth.andand.update_attributes(expires_at: db_current_time)
493 cr = ContainerRequest.
494 where('container_uuid=? and priority>0', self.uuid).
495 order('priority desc').
498 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
500 self.auth = ApiClientAuthorization.
501 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
505 def sort_serialized_attrs
506 if self.environment_changed?
507 self.environment = self.class.deep_sort_hash(self.environment)
509 if self.mounts_changed?
510 self.mounts = self.class.deep_sort_hash(self.mounts)
512 if self.runtime_constraints_changed?
513 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
515 if self.scheduling_parameters_changed?
516 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
520 def update_secret_mounts_md5
521 if self.secret_mounts_changed?
522 self.secret_mounts_md5 = Digest::MD5.hexdigest(
523 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
527 def scrub_secret_mounts
528 # this runs after update_secret_mounts_md5, so the
529 # secret_mounts_md5 will still reflect the secrets that are being
531 if self.state_changed? && self.final?
532 self.secret_mounts = {}
537 # This container is finished so finalize any associated container requests
538 # that are associated with this container.
539 if self.state_changed? and self.final?
540 act_as_system_user do
542 if self.state == Cancelled
543 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
545 retryable_requests = []
548 if retryable_requests.any?
550 command: self.command,
552 environment: self.environment,
553 output_path: self.output_path,
554 container_image: self.container_image,
556 runtime_constraints: self.runtime_constraints,
557 scheduling_parameters: self.scheduling_parameters
559 c = Container.create! c_attrs
560 retryable_requests.each do |cr|
562 leave_modified_by_user_alone do
563 # Use row locking because this increments container_count
564 cr.container_uuid = c.uuid
571 # Notify container requests associated with this container
572 ContainerRequest.where(container_uuid: uuid,
573 state: ContainerRequest::Committed).each do |cr|
574 leave_modified_by_user_alone do
579 # Cancel outstanding container requests made by this container.
581 includes(:container).
582 where(requesting_container_uuid: uuid,
583 state: ContainerRequest::Committed).each do |cr|
584 leave_modified_by_user_alone do
585 cr.update_attributes!(priority: 0)
587 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
588 # If the child container hasn't started yet, finalize the
589 # child CR now instead of leaving it "on hold", i.e.,
590 # Queued with priority 0. (OTOH, if the child is already
591 # running, leave it alone so it can get cancelled the
592 # usual way, get a copy of the log collection, etc.)
593 cr.update_attributes!(state: ContainerRequest::Final)