1 require 'whitelist_update'
4 class Container < ArvadosModel
7 include CommonApiTemplate
8 include WhitelistUpdate
9 extend CurrentApiClient
11 serialize :environment, Hash
12 serialize :mounts, Hash
13 serialize :runtime_constraints, Hash
14 serialize :command, Array
15 serialize :scheduling_parameters, Hash
17 before_validation :fill_field_defaults, :if => :new_record?
18 before_validation :set_timestamps
19 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
20 validate :validate_state_change
21 validate :validate_change
22 validate :validate_lock
23 validate :validate_output
24 after_validation :assign_auth
25 before_save :sort_serialized_attrs
26 after_save :handle_completed
28 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
29 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
31 api_accessible :user, extend: :common do |t|
33 t.add :container_image
45 t.add :runtime_constraints
49 t.add :scheduling_parameters
52 # Supported states for a container
57 (Running = 'Running'),
58 (Complete = 'Complete'),
59 (Cancelled = 'Cancelled')
64 Queued => [Locked, Cancelled],
65 Locked => [Queued, Running, Cancelled],
66 Running => [Complete, Cancelled]
74 if [Queued, Locked, Running].include? self.state
75 # Update the priority of this container to the maximum priority of any of
76 # its committed container requests and save the record.
77 self.priority = ContainerRequest.
78 where(container_uuid: uuid,
79 state: ContainerRequest::Committed).
85 # Create a new container (or find an existing one) to satisfy the
86 # given container request.
91 environment: req.environment,
92 output_path: req.output_path,
93 container_image: resolve_container_image(req.container_image),
94 mounts: resolve_mounts(req.mounts),
95 runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
96 scheduling_parameters: req.scheduling_parameters,
99 if req.use_existing && (reusable = find_reusable(c_attrs))
102 Container.create!(c_attrs)
107 # Return a runtime_constraints hash that complies with requested but
108 # is suitable for saving in a container record, i.e., has specific
109 # values instead of ranges.
111 # Doing this as a step separate from other resolutions, like "git
112 # revision range to commit hash", makes sense only when there is no
113 # opportunity to reuse an existing container (e.g., container reuse
114 # is not implemented yet, or we have already found that no existing
115 # containers are suitable).
116 def self.resolve_runtime_constraints(runtime_constraints)
120 Rails.configuration.container_default_keep_cache_ram,
122 defaults.merge(runtime_constraints).each do |k, v|
132 # Return a mounts hash suitable for a Container, i.e., with every
133 # readonly collection UUID resolved to a PDH.
134 def self.resolve_mounts(mounts)
136 mounts.each do |k, mount|
139 if mount['kind'] != 'collection'
142 if (uuid = mount.delete 'uuid')
144 readable_by(current_user).
146 select(:portable_data_hash).
149 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
151 if mount['portable_data_hash'].nil?
152 # PDH not supplied by client
153 mount['portable_data_hash'] = c.portable_data_hash
154 elsif mount['portable_data_hash'] != c.portable_data_hash
155 # UUID and PDH supplied by client, but they don't agree
156 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"
163 # Return a container_image PDH suitable for a Container.
164 def self.resolve_container_image(container_image)
165 coll = Collection.for_latest_docker_image(container_image)
167 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
169 coll.portable_data_hash
172 def self.find_reusable(attrs)
173 candidates = Container.
174 where_serialized(:command, attrs[:command]).
175 where('cwd = ?', attrs[:cwd]).
176 where_serialized(:environment, attrs[:environment]).
177 where('output_path = ?', attrs[:output_path]).
178 where('container_image = ?', resolve_container_image(attrs[:container_image])).
179 where_serialized(:mounts, resolve_mounts(attrs[:mounts])).
180 where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
182 # Check for Completed candidates whose output and log are both readable.
183 select_readable_pdh = Collection.
184 readable_by(current_user).
185 select(:portable_data_hash).
188 where(state: Complete).
190 where("log IN (#{select_readable_pdh})").
191 where("output IN (#{select_readable_pdh})").
192 order('finished_at ASC').
195 return usable if usable
197 # Check for Running candidates and return the most likely to finish sooner.
198 running = candidates.where(state: Running).
199 order('progress desc, started_at asc').limit(1).first
200 return running if not running.nil?
202 # Check for Locked or Queued ones and return the most likely to start first.
203 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
204 order('state asc, priority desc, created_at asc').limit(1).first
205 return locked_or_queued if not locked_or_queued.nil?
207 # No suitable candidate found.
213 if self.state == Locked
214 raise AlreadyLockedError
223 if self.state == Queued
224 raise InvalidStateTransitionError
231 def self.readable_by(*users_list)
232 if users_list.select { |u| u.is_admin }.any?
235 user_uuids = users_list.map { |u| u.uuid }
236 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
238 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
239 joins(:container_requests).
240 where("container_requests.uuid IN #{permitted} OR "+
241 "container_requests.owner_uuid IN (:uuids)",
246 [Complete, Cancelled].include?(self.state)
251 def fill_field_defaults
252 self.state ||= Queued
253 self.environment ||= {}
254 self.runtime_constraints ||= {}
258 self.scheduling_parameters ||= {}
261 def permission_to_create
262 current_user.andand.is_admin
265 def permission_to_update
266 # Override base permission check to allow auth_uuid to set progress and
267 # output (only). Whether it is legal to set progress and output in the current
268 # state has already been checked in validate_change.
269 current_user.andand.is_admin ||
270 (!current_api_client_authorization.nil? and
271 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
274 def ensure_owner_uuid_is_permitted
275 # Override base permission check to allow auth_uuid to set progress and
276 # output (only). Whether it is legal to set progress and output in the current
277 # state has already been checked in validate_change.
278 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
279 check_update_whitelist [:progress, :output]
286 if self.state_changed? and self.state == Running
287 self.started_at ||= db_current_time
290 if self.state_changed? and [Complete, Cancelled].include? self.state
291 self.finished_at ||= db_current_time
299 permitted.push(:owner_uuid, :command, :container_image, :cwd,
300 :environment, :mounts, :output_path, :priority,
301 :runtime_constraints, :scheduling_parameters)
306 permitted.push :priority
309 permitted.push :priority, :progress, :output
310 if self.state_changed?
311 permitted.push :started_at
315 if self.state_was == Running
316 permitted.push :finished_at, :output, :log, :exit_code
322 permitted.push :finished_at, :output, :log
324 permitted.push :finished_at
328 # The state_transitions check will add an error message for this
332 check_update_whitelist permitted
336 if [Locked, Running].include? self.state
337 # If the Container was already locked, locked_by_uuid must not
338 # changes. Otherwise, the current auth gets the lock.
339 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
344 # The caller can provide a new value for locked_by_uuid, but only
345 # if it's exactly what we expect. This allows a caller to perform
346 # an update like {"state":"Unlocked","locked_by_uuid":null}.
347 if self.locked_by_uuid_changed?
348 if self.locked_by_uuid != need_lock
349 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
352 self.locked_by_uuid = need_lock
356 # Output must exist and be readable by the current user. This is so
357 # that a container cannot "claim" a collection that it doesn't otherwise
358 # have access to just by setting the output field to the collection PDH.
360 c = Collection.unscoped do
362 readable_by(current_user).
363 where(portable_data_hash: self.output).
367 errors.add :output, "collection must exist and be readable by current user."
373 if self.auth_uuid_changed?
374 return errors.add :auth_uuid, 'is readonly'
376 if not [Locked, Running].include? self.state
378 self.auth.andand.update_attributes(expires_at: db_current_time)
385 cr = ContainerRequest.
386 where('container_uuid=? and priority>0', self.uuid).
387 order('priority desc').
390 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
392 self.auth = ApiClientAuthorization.
393 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
397 def sort_serialized_attrs
398 if self.environment_changed?
399 self.environment = self.class.deep_sort_hash(self.environment)
401 if self.mounts_changed?
402 self.mounts = self.class.deep_sort_hash(self.mounts)
404 if self.runtime_constraints_changed?
405 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
407 if self.scheduling_parameters_changed?
408 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
413 # This container is finished so finalize any associated container requests
414 # that are associated with this container.
415 if self.state_changed? and self.final?
416 act_as_system_user do
418 if self.state == Cancelled
419 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
421 retryable_requests = []
424 if retryable_requests.any?
426 command: self.command,
428 environment: self.environment,
429 output_path: self.output_path,
430 container_image: self.container_image,
432 runtime_constraints: self.runtime_constraints,
433 scheduling_parameters: self.scheduling_parameters
435 c = Container.create! c_attrs
436 retryable_requests.each do |cr|
438 # Use row locking because this increments container_count
439 cr.container_uuid = c.uuid
445 # Notify container requests associated with this container
446 ContainerRequest.where(container_uuid: uuid,
447 state: ContainerRequest::Committed).each do |cr|
451 # Try to cancel any outstanding container requests made by this container.
452 ContainerRequest.where(requesting_container_uuid: uuid,
453 state: ContainerRequest::Committed).each do |cr|