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
24 before_validation :fill_field_defaults, :if => :new_record?
25 before_validation :set_timestamps
26 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
27 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
28 validate :validate_state_change
29 validate :validate_change
30 validate :validate_lock
31 validate :validate_output
32 after_validation :assign_auth
33 before_save :sort_serialized_attrs
34 after_save :handle_completed
35 after_save :propagate_priority
37 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
38 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
40 api_accessible :user, extend: :common do |t|
42 t.add :container_image
54 t.add :runtime_constraints
58 t.add :scheduling_parameters
61 # Supported states for a container
66 (Running = 'Running'),
67 (Complete = 'Complete'),
68 (Cancelled = 'Cancelled')
73 Queued => [Locked, Cancelled],
74 Locked => [Queued, Running, Cancelled],
75 Running => [Complete, Cancelled]
78 def self.limit_index_columns_read
87 if [Queued, Locked, Running].include? self.state
88 # Update the priority of this container to the maximum priority of any of
89 # its committed container requests and save the record.
90 self.priority = ContainerRequest.
91 where(container_uuid: uuid,
92 state: ContainerRequest::Committed).
93 maximum('priority') || 0
98 def propagate_priority
99 if self.priority_changed?
100 act_as_system_user do
101 # Update the priority of child container requests to match new priority
102 # of the parent container.
103 ContainerRequest.where(requesting_container_uuid: self.uuid,
104 state: ContainerRequest::Committed).each do |cr|
105 cr.priority = self.priority
112 # Create a new container (or find an existing one) to satisfy the
113 # given container request.
114 def self.resolve(req)
116 command: req.command,
118 environment: req.environment,
119 output_path: req.output_path,
120 container_image: resolve_container_image(req.container_image),
121 mounts: resolve_mounts(req.mounts),
122 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
123 scheduling_parameters: req.scheduling_parameters,
125 act_as_system_user do
126 if req.use_existing && (reusable = find_reusable(c_attrs))
129 Container.create!(c_attrs)
134 # Return a runtime_constraints hash that complies with requested but
135 # is suitable for saving in a container record, i.e., has specific
136 # values instead of ranges.
138 # Doing this as a step separate from other resolutions, like "git
139 # revision range to commit hash", makes sense only when there is no
140 # opportunity to reuse an existing container (e.g., container reuse
141 # is not implemented yet, or we have already found that no existing
142 # containers are suitable).
143 def self.resolve_runtime_constraints(runtime_constraints)
147 Rails.configuration.container_default_keep_cache_ram,
149 defaults.merge(runtime_constraints).each do |k, v|
159 # Return a mounts hash suitable for a Container, i.e., with every
160 # readonly collection UUID resolved to a PDH.
161 def self.resolve_mounts(mounts)
163 mounts.each do |k, mount|
166 if mount['kind'] != 'collection'
169 if (uuid = mount.delete 'uuid')
171 readable_by(current_user).
173 select(:portable_data_hash).
176 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
178 if mount['portable_data_hash'].nil?
179 # PDH not supplied by client
180 mount['portable_data_hash'] = c.portable_data_hash
181 elsif mount['portable_data_hash'] != c.portable_data_hash
182 # UUID and PDH supplied by client, but they don't agree
183 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"
190 # Return a container_image PDH suitable for a Container.
191 def self.resolve_container_image(container_image)
192 coll = Collection.for_latest_docker_image(container_image)
194 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
196 coll.portable_data_hash
199 def self.find_reusable(attrs)
200 log_reuse_info { "starting with #{Container.all.count} container records in database" }
201 candidates = Container.where_serialized(:command, attrs[:command])
202 log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
204 candidates = candidates.where('cwd = ?', attrs[:cwd])
205 log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
207 candidates = candidates.where_serialized(:environment, attrs[:environment])
208 log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
210 candidates = candidates.where('output_path = ?', attrs[:output_path])
211 log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
213 image = resolve_container_image(attrs[:container_image])
214 candidates = candidates.where('container_image = ?', image)
215 log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
217 candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]))
218 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
220 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
221 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
223 log_reuse_info { "checking for state=Complete with readable output and log..." }
225 select_readable_pdh = Collection.
226 readable_by(current_user).
227 select(:portable_data_hash).
230 usable = candidates.where(state: Complete, exit_code: 0)
231 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
233 usable = usable.where("log IN (#{select_readable_pdh})")
234 log_reuse_info(usable) { "with readable log" }
236 usable = usable.where("output IN (#{select_readable_pdh})")
237 log_reuse_info(usable) { "with readable output" }
239 usable = usable.order('finished_at ASC').limit(1).first
241 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
245 # Check for Running candidates and return the most likely to finish sooner.
246 log_reuse_info { "checking for state=Running..." }
247 running = candidates.where(state: Running).
248 order('progress desc, started_at asc').
251 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
254 log_reuse_info { "have no containers in Running state" }
257 # Check for Locked or Queued ones and return the most likely to start first.
258 locked_or_queued = candidates.
259 where("state IN (?)", [Locked, Queued]).
260 order('state asc, priority desc, created_at asc').
263 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
264 return locked_or_queued
266 log_reuse_info { "have no containers in Locked or Queued state" }
269 log_reuse_info { "done, no reusable container found" }
274 if self.state != Queued
275 raise LockFailedError.new("cannot lock when #{self.state}")
276 elsif self.priority <= 0
277 raise LockFailedError.new("cannot lock when priority<=0")
282 # Check invalid state transitions once before getting the lock
283 # (because it's cheaper that way) and once after getting the lock
284 # (because state might have changed while acquiring the lock).
288 reload(lock: 'FOR UPDATE NOWAIT')
290 raise LockFailedError.new("cannot lock: other transaction in progress")
293 update_attributes!(state: Locked)
297 def check_unlock_fail
298 if self.state != Locked
299 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
300 elsif self.locked_by_uuid != current_api_client_authorization.uuid
301 raise InvalidStateTransitionError.new("locked by a different token")
306 # Check invalid state transitions twice (see lock)
309 reload(lock: 'FOR UPDATE')
311 update_attributes!(state: Queued)
315 def self.readable_by(*users_list)
316 # Load optional keyword arguments, if they exist.
317 if users_list.last.is_a? Hash
318 kwargs = users_list.pop
322 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
326 [Complete, Cancelled].include?(self.state)
331 def fill_field_defaults
332 self.state ||= Queued
333 self.environment ||= {}
334 self.runtime_constraints ||= {}
338 self.scheduling_parameters ||= {}
341 def permission_to_create
342 current_user.andand.is_admin
345 def permission_to_update
346 # Override base permission check to allow auth_uuid to set progress and
347 # output (only). Whether it is legal to set progress and output in the current
348 # state has already been checked in validate_change.
349 current_user.andand.is_admin ||
350 (!current_api_client_authorization.nil? and
351 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
354 def ensure_owner_uuid_is_permitted
355 # Override base permission check to allow auth_uuid to set progress and
356 # output (only). Whether it is legal to set progress and output in the current
357 # state has already been checked in validate_change.
358 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
359 check_update_whitelist [:progress, :output]
366 if self.state_changed? and self.state == Running
367 self.started_at ||= db_current_time
370 if self.state_changed? and [Complete, Cancelled].include? self.state
371 self.finished_at ||= db_current_time
379 permitted.push(:owner_uuid, :command, :container_image, :cwd,
380 :environment, :mounts, :output_path, :priority,
381 :runtime_constraints, :scheduling_parameters)
386 permitted.push :priority
389 permitted.push :priority, :progress, :output
390 if self.state_changed?
391 permitted.push :started_at
395 if self.state_was == Running
396 permitted.push :finished_at, :output, :log, :exit_code
402 permitted.push :finished_at, :output, :log
404 permitted.push :finished_at, :log
408 # The state_transitions check will add an error message for this
412 check_update_whitelist permitted
416 if [Locked, Running].include? self.state
417 # If the Container was already locked, locked_by_uuid must not
418 # changes. Otherwise, the current auth gets the lock.
419 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
424 # The caller can provide a new value for locked_by_uuid, but only
425 # if it's exactly what we expect. This allows a caller to perform
426 # an update like {"state":"Unlocked","locked_by_uuid":null}.
427 if self.locked_by_uuid_changed?
428 if self.locked_by_uuid != need_lock
429 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
432 self.locked_by_uuid = need_lock
436 # Output must exist and be readable by the current user. This is so
437 # that a container cannot "claim" a collection that it doesn't otherwise
438 # have access to just by setting the output field to the collection PDH.
441 readable_by(current_user, {include_trash: true}).
442 where(portable_data_hash: self.output).
445 errors.add :output, "collection must exist and be readable by current user."
451 if self.auth_uuid_changed?
452 return errors.add :auth_uuid, 'is readonly'
454 if not [Locked, Running].include? self.state
456 self.auth.andand.update_attributes(expires_at: db_current_time)
463 cr = ContainerRequest.
464 where('container_uuid=? and priority>0', self.uuid).
465 order('priority desc').
468 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
470 self.auth = ApiClientAuthorization.
471 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
475 def sort_serialized_attrs
476 if self.environment_changed?
477 self.environment = self.class.deep_sort_hash(self.environment)
479 if self.mounts_changed?
480 self.mounts = self.class.deep_sort_hash(self.mounts)
482 if self.runtime_constraints_changed?
483 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
485 if self.scheduling_parameters_changed?
486 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
491 # This container is finished so finalize any associated container requests
492 # that are associated with this container.
493 if self.state_changed? and self.final?
494 act_as_system_user do
496 if self.state == Cancelled
497 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
499 retryable_requests = []
502 if retryable_requests.any?
504 command: self.command,
506 environment: self.environment,
507 output_path: self.output_path,
508 container_image: self.container_image,
510 runtime_constraints: self.runtime_constraints,
511 scheduling_parameters: self.scheduling_parameters
513 c = Container.create! c_attrs
514 retryable_requests.each do |cr|
516 # Use row locking because this increments container_count
517 cr.container_uuid = c.uuid
523 # Notify container requests associated with this container
524 ContainerRequest.where(container_uuid: uuid,
525 state: ContainerRequest::Committed).each do |cr|
529 # Cancel outstanding container requests made by this container.
531 includes(:container).
532 where(requesting_container_uuid: uuid,
533 state: ContainerRequest::Committed).each do |cr|
534 cr.update_attributes!(priority: 0)
536 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
537 # If the child container hasn't started yet, finalize the
538 # child CR now instead of leaving it "on hold", i.e.,
539 # Queued with priority 0. (OTOH, if the child is already
540 # running, leave it alone so it can get cancelled the
541 # usual way, get a copy of the log collection, etc.)
542 cr.update_attributes!(state: ContainerRequest::Final)