1 require 'whitelist_update'
3 class Container < ArvadosModel
6 include CommonApiTemplate
7 include WhitelistUpdate
8 extend CurrentApiClient
10 serialize :environment, Hash
11 serialize :mounts, Hash
12 serialize :runtime_constraints, Hash
13 serialize :command, Array
14 serialize :scheduling_parameters, Hash
16 before_validation :fill_field_defaults, :if => :new_record?
17 before_validation :set_timestamps
18 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
19 validate :validate_state_change
20 validate :validate_change
21 validate :validate_lock
22 validate :validate_output
23 after_validation :assign_auth
24 before_save :sort_serialized_attrs
25 after_save :handle_completed
27 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
28 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
30 api_accessible :user, extend: :common do |t|
32 t.add :container_image
44 t.add :runtime_constraints
48 t.add :scheduling_parameters
51 # Supported states for a container
56 (Running = 'Running'),
57 (Complete = 'Complete'),
58 (Cancelled = 'Cancelled')
63 Queued => [Locked, Cancelled],
64 Locked => [Queued, Running, Cancelled],
65 Running => [Complete, Cancelled]
73 if [Queued, Locked, Running].include? self.state
74 # Update the priority of this container to the maximum priority of any of
75 # its committed container requests and save the record.
76 self.priority = ContainerRequest.
77 where(container_uuid: uuid,
78 state: ContainerRequest::Committed).
84 def self.find_reusable(attrs)
85 candidates = Container.
86 where('command = ?', attrs[:command].to_yaml).
87 where('cwd = ?', attrs[:cwd]).
88 where('environment = ?', self.deep_sort_hash(attrs[:environment]).to_yaml).
89 where('output_path = ?', attrs[:output_path]).
90 where('container_image = ?', attrs[:container_image]).
91 where('mounts = ?', self.deep_sort_hash(attrs[:mounts]).to_yaml).
92 where('runtime_constraints = ?', self.deep_sort_hash(attrs[:runtime_constraints]).to_yaml)
94 # Check for Completed candidates whose output and log are both readable.
95 select_readable_pdh = Collection.
96 readable_by(current_user).
97 select(:portable_data_hash).
100 where(state: Complete).
102 where("log IN (#{select_readable_pdh})").
103 where("output IN (#{select_readable_pdh})").
104 order('finished_at ASC').
107 return usable if usable
109 # Check for Running candidates and return the most likely to finish sooner.
110 running = candidates.where(state: Running).
111 order('progress desc, started_at asc').limit(1).first
112 return running if not running.nil?
114 # Check for Locked or Queued ones and return the most likely to start first.
115 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
116 order('state asc, priority desc, created_at asc').limit(1).first
117 return locked_or_queued if not locked_or_queued.nil?
119 # No suitable candidate found.
125 if self.state == Locked
126 raise AlreadyLockedError
135 if self.state == Queued
136 raise InvalidStateTransitionError
143 def self.readable_by(*users_list)
144 if users_list.select { |u| u.is_admin }.any?
147 user_uuids = users_list.map { |u| u.uuid }
148 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
150 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
151 joins(:container_requests).
152 where("container_requests.uuid IN #{permitted} OR "+
153 "container_requests.owner_uuid IN (:uuids)",
158 [Complete, Cancelled].include?(self.state)
163 def fill_field_defaults
164 self.state ||= Queued
165 self.environment ||= {}
166 self.runtime_constraints ||= {}
170 self.scheduling_parameters ||= {}
173 def permission_to_create
174 current_user.andand.is_admin
177 def permission_to_update
178 # Override base permission check to allow auth_uuid to set progress and
179 # output (only). Whether it is legal to set progress and output in the current
180 # state has already been checked in validate_change.
181 current_user.andand.is_admin ||
182 (!current_api_client_authorization.nil? and
183 [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
186 def ensure_owner_uuid_is_permitted
187 # Override base permission check to allow auth_uuid to set progress and
188 # output (only). Whether it is legal to set progress and output in the current
189 # state has already been checked in validate_change.
190 if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
191 check_update_whitelist [:progress, :output]
198 if self.state_changed? and self.state == Running
199 self.started_at ||= db_current_time
202 if self.state_changed? and [Complete, Cancelled].include? self.state
203 self.finished_at ||= db_current_time
211 permitted.push(:owner_uuid, :command, :container_image, :cwd,
212 :environment, :mounts, :output_path, :priority,
213 :runtime_constraints, :scheduling_parameters)
218 permitted.push :priority
221 permitted.push :priority, :progress, :output
222 if self.state_changed?
223 permitted.push :started_at
227 if self.state_was == Running
228 permitted.push :finished_at, :output, :log, :exit_code
234 permitted.push :finished_at, :output, :log
236 permitted.push :finished_at
240 # The state_transitions check will add an error message for this
244 check_update_whitelist permitted
248 if [Locked, Running].include? self.state
249 # If the Container was already locked, locked_by_uuid must not
250 # changes. Otherwise, the current auth gets the lock.
251 need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
256 # The caller can provide a new value for locked_by_uuid, but only
257 # if it's exactly what we expect. This allows a caller to perform
258 # an update like {"state":"Unlocked","locked_by_uuid":null}.
259 if self.locked_by_uuid_changed?
260 if self.locked_by_uuid != need_lock
261 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
264 self.locked_by_uuid = need_lock
268 # Output must exist and be readable by the current user. This is so
269 # that a container cannot "claim" a collection that it doesn't otherwise
270 # have access to just by setting the output field to the collection PDH.
272 c = Collection.unscoped do
274 readable_by(current_user).
275 where(portable_data_hash: self.output).
279 errors.add :output, "collection must exist and be readable by current user."
285 if self.auth_uuid_changed?
286 return errors.add :auth_uuid, 'is readonly'
288 if not [Locked, Running].include? self.state
290 self.auth.andand.update_attributes(expires_at: db_current_time)
297 cr = ContainerRequest.
298 where('container_uuid=? and priority>0', self.uuid).
299 order('priority desc').
302 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
304 self.auth = ApiClientAuthorization.
305 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
309 def sort_serialized_attrs
310 if self.environment_changed?
311 self.environment = self.class.deep_sort_hash(self.environment)
313 if self.mounts_changed?
314 self.mounts = self.class.deep_sort_hash(self.mounts)
316 if self.runtime_constraints_changed?
317 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
319 if self.scheduling_parameters_changed?
320 self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
325 # This container is finished so finalize any associated container requests
326 # that are associated with this container.
327 if self.state_changed? and self.final?
328 act_as_system_user do
330 if self.state == Cancelled
331 retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
333 retryable_requests = []
336 if retryable_requests.any?
338 command: self.command,
340 environment: self.environment,
341 output_path: self.output_path,
342 container_image: self.container_image,
344 runtime_constraints: self.runtime_constraints,
345 scheduling_parameters: self.scheduling_parameters
347 c = Container.create! c_attrs
348 retryable_requests.each do |cr|
350 # Use row locking because this increments container_count
351 cr.container_uuid = c.uuid
357 # Notify container requests associated with this container
358 ContainerRequest.where(container_uuid: uuid,
359 state: ContainerRequest::Committed).each do |cr|
363 # Try to cancel any outstanding container requests made by this container.
364 ContainerRequest.where(requesting_container_uuid: uuid,
365 state: ContainerRequest::Committed).each do |cr|