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
10 include ArvadosModelUpdates
13 include CommonApiTemplate
14 include WhitelistUpdate
15 extend CurrentApiClient
19 serialize :environment, Hash
20 serialize :mounts, Hash
21 serialize :runtime_constraints, Hash
22 serialize :command, Array
23 serialize :scheduling_parameters, Hash
24 serialize :secret_mounts, Hash
26 before_validation :fill_field_defaults, :if => :new_record?
27 before_validation :set_timestamps
28 validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
29 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
30 validate :validate_state_change
31 validate :validate_change
32 validate :validate_lock
33 validate :validate_output
34 after_validation :assign_auth
35 before_save :sort_serialized_attrs
36 before_save :update_secret_mounts_md5
37 before_save :scrub_secret_mounts
38 after_save :handle_completed
39 after_save :propagate_priority
41 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
42 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
44 api_accessible :user, extend: :common do |t|
46 t.add :container_image
58 t.add :runtime_constraints
62 t.add :scheduling_parameters
65 # Supported states for a container
70 (Running = 'Running'),
71 (Complete = 'Complete'),
72 (Cancelled = 'Cancelled')
77 Queued => [Locked, Cancelled],
78 Locked => [Queued, Running, Cancelled],
79 Running => [Complete, Cancelled]
82 def self.limit_index_columns_read
86 def self.full_text_searchable_columns
87 super - ["secret_mounts", "secret_mounts_md5"]
90 def self.searchable_columns *args
91 super - ["secret_mounts_md5"]
95 super.except('secret_mounts')
102 # Container priority is the highest "computed priority" of any
103 # matching request. The computed priority of a container-submitted
104 # request is the priority of the submitting container. The computed
105 # priority of a user-submitted request is a function of
106 # user-assigned priority and request creation time.
108 return if ![Queued, Locked, Running].include?(state)
109 p = ContainerRequest.
110 where('container_uuid=? and priority>0', uuid).
111 includes(:requesting_container).
114 if cr.requesting_container
115 cr.requesting_container.priority
117 (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
120 update_attributes!(priority: p)
123 def propagate_priority
124 return true unless priority_changed?
125 act_as_system_user do
126 # Update the priority of child container requests to match new
127 # priority of the parent container (ignoring requests with no
128 # container assigned, because their priority doesn't matter).
129 ActiveRecord::Base.connection.execute('LOCK container_requests, containers IN EXCLUSIVE MODE')
131 where(requesting_container_uuid: self.uuid,
132 state: ContainerRequest::Committed).
133 where('container_uuid is not null').
134 includes(:container).
136 map(&:update_priority!)
140 # Create a new container (or find an existing one) to satisfy the
141 # given container request.
142 def self.resolve(req)
144 command: req.command,
146 environment: req.environment,
147 output_path: req.output_path,
148 container_image: resolve_container_image(req.container_image),
149 mounts: resolve_mounts(req.mounts),
150 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
151 scheduling_parameters: req.scheduling_parameters,
152 secret_mounts: req.secret_mounts,
154 act_as_system_user do
155 if req.use_existing && (reusable = find_reusable(c_attrs))
158 Container.create!(c_attrs)
163 # Return a runtime_constraints hash that complies with requested but
164 # is suitable for saving in a container record, i.e., has specific
165 # values instead of ranges.
167 # Doing this as a step separate from other resolutions, like "git
168 # revision range to commit hash", makes sense only when there is no
169 # opportunity to reuse an existing container (e.g., container reuse
170 # is not implemented yet, or we have already found that no existing
171 # containers are suitable).
172 def self.resolve_runtime_constraints(runtime_constraints)
176 Rails.configuration.container_default_keep_cache_ram,
178 defaults.merge(runtime_constraints).each do |k, v|
188 # Return a mounts hash suitable for a Container, i.e., with every
189 # readonly collection UUID resolved to a PDH.
190 def self.resolve_mounts(mounts)
192 mounts.each do |k, mount|
195 if mount['kind'] != 'collection'
198 if (uuid = mount.delete 'uuid')
200 readable_by(current_user).
202 select(:portable_data_hash).
205 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
207 if mount['portable_data_hash'].nil?
208 # PDH not supplied by client
209 mount['portable_data_hash'] = c.portable_data_hash
210 elsif mount['portable_data_hash'] != c.portable_data_hash
211 # UUID and PDH supplied by client, but they don't agree
212 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"
219 # Return a container_image PDH suitable for a Container.
220 def self.resolve_container_image(container_image)
221 coll = Collection.for_latest_docker_image(container_image)
223 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
225 coll.portable_data_hash
228 def self.find_reusable(attrs)
229 log_reuse_info { "starting with #{Container.all.count} container records in database" }
230 candidates = Container.where_serialized(:command, attrs[:command])
231 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
233 candidates = candidates.where('cwd = ?', attrs[:cwd])
234 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
236 candidates = candidates.where_serialized(:environment, attrs[:environment])
237 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
239 candidates = candidates.where('output_path = ?', attrs[:output_path])
240 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
242 image = resolve_container_image(attrs[:container_image])
243 candidates = candidates.where('container_image = ?', image)
244 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
246 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
247 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
249 candidates = candidates.where('secret_mounts_md5 = ?', Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts]))))
250 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
252 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
253 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
255 log_reuse_info { "checking for state=Complete with readable output and log..." }
257 select_readable_pdh = Collection.
258 readable_by(current_user).
259 select(:portable_data_hash).
262 usable = candidates.where(state: Complete, exit_code: 0)
263 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
265 usable = usable.where("log IN (#{select_readable_pdh})")
266 log_reuse_info(usable) { "with readable log" }
268 usable = usable.where("output IN (#{select_readable_pdh})")
269 log_reuse_info(usable) { "with readable output" }
271 usable = usable.order('finished_at ASC').limit(1).first
273 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
277 # Check for Running candidates and return the most likely to finish sooner.
278 log_reuse_info { "checking for state=Running..." }
279 running = candidates.where(state: Running).
280 order('progress desc, started_at asc').
283 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
286 log_reuse_info { "have no containers in Running state" }
289 # Check for Locked or Queued ones and return the most likely to start first.
290 locked_or_queued = candidates.
291 where("state IN (?)", [Locked, Queued]).
292 order('state asc, priority desc, created_at asc').
295 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
296 return locked_or_queued
298 log_reuse_info { "have no containers in Locked or Queued state" }
301 log_reuse_info { "done, no reusable container found" }
306 if self.state != Queued
307 raise LockFailedError.new("cannot lock when #{self.state}")
308 elsif self.priority <= 0
309 raise LockFailedError.new("cannot lock when priority<=0")
314 # Check invalid state transitions once before getting the lock
315 # (because it's cheaper that way) and once after getting the lock
316 # (because state might have changed while acquiring the lock).
319 # Locking involves assigning auth_uuid, which involves looking
320 # up container requests, so we must lock both tables in the
321 # proper order to avoid deadlock.
322 ActiveRecord::Base.connection.execute('LOCK container_requests, containers IN EXCLUSIVE MODE')
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
422 permitted.push :priority, :progress, :output
423 if self.state_changed?
424 permitted.push :started_at
428 if self.state_was == Running
429 permitted.push :finished_at, :output, :log, :exit_code
435 permitted.push :finished_at, :output, :log
437 permitted.push :finished_at, :log
441 # The state_transitions check will add an error message for this
445 check_update_whitelist permitted
449 if [Locked, Running].include? self.state
450 # If the Container was already locked, locked_by_uuid must not
451 # changes. Otherwise, the current auth gets the lock.
452 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
457 # The caller can provide a new value for locked_by_uuid, but only
458 # if it's exactly what we expect. This allows a caller to perform
459 # an update like {"state":"Unlocked","locked_by_uuid":null}.
460 if self.locked_by_uuid_changed?
461 if self.locked_by_uuid != need_lock
462 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
465 self.locked_by_uuid = need_lock
469 # Output must exist and be readable by the current user. This is so
470 # that a container cannot "claim" a collection that it doesn't otherwise
471 # have access to just by setting the output field to the collection PDH.
474 readable_by(current_user, {include_trash: true}).
475 where(portable_data_hash: self.output).
478 errors.add :output, "collection must exist and be readable by current user."
484 if self.auth_uuid_changed?
485 return errors.add :auth_uuid, 'is readonly'
487 if not [Locked, Running].include? self.state
489 self.auth.andand.update_attributes(expires_at: db_current_time)
496 cr = ContainerRequest.
497 where('container_uuid=? and priority>0', self.uuid).
498 order('priority desc').
501 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
503 self.auth = ApiClientAuthorization.
504 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
508 def sort_serialized_attrs
509 if self.environment_changed?
510 self.environment = self.class.deep_sort_hash(self.environment)
512 if self.mounts_changed?
513 self.mounts = self.class.deep_sort_hash(self.mounts)
515 if self.runtime_constraints_changed?
516 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
518 if self.scheduling_parameters_changed?
519 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
523 def update_secret_mounts_md5
524 if self.secret_mounts_changed?
525 self.secret_mounts_md5 = Digest::MD5.hexdigest(
526 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
530 def scrub_secret_mounts
531 # this runs after update_secret_mounts_md5, so the
532 # secret_mounts_md5 will still reflect the secrets that are being
534 if self.state_changed? && self.final?
535 self.secret_mounts = {}
540 # This container is finished so finalize any associated container requests
541 # that are associated with this container.
542 if self.state_changed? and self.final?
543 act_as_system_user do
545 ActiveRecord::Base.connection.execute('LOCK container_requests, containers IN EXCLUSIVE MODE')
546 if self.state == Cancelled
547 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
549 retryable_requests = []
552 if retryable_requests.any?
554 command: self.command,
556 environment: self.environment,
557 output_path: self.output_path,
558 container_image: self.container_image,
560 runtime_constraints: self.runtime_constraints,
561 scheduling_parameters: self.scheduling_parameters
563 c = Container.create! c_attrs
564 retryable_requests.each do |cr|
566 leave_modified_by_user_alone do
567 # Use row locking because this increments container_count
568 cr.container_uuid = c.uuid
575 # Notify container requests associated with this container
576 ContainerRequest.where(container_uuid: uuid,
577 state: ContainerRequest::Committed).each do |cr|
578 leave_modified_by_user_alone do
583 # Cancel outstanding container requests made by this container.
585 includes(:container).
586 where(requesting_container_uuid: uuid,
587 state: ContainerRequest::Committed).each do |cr|
588 leave_modified_by_user_alone do
589 cr.update_attributes!(priority: 0)
591 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
592 # If the child container hasn't started yet, finalize the
593 # child CR now instead of leaving it "on hold", i.e.,
594 # Queued with priority 0. (OTOH, if the child is already
595 # running, leave it alone so it can get cancelled the
596 # usual way, get a copy of the log collection, etc.)
597 cr.update_attributes!(state: ContainerRequest::Final)