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], md5: true)
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], md5: true)
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]), md5: true)
248 log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
250 secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
251 candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
252 log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
254 candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
255 log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
257 log_reuse_info { "checking for state=Complete with readable output and log..." }
259 select_readable_pdh = Collection.
260 readable_by(current_user).
261 select(:portable_data_hash).
264 usable = candidates.where(state: Complete, exit_code: 0)
265 log_reuse_info(usable) { "with state=Complete, exit_code=0" }
267 usable = usable.where("log IN (#{select_readable_pdh})")
268 log_reuse_info(usable) { "with readable log" }
270 usable = usable.where("output IN (#{select_readable_pdh})")
271 log_reuse_info(usable) { "with readable output" }
273 usable = usable.order('finished_at ASC').limit(1).first
275 log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
279 # Check for Running candidates and return the most likely to finish sooner.
280 log_reuse_info { "checking for state=Running..." }
281 running = candidates.where(state: Running).
282 order('progress desc, started_at asc').
285 log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
288 log_reuse_info { "have no containers in Running state" }
291 # Check for Locked or Queued ones and return the most likely to start first.
292 locked_or_queued = candidates.
293 where("state IN (?)", [Locked, Queued]).
294 order('state asc, priority desc, created_at asc').
297 log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
298 return locked_or_queued
300 log_reuse_info { "have no containers in Locked or Queued state" }
303 log_reuse_info { "done, no reusable container found" }
308 if self.state != Queued
309 raise LockFailedError.new("cannot lock when #{self.state}")
310 elsif self.priority <= 0
311 raise LockFailedError.new("cannot lock when priority<=0")
316 # Check invalid state transitions once before getting the lock
317 # (because it's cheaper that way) and once after getting the lock
318 # (because state might have changed while acquiring the lock).
323 update_attributes!(state: Locked)
327 def check_unlock_fail
328 if self.state != Locked
329 raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
330 elsif self.locked_by_uuid != current_api_client_authorization.uuid
331 raise InvalidStateTransitionError.new("locked by a different token")
336 # Check invalid state transitions twice (see lock)
339 reload(lock: 'FOR UPDATE')
341 update_attributes!(state: Queued)
345 def self.readable_by(*users_list)
346 # Load optional keyword arguments, if they exist.
347 if users_list.last.is_a? Hash
348 kwargs = users_list.pop
352 Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
356 [Complete, Cancelled].include?(self.state)
361 def fill_field_defaults
362 self.state ||= Queued
363 self.environment ||= {}
364 self.runtime_constraints ||= {}
368 self.scheduling_parameters ||= {}
371 def permission_to_create
372 current_user.andand.is_admin
375 def permission_to_update
376 # Override base permission check to allow auth_uuid to set progress and
377 # output (only). Whether it is legal to set progress and output in the current
378 # state has already been checked in validate_change.
379 current_user.andand.is_admin ||
380 (!current_api_client_authorization.nil? and
381 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
384 def ensure_owner_uuid_is_permitted
385 # Override base permission check to allow auth_uuid to set progress and
386 # output (only). Whether it is legal to set progress and output in the current
387 # state has already been checked in validate_change.
388 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
389 check_update_whitelist [:progress, :output]
396 if self.state_changed? and self.state == Running
397 self.started_at ||= db_current_time
400 if self.state_changed? and [Complete, Cancelled].include? self.state
401 self.finished_at ||= db_current_time
409 permitted.push(:owner_uuid, :command, :container_image, :cwd,
410 :environment, :mounts, :output_path, :priority,
411 :runtime_constraints, :scheduling_parameters,
417 permitted.push :priority
420 permitted.push :priority, :progress, :output
421 if self.state_changed?
422 permitted.push :started_at
426 if self.state_was == Running
427 permitted.push :finished_at, :output, :log, :exit_code
433 permitted.push :finished_at, :output, :log
435 permitted.push :finished_at, :log
439 # The state_transitions check will add an error message for this
443 check_update_whitelist permitted
447 if [Locked, Running].include? self.state
448 # If the Container was already locked, locked_by_uuid must not
449 # changes. Otherwise, the current auth gets the lock.
450 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
455 # The caller can provide a new value for locked_by_uuid, but only
456 # if it's exactly what we expect. This allows a caller to perform
457 # an update like {"state":"Unlocked","locked_by_uuid":null}.
458 if self.locked_by_uuid_changed?
459 if self.locked_by_uuid != need_lock
460 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
463 self.locked_by_uuid = need_lock
467 # Output must exist and be readable by the current user. This is so
468 # that a container cannot "claim" a collection that it doesn't otherwise
469 # have access to just by setting the output field to the collection PDH.
472 readable_by(current_user, {include_trash: true}).
473 where(portable_data_hash: self.output).
476 errors.add :output, "collection must exist and be readable by current user."
482 if self.auth_uuid_changed?
483 return errors.add :auth_uuid, 'is readonly'
485 if not [Locked, Running].include? self.state
487 self.auth.andand.update_attributes(expires_at: db_current_time)
494 cr = ContainerRequest.
495 where('container_uuid=? and priority>0', self.uuid).
496 order('priority desc').
499 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
501 self.auth = ApiClientAuthorization.
502 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
506 def sort_serialized_attrs
507 if self.environment_changed?
508 self.environment = self.class.deep_sort_hash(self.environment)
510 if self.mounts_changed?
511 self.mounts = self.class.deep_sort_hash(self.mounts)
513 if self.runtime_constraints_changed?
514 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
516 if self.scheduling_parameters_changed?
517 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
521 def update_secret_mounts_md5
522 if self.secret_mounts_changed?
523 self.secret_mounts_md5 = Digest::MD5.hexdigest(
524 SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
528 def scrub_secret_mounts
529 # this runs after update_secret_mounts_md5, so the
530 # secret_mounts_md5 will still reflect the secrets that are being
532 if self.state_changed? && self.final?
533 self.secret_mounts = {}
538 # This container is finished so finalize any associated container requests
539 # that are associated with this container.
540 if self.state_changed? and self.final?
541 act_as_system_user do
543 if self.state == Cancelled
544 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
546 retryable_requests = []
549 if retryable_requests.any?
551 command: self.command,
553 environment: self.environment,
554 output_path: self.output_path,
555 container_image: self.container_image,
557 runtime_constraints: self.runtime_constraints,
558 scheduling_parameters: self.scheduling_parameters
560 c = Container.create! c_attrs
561 retryable_requests.each do |cr|
563 leave_modified_by_user_alone do
564 # Use row locking because this increments container_count
565 cr.container_uuid = c.uuid
572 # Notify container requests associated with this container
573 ContainerRequest.where(container_uuid: uuid,
574 state: ContainerRequest::Committed).each do |cr|
575 leave_modified_by_user_alone do
580 # Cancel outstanding container requests made by this container.
582 includes(:container).
583 where(requesting_container_uuid: uuid,
584 state: ContainerRequest::Committed).each do |cr|
585 leave_modified_by_user_alone do
586 cr.update_attributes!(priority: 0)
588 if cr.container.state == Container::Queued || cr.container.state == Container::Locked
589 # If the child container hasn't started yet, finalize the
590 # child CR now instead of leaving it "on hold", i.e.,
591 # Queued with priority 0. (OTOH, if the child is already
592 # running, leave it alone so it can get cancelled the
593 # usual way, get a copy of the log collection, etc.)
594 cr.update_attributes!(state: ContainerRequest::Final)