1 require 'whitelist_update'
3 class ContainerRequest < ArvadosModel
6 include CommonApiTemplate
7 include WhitelistUpdate
9 serialize :properties, Hash
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 :validate_runtime_constraints
18 before_validation :validate_scheduling_parameters
19 before_validation :set_container
20 validates :command, :container_image, :output_path, :cwd, :presence => true
21 validate :validate_state_change
22 validate :validate_change
23 after_save :update_priority
24 after_save :finalize_if_needed
25 before_create :set_requesting_container_uuid
27 api_accessible :user, extend: :common do |t|
29 t.add :container_count
30 t.add :container_count_max
31 t.add :container_image
46 t.add :requesting_container_uuid
47 t.add :runtime_constraints
48 t.add :scheduling_parameters
53 # Supported states for a container request
56 (Uncommitted = 'Uncommitted'),
57 (Committed = 'Committed'),
62 nil => [Uncommitted, Committed],
63 Uncommitted => [Committed],
71 def skip_uuid_read_permission_check
72 # XXX temporary until permissions are sorted out.
73 %w(modified_by_client_uuid container_uuid requesting_container_uuid)
76 def finalize_if_needed
77 if state == Committed && Container.find_by_uuid(container_uuid).final?
85 # Finalize the container request after the container has
90 c = Container.find_by_uuid(container_uuid)
91 ['output', 'log'].each do |out_type|
92 pdh = c.send(out_type)
94 if self.output_name and out_type == 'output'
95 coll_name = self.output_name
97 coll_name = "Container #{out_type} for request #{uuid}"
99 manifest = Collection.unscoped.where(portable_data_hash: pdh).first.manifest_text
101 coll = Collection.create!(owner_uuid: owner_uuid,
102 manifest_text: manifest,
103 portable_data_hash: pdh,
107 'container_request' => uuid,
109 rescue ActiveRecord::RecordNotUnique => rn
110 # In case this is executed as part of a transaction: When a Postgres exception happens,
111 # the following statements on the same transaction become invalid, so a rollback is
112 # needed. One example are Unit Tests, every test is enclosed inside a transaction so
113 # that the database can be reverted before every new test starts.
114 # See: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Exception+handling+and+rolling+back
115 ActiveRecord::Base.connection.execute 'ROLLBACK'
116 raise unless out_type == 'output' and self.output_name
117 # Postgres specific unique name check. See ApplicationController#create for
118 # a detailed explanation.
119 raise unless rn.original_exception.is_a? PG::UniqueViolation
120 err = rn.original_exception
121 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
122 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
123 # Output collection name collision detected: append a timestamp.
124 coll_name = "#{self.output_name} #{Time.now.getgm.strftime('%FT%TZ')}"
127 if out_type == 'output'
133 update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)
136 def self.full_text_searchable_columns
142 def fill_field_defaults
143 self.state ||= Uncommitted
144 self.environment ||= {}
145 self.runtime_constraints ||= {}
148 self.container_count_max ||= Rails.configuration.container_count_max
149 self.scheduling_parameters ||= {}
152 # Create a new container (or find an existing one) to satisfy this
155 c_mounts = mounts_for_container
156 c_runtime_constraints = runtime_constraints_for_container
157 c_container_image = container_image_for_container
158 c = act_as_system_user do
159 c_attrs = {command: self.command,
161 environment: self.environment,
162 output_path: self.output_path,
163 container_image: c_container_image,
165 runtime_constraints: c_runtime_constraints}
167 reusable = self.use_existing ? Container.find_reusable(c_attrs) : nil
171 c_attrs[:scheduling_parameters] = self.scheduling_parameters
172 Container.create!(c_attrs)
175 self.container_uuid = c.uuid
178 # Return a runtime_constraints hash that complies with
179 # self.runtime_constraints but is suitable for saving in a container
180 # record, i.e., has specific values instead of ranges.
182 # Doing this as a step separate from other resolutions, like "git
183 # revision range to commit hash", makes sense only when there is no
184 # opportunity to reuse an existing container (e.g., container reuse
185 # is not implemented yet, or we have already found that no existing
186 # containers are suitable).
187 def runtime_constraints_for_container
189 runtime_constraints.each do |k, v|
199 # Return a mounts hash suitable for a Container, i.e., with every
200 # readonly collection UUID resolved to a PDH.
201 def mounts_for_container
203 mounts.each do |k, mount|
206 if mount['kind'] != 'collection'
209 if (uuid = mount.delete 'uuid')
211 readable_by(current_user).
213 select(:portable_data_hash).
216 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
218 if mount['portable_data_hash'].nil?
219 # PDH not supplied by client
220 mount['portable_data_hash'] = c.portable_data_hash
221 elsif mount['portable_data_hash'] != c.portable_data_hash
222 # UUID and PDH supplied by client, but they don't agree
223 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"
230 # Return a container_image PDH suitable for a Container.
231 def container_image_for_container
232 coll = Collection.for_latest_docker_image(container_image)
234 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
236 return Collection.docker_migration_pdh([current_user], coll.portable_data_hash)
240 if (container_uuid_changed? and
241 not current_user.andand.is_admin and
242 not container_uuid.nil?)
243 errors.add :container_uuid, "can only be updated to nil."
246 if state_changed? and state == Committed and container_uuid.nil?
249 if self.container_uuid != self.container_uuid_was
250 if self.container_count_changed?
251 errors.add :container_count, "cannot be updated directly."
254 self.container_count += 1
259 def validate_runtime_constraints
262 ['vcpus', 'ram'].each do |k|
263 if not (runtime_constraints.include? k and
264 runtime_constraints[k].is_a? Integer and
265 runtime_constraints[k] > 0)
266 errors.add :runtime_constraints, "#{k} must be a positive integer"
270 if runtime_constraints.include? 'keep_cache_ram' and
271 (!runtime_constraints['keep_cache_ram'].is_a?(Integer) or
272 runtime_constraints['keep_cache_ram'] <= 0)
273 errors.add :runtime_constraints, "keep_cache_ram must be a positive integer"
274 elsif !runtime_constraints.include? 'keep_cache_ram'
275 runtime_constraints['keep_cache_ram'] = Rails.configuration.container_default_keep_cache_ram
280 def validate_scheduling_parameters
281 if self.state == Committed
282 if scheduling_parameters.include? 'partitions' and
283 (!scheduling_parameters['partitions'].is_a?(Array) ||
284 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
285 scheduling_parameters['partitions'].size)
286 errors.add :scheduling_parameters, "partitions must be an array of strings"
292 permitted = [:owner_uuid]
296 # Permit updating most fields
297 permitted.push :command, :container_count_max,
298 :container_image, :cwd, :description, :environment,
299 :filters, :mounts, :name, :output_path, :priority,
300 :properties, :requesting_container_uuid, :runtime_constraints,
301 :state, :container_uuid, :use_existing, :scheduling_parameters,
305 if container_uuid.nil?
306 errors.add :container_uuid, "has not been resolved to a container."
310 errors.add :priority, "cannot be nil"
313 # Can update priority, container count, name and description
314 permitted.push :priority, :container_count, :container_count_max, :container_uuid,
317 if self.state_changed?
318 # Allow create-and-commit in a single operation.
319 permitted.push :command, :container_image, :cwd, :description, :environment,
320 :filters, :mounts, :name, :output_path, :properties,
321 :requesting_container_uuid, :runtime_constraints,
322 :state, :container_uuid, :use_existing, :scheduling_parameters,
327 if not current_user.andand.is_admin and not (self.name_changed? || self.description_changed?)
328 errors.add :state, "of container request can only be set to Final by system."
331 if self.state_changed? || self.name_changed? || self.description_changed? || self.output_uuid_changed? || self.log_uuid_changed?
332 permitted.push :state, :name, :description, :output_uuid, :log_uuid
334 errors.add :state, "does not allow updates"
338 errors.add :state, "invalid value"
341 check_update_whitelist permitted
345 if self.state_changed? or
346 self.priority_changed? or
347 self.container_uuid_changed?
348 act_as_system_user do
351 [self.container_uuid_was, self.container_uuid].compact).
352 map(&:update_priority!)
357 def set_requesting_container_uuid
358 return !new_record? if self.requesting_container_uuid # already set
360 token_uuid = current_api_client_authorization.andand.uuid
361 container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
362 self.requesting_container_uuid = container.uuid if container