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
15 before_validation :fill_field_defaults, :if => :new_record?
16 before_validation :set_timestamps
17 validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
18 validate :validate_state_change
19 validate :validate_change
20 validate :validate_lock
21 validate :validate_output
22 after_validation :assign_auth
23 before_save :sort_serialized_attrs
24 after_save :handle_completed
26 has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
27 belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
29 api_accessible :user, extend: :common do |t|
31 t.add :container_image
43 t.add :runtime_constraints
49 # Supported states for a container
54 (Running = 'Running'),
55 (Complete = 'Complete'),
56 (Cancelled = 'Cancelled')
61 Queued => [Locked, Cancelled],
62 Locked => [Queued, Running, Cancelled],
63 Running => [Complete, Cancelled]
71 if [Queued, Locked, Running].include? self.state
72 # Update the priority of this container to the maximum priority of any of
73 # its committed container requests and save the record.
74 self.priority = ContainerRequest.
75 where(container_uuid: uuid,
76 state: ContainerRequest::Committed).
82 def self.find_reusable(attrs)
83 candidates = Container.
84 where('command = ?', attrs[:command].to_yaml).
85 where('cwd = ?', attrs[:cwd]).
86 where('environment = ?', self.deep_sort_hash(attrs[:environment]).to_yaml).
87 where('output_path = ?', attrs[:output_path]).
88 where('container_image = ?', attrs[:container_image]).
89 where('mounts = ?', self.deep_sort_hash(attrs[:mounts]).to_yaml).
90 where('runtime_constraints = ?', self.deep_sort_hash(attrs[:runtime_constraints]).to_yaml)
92 # Check for Completed candidates that had consistent outputs.
93 completed = candidates.where(state: Complete).where(exit_code: 0)
94 outputs = completed.select('output').group('output').limit(2)
95 if outputs.count.count != 1
96 Rails.logger.debug("Found #{outputs.count.length} different outputs")
98 readable_by(current_user).
99 where(portable_data_hash: outputs.first.output).
101 Rails.logger.info("Found reusable container(s) " +
102 "but output #{outputs.first} is not readable " +
103 "by user #{current_user.uuid}")
105 # Return the oldest eligible container whose log is still
106 # present and readable by current_user.
107 readable_pdh = Collection.
108 readable_by(current_user).
109 select('portable_data_hash')
110 completed = completed.
111 where("log in (#{readable_pdh.to_sql})").
112 order('finished_at asc').
115 return completed.first
117 Rails.logger.info("Found reusable container(s) but none with a log " +
118 "readable by user #{current_user.uuid}")
122 # Check for Running candidates and return the most likely to finish sooner.
123 running = candidates.where(state: Running).
124 order('progress desc, started_at asc').limit(1).first
125 return running if not running.nil?
127 # Check for Locked or Queued ones and return the most likely to start first.
128 locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
129 order('state asc, priority desc, created_at asc').limit(1).first
130 return locked_or_queued if not locked_or_queued.nil?
132 # No suitable candidate found.
138 if self.state == Locked
139 raise AlreadyLockedError
148 if self.state == Queued
149 raise InvalidStateTransitionError
156 def self.readable_by(*users_list)
157 if users_list.select { |u| u.is_admin }.any?
160 user_uuids = users_list.map { |u| u.uuid }
161 uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
163 permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
164 joins(:container_requests).
165 where("container_requests.uuid IN #{permitted} OR "+
166 "container_requests.owner_uuid IN (:uuids)",
171 [Complete, Cancelled].include?(self.state)
176 def fill_field_defaults
177 self.state ||= Queued
178 self.environment ||= {}
179 self.runtime_constraints ||= {}
185 def permission_to_create
186 current_user.andand.is_admin
189 def permission_to_update
190 current_user.andand.is_admin
194 if self.state_changed? and self.state == Running
195 self.started_at ||= db_current_time
198 if self.state_changed? and [Complete, Cancelled].include? self.state
199 self.finished_at ||= db_current_time
207 permitted.push(:owner_uuid, :command, :container_image, :cwd,
208 :environment, :mounts, :output_path, :priority,
209 :runtime_constraints)
214 permitted.push :priority
217 permitted.push :priority, :progress, :output
218 if self.state_changed?
219 permitted.push :started_at
223 if self.state_was == Running
224 permitted.push :finished_at, :output, :log, :exit_code
230 permitted.push :finished_at, :output, :log
232 permitted.push :finished_at
236 # The state_transitions check will add an error message for this
240 check_update_whitelist permitted
244 # If the Container is already locked by someone other than the
245 # current api_client_auth, disallow all changes -- except
246 # priority, which needs to change to reflect max(priority) of
247 # relevant ContainerRequests.
248 if !locked_by_uuid_was.nil? and locked_by_uuid_was != Thread.current[:api_client_authorization].uuid
249 if auth_uuid_was == Thread.current[:api_client_authorization].uuid
250 check_update_whitelist [:priority, :output, :progress]
252 check_update_whitelist [:priority]
256 if [Locked, Running].include? self.state
257 # If the Container was already locked, locked_by_uuid must not
258 # changes. Otherwise, the current auth gets the lock.
259 need_lock = locked_by_uuid_was || Thread.current[:api_client_authorization].uuid
264 # The caller can provide a new value for locked_by_uuid, but only
265 # if it's exactly what we expect. This allows a caller to perform
266 # an update like {"state":"Unlocked","locked_by_uuid":null}.
267 if self.locked_by_uuid_changed?
268 if self.locked_by_uuid != need_lock
269 return errors.add :locked_by_uuid, "can only change to #{need_lock}"
272 self.locked_by_uuid = need_lock
277 apiauth = ApiClientAuthorization.find_by_uuid(uuid: auth_uuid)
279 readable_by(User.find_by_id(apiauth.user_id)).
280 where(portable_data_hash: self.output).
283 raise #ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
289 if self.auth_uuid_changed?
290 return errors.add :auth_uuid, 'is readonly'
292 if not [Locked, Running].include? self.state
294 self.auth.andand.update_attributes(expires_at: db_current_time)
301 cr = ContainerRequest.
302 where('container_uuid=? and priority>0', self.uuid).
303 order('priority desc').
306 return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
308 self.auth = ApiClientAuthorization.
309 create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
313 def sort_serialized_attrs
314 if self.environment_changed?
315 self.environment = self.class.deep_sort_hash(self.environment)
317 if self.mounts_changed?
318 self.mounts = self.class.deep_sort_hash(self.mounts)
320 if self.runtime_constraints_changed?
321 self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
326 # This container is finished so finalize any associated container requests
327 # that are associated with this container.
328 if self.state_changed? and self.final?
329 act_as_system_user do
331 if self.state == Cancelled
332 retryable_requests = ContainerRequest.where("priority > 0 and state = 'Committed' and container_count < container_count_max")
334 retryable_requests = []
337 if retryable_requests.any?
339 command: self.command,
341 environment: self.environment,
342 output_path: self.output_path,
343 container_image: self.container_image,
345 runtime_constraints: self.runtime_constraints
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|