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'
9 class Container < ArvadosModel
12 include CommonApiTemplate
13 include WhitelistUpdate
14 extend CurrentApiClient
18 serialize :environment, Hash
19 serialize :mounts, Hash
20 serialize :runtime_constraints, Hash
21 serialize :command, Array
22 serialize :scheduling_parameters, Hash
23 serialize :secret_mounts, Hash
25 before_validation :fill_field_defaults, :if => :new_record?
26 before_validation :set_timestamps
27 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
28 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
29 validate :validate_state_change
30 validate :validate_change
31 validate :validate_lock
32 validate :validate_output
33 after_validation :assign_auth
34 before_save :sort_serialized_attrs
35 before_save :update_secret_mounts_md5
36 before_save :scrub_secret_mounts
37 after_save :handle_completed
38 after_save :propagate_priority
40 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
41 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
43 api_accessible :user, extend: :common do |t|
45 t.add :container_image
57 t.add :runtime_constraints
61 t.add :scheduling_parameters
64 # Supported states for a container
69 (Running = 'Running'),
70 (Complete = 'Complete'),
71 (Cancelled = 'Cancelled')
76 Queued => [Locked, Cancelled],
77 Locked => [Queued, Running, Cancelled],
78 Running => [Complete, Cancelled]
81 def self.limit_index_columns_read
85 def self.full_text_searchable_columns
86 super - ["secret_mounts", "secret_mounts_md5"]
89 def self.searchable_columns *args
90 super - ["secret_mounts_md5"]
94 super.except('secret_mounts')
102 if [Queued, Locked, Running].include? self.state
103 # Update the priority of this container to the maximum priority of any of
104 # its committed container requests and save the record.
105 self.priority = ContainerRequest.
106 where(container_uuid: uuid,
107 state: ContainerRequest::Committed).
108 maximum('priority') || 0
113 def propagate_priority
114 if self.priority_changed?
115 act_as_system_user do
116 # Update the priority of child container requests to match new priority
117 # of the parent container.
118 ContainerRequest.where(requesting_container_uuid: self.uuid,
119 state: ContainerRequest::Committed).each do |cr|
120 cr.priority = self.priority
127 # Create a new container (or find an existing one) to satisfy the
128 # given container request.
129 def self.resolve(req)
131 command: req.command,
133 environment: req.environment,
134 output_path: req.output_path,
135 container_image: resolve_container_image(req.container_image),
136 mounts: resolve_mounts(req.mounts),
137 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
138 scheduling_parameters: req.scheduling_parameters,
139 secret_mounts: req.secret_mounts,
141 act_as_system_user do
142 if req.use_existing && (reusable = find_reusable(c_attrs))
145 Container.create!(c_attrs)
150 # Return a runtime_constraints hash that complies with requested but
151 # is suitable for saving in a container record, i.e., has specific
152 # values instead of ranges.
154 # Doing this as a step separate from other resolutions, like "git
155 # revision range to commit hash", makes sense only when there is no
156 # opportunity to reuse an existing container (e.g., container reuse
157 # is not implemented yet, or we have already found that no existing
158 # containers are suitable).
159 def self.resolve_runtime_constraints(runtime_constraints)
163 Rails.configuration.container_default_keep_cache_ram,
165 defaults.merge(runtime_constraints).each do |k, v|
175 # Return a mounts hash suitable for a Container, i.e., with every
176 # readonly collection UUID resolved to a PDH.
177 def self.resolve_mounts(mounts)
179 mounts.each do |k, mount|
182 if mount['kind'] != 'collection'
185 if (uuid = mount.delete 'uuid')
187 readable_by(current_user).
189 select(:portable_data_hash).
192 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
194 if mount['portable_data_hash'].nil?
195 # PDH not supplied by client
196 mount['portable_data_hash'] = c.portable_data_hash
197 elsif mount['portable_data_hash'] != c.portable_data_hash
198 # UUID and PDH supplied by client, but they don't agree
199 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"
206 # Return a container_image PDH suitable for a Container.
207 def self.resolve_container_image(container_image)
208 coll = Collection.for_latest_docker_image(container_image)
210 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
212 coll.portable_data_hash
215 def self.find_reusable(attrs)
216 log_reuse_info { "starting with #{Container.all.count} container records in database" }
217 candidates = Container.where_serialized(:command, attrs[:command])
218 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
220 candidates = candidates.where('cwd = ?', attrs[:cwd])
221 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
223 candidates = candidates.where_serialized(:environment, attrs[:environment])
224 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
226 candidates = candidates.where('output_path = ?', attrs[:output_path])
227 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
229 image = resolve_container_image(attrs[:container_image])
230 candidates = candidates.where('container_image = ?', image)
231 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
233 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
234 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
236 candidates = candidates.where('secret_mounts_md5 = ?', Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts]))))
237 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
239 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
240 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
242 log_reuse_info { "checking for state=Complete with readable output and log..." }
244 select_readable_pdh = Collection.
245 readable_by(current_user).
246 select(:portable_data_hash).
249 usable = candidates.where(state: Complete, exit_code: 0)
250 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
252 usable = usable.where("log IN (#{select_readable_pdh})")
253 log_reuse_info(usable) { "with readable log" }
255 usable = usable.where("output IN (#{select_readable_pdh})")
256 log_reuse_info(usable) { "with readable output" }
258 usable = usable.order('finished_at ASC').limit(1).first
260 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
264 # Check for Running candidates and return the most likely to finish sooner.
265 log_reuse_info { "checking for state=Running..." }
266 running = candidates.where(state: Running).
267 order('progress desc, started_at asc').
270 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
273 log_reuse_info { "have no containers in Running state" }
276 # Check for Locked or Queued ones and return the most likely to start first.
277 locked_or_queued = candidates.
278 where("state IN (?)", [Locked, Queued]).
279 order('state asc, priority desc, created_at asc').
282 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
283 return locked_or_queued
285 log_reuse_info { "have no containers in Locked or Queued state" }
288 log_reuse_info { "done, no reusable container found" }
293 if self.state != Queued
294 raise LockFailedError.new("cannot lock when #{self.state}")
295 elsif self.priority <= 0
296 raise LockFailedError.new("cannot lock when priority<=0")
301 # Check invalid state transitions once before getting the lock
302 # (because it's cheaper that way) and once after getting the lock
303 # (because state might have changed while acquiring the lock).
307 reload(lock: 'FOR UPDATE NOWAIT')
309 raise LockFailedError.new("cannot lock: other transaction in progress")
312 update_attributes!(state: Locked)
316 def check_unlock_fail
317 if self.state != Locked
318 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
319 elsif self.locked_by_uuid != current_api_client_authorization.uuid
320 raise InvalidStateTransitionError.new("locked by a different token")
325 # Check invalid state transitions twice (see lock)
328 reload(lock: 'FOR UPDATE')
330 update_attributes!(state: Queued)
334 def self.readable_by(*users_list)
335 # Load optional keyword arguments, if they exist.
336 if users_list.last.is_a? Hash
337 kwargs = users_list.pop
341 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
345 [Complete, Cancelled].include?(self.state)
350 def fill_field_defaults
351 self.state ||= Queued
352 self.environment ||= {}
353 self.runtime_constraints ||= {}
357 self.scheduling_parameters ||= {}
360 def permission_to_create
361 current_user.andand.is_admin
364 def permission_to_update
365 # Override base permission check to allow auth_uuid to set progress and
366 # output (only). Whether it is legal to set progress and output in the current
367 # state has already been checked in validate_change.
368 current_user.andand.is_admin ||
369 (!current_api_client_authorization.nil? and
370 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
373 def ensure_owner_uuid_is_permitted
374 # Override base permission check to allow auth_uuid to set progress and
375 # output (only). Whether it is legal to set progress and output in the current
376 # state has already been checked in validate_change.
377 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
378 check_update_whitelist [:progress, :output]
385 if self.state_changed? and self.state == Running
386 self.started_at ||= db_current_time
389 if self.state_changed? and [Complete, Cancelled].include? self.state
390 self.finished_at ||= db_current_time
398 permitted.push(:owner_uuid, :command, :container_image, :cwd,
399 :environment, :mounts, :output_path, :priority,
400 :runtime_constraints, :scheduling_parameters,
406 permitted.push :priority
409 permitted.push :priority, :progress, :output
410 if self.state_changed?
411 permitted.push :started_at
415 if self.state_was == Running
416 permitted.push :finished_at, :output, :log, :exit_code
422 permitted.push :finished_at, :output, :log
424 permitted.push :finished_at, :log
428 # The state_transitions check will add an error message for this
432 check_update_whitelist permitted
436 if [Locked, Running].include? self.state
437 # If the Container was already locked, locked_by_uuid must not
438 # changes. Otherwise, the current auth gets the lock.
439 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
444 # The caller can provide a new value for locked_by_uuid, but only
445 # if it's exactly what we expect. This allows a caller to perform
446 # an update like {"state":"Unlocked","locked_by_uuid":null}.
447 if self.locked_by_uuid_changed?
448 if self.locked_by_uuid != need_lock
449 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
452 self.locked_by_uuid = need_lock
456 # Output must exist and be readable by the current user. This is so
457 # that a container cannot "claim" a collection that it doesn't otherwise
458 # have access to just by setting the output field to the collection PDH.
461 readable_by(current_user, {include_trash: true}).
462 where(portable_data_hash: self.output).
465 errors.add :output, "collection must exist and be readable by current user."
471 if self.auth_uuid_changed?
472 return errors.add :auth_uuid, 'is readonly'
474 if not [Locked, Running].include? self.state
476 self.auth.andand.update_attributes(expires_at: db_current_time)
483 cr = ContainerRequest.
484 where('container_uuid=? and priority>0', self.uuid).
485 order('priority desc').
488 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
490 self.auth = ApiClientAuthorization.
491 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
495 def sort_serialized_attrs
496 if self.environment_changed?
497 self.environment = self.class.deep_sort_hash(self.environment)
499 if self.mounts_changed?
500 self.mounts = self.class.deep_sort_hash(self.mounts)
502 if self.runtime_constraints_changed?
503 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
505 if self.scheduling_parameters_changed?
506 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
510 def update_secret_mounts_md5
511 if self.secret_mounts_changed?
512 self.secret_mounts_md5 = Digest::MD5.hexdigest(
513 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
517 def scrub_secret_mounts
518 # this runs after update_secret_mounts_md5, so the
519 # secret_mounts_md5 will still reflect the secrets that are being
521 if self.state_changed? && self.final?
522 self.secret_mounts = {}
527 # This container is finished so finalize any associated container requests
528 # that are associated with this container.
529 if self.state_changed? and self.final?
530 act_as_system_user do
532 if self.state == Cancelled
533 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
535 retryable_requests = []
538 if retryable_requests.any?
540 command: self.command,
542 environment: self.environment,
543 output_path: self.output_path,
544 container_image: self.container_image,
546 runtime_constraints: self.runtime_constraints,
547 scheduling_parameters: self.scheduling_parameters
549 c = Container.create! c_attrs
550 retryable_requests.each do |cr|
552 # Use row locking because this increments container_count
553 cr.container_uuid = c.uuid
559 # Notify container requests associated with this container
560 ContainerRequest.where(container_uuid: uuid,
561 state: ContainerRequest::Committed).each do |cr|
565 # Cancel outstanding container requests made by this container.
567 includes(:container).
568 where(requesting_container_uuid: uuid,
569 state: ContainerRequest::Committed).each do |cr|
570 cr.update_attributes!(priority: 0)
572 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
573 # If the child container hasn't started yet, finalize the
574 # child CR now instead of leaving it "on hold", i.e.,
575 # Queued with priority 0. (OTOH, if the child is already
576 # running, leave it alone so it can get cancelled the
577 # usual way, get a copy of the log collection, etc.)
578 cr.update_attributes!(state: ContainerRequest::Final)