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 do
100 Collection.where(portable_data_hash: pdh).first.manifest_text
103 coll = Collection.create!(owner_uuid: owner_uuid,
104 manifest_text: manifest,
105 portable_data_hash: pdh,
109 'container_request' => uuid,
111 rescue ActiveRecord::RecordNotUnique => rn
112 # In case this is executed as part of a transaction: When a Postgres exception happens,
113 # the following statements on the same transaction become invalid, so a rollback is
114 # needed. One example are Unit Tests, every test is enclosed inside a transaction so
115 # that the database can be reverted before every new test starts.
116 # See: http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#module-ActiveRecord::Transactions::ClassMethods-label-Exception+handling+and+rolling+back
117 ActiveRecord::Base.connection.execute 'ROLLBACK'
118 raise unless out_type == 'output' and self.output_name
119 # Postgres specific unique name check. See ApplicationController#create for
120 # a detailed explanation.
121 raise unless rn.original_exception.is_a? PG::UniqueViolation
122 err = rn.original_exception
123 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
124 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
125 # Output collection name collision detected: append a timestamp.
126 coll_name = "#{self.output_name} #{Time.now.getgm.strftime('%FT%TZ')}"
129 if out_type == 'output'
135 update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)
138 def self.full_text_searchable_columns
144 def fill_field_defaults
145 self.state ||= Uncommitted
146 self.environment ||= {}
147 self.runtime_constraints ||= {}
150 self.container_count_max ||= Rails.configuration.container_count_max
151 self.scheduling_parameters ||= {}
154 # Create a new container (or find an existing one) to satisfy this
157 c_mounts = mounts_for_container
158 c_runtime_constraints = runtime_constraints_for_container
159 c_container_image = container_image_for_container
160 c = act_as_system_user do
161 c_attrs = {command: self.command,
163 environment: self.environment,
164 output_path: self.output_path,
165 container_image: c_container_image,
167 runtime_constraints: c_runtime_constraints}
169 reusable = self.use_existing ? Container.find_reusable(c_attrs) : nil
173 c_attrs[:scheduling_parameters] = self.scheduling_parameters
174 Container.create!(c_attrs)
177 self.container_uuid = c.uuid
180 # Return a runtime_constraints hash that complies with
181 # self.runtime_constraints but is suitable for saving in a container
182 # record, i.e., has specific values instead of ranges.
184 # Doing this as a step separate from other resolutions, like "git
185 # revision range to commit hash", makes sense only when there is no
186 # opportunity to reuse an existing container (e.g., container reuse
187 # is not implemented yet, or we have already found that no existing
188 # containers are suitable).
189 def runtime_constraints_for_container
191 runtime_constraints.each do |k, v|
201 # Return a mounts hash suitable for a Container, i.e., with every
202 # readonly collection UUID resolved to a PDH.
203 def mounts_for_container
205 mounts.each do |k, mount|
208 if mount['kind'] != 'collection'
211 if (uuid = mount.delete 'uuid')
213 readable_by(current_user).
215 select(:portable_data_hash).
218 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
220 if mount['portable_data_hash'].nil?
221 # PDH not supplied by client
222 mount['portable_data_hash'] = c.portable_data_hash
223 elsif mount['portable_data_hash'] != c.portable_data_hash
224 # UUID and PDH supplied by client, but they don't agree
225 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"
232 # Return a container_image PDH suitable for a Container.
233 def container_image_for_container
234 coll = Collection.for_latest_docker_image(container_image)
236 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
238 return Collection.docker_migration_pdh([current_user], coll.portable_data_hash)
242 if (container_uuid_changed? and
243 not current_user.andand.is_admin and
244 not container_uuid.nil?)
245 errors.add :container_uuid, "can only be updated to nil."
248 if state_changed? and state == Committed and container_uuid.nil?
251 if self.container_uuid != self.container_uuid_was
252 if self.container_count_changed?
253 errors.add :container_count, "cannot be updated directly."
256 self.container_count += 1
261 def validate_runtime_constraints
264 ['vcpus', 'ram'].each do |k|
265 if not (runtime_constraints.include? k and
266 runtime_constraints[k].is_a? Integer and
267 runtime_constraints[k] > 0)
268 errors.add :runtime_constraints, "#{k} must be a positive integer"
272 if runtime_constraints.include? 'keep_cache_ram' and
273 (!runtime_constraints['keep_cache_ram'].is_a?(Integer) or
274 runtime_constraints['keep_cache_ram'] <= 0)
275 errors.add :runtime_constraints, "keep_cache_ram must be a positive integer"
276 elsif !runtime_constraints.include? 'keep_cache_ram'
277 runtime_constraints['keep_cache_ram'] = Rails.configuration.container_default_keep_cache_ram
282 def validate_scheduling_parameters
283 if self.state == Committed
284 if scheduling_parameters.include? 'partitions' and
285 (!scheduling_parameters['partitions'].is_a?(Array) ||
286 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
287 scheduling_parameters['partitions'].size)
288 errors.add :scheduling_parameters, "partitions must be an array of strings"
294 permitted = [:owner_uuid]
298 # Permit updating most fields
299 permitted.push :command, :container_count_max,
300 :container_image, :cwd, :description, :environment,
301 :filters, :mounts, :name, :output_path, :priority,
302 :properties, :requesting_container_uuid, :runtime_constraints,
303 :state, :container_uuid, :use_existing, :scheduling_parameters,
307 if container_uuid.nil?
308 errors.add :container_uuid, "has not been resolved to a container."
312 errors.add :priority, "cannot be nil"
315 # Can update priority, container count, name and description
316 permitted.push :priority, :container_count, :container_count_max, :container_uuid,
319 if self.state_changed?
320 # Allow create-and-commit in a single operation.
321 permitted.push :command, :container_image, :cwd, :description, :environment,
322 :filters, :mounts, :name, :output_path, :properties,
323 :requesting_container_uuid, :runtime_constraints,
324 :state, :container_uuid, :use_existing, :scheduling_parameters,
329 if not current_user.andand.is_admin and not (self.name_changed? || self.description_changed?)
330 errors.add :state, "of container request can only be set to Final by system."
333 if self.state_changed? || self.name_changed? || self.description_changed? || self.output_uuid_changed? || self.log_uuid_changed?
334 permitted.push :state, :name, :description, :output_uuid, :log_uuid
336 errors.add :state, "does not allow updates"
340 errors.add :state, "invalid value"
343 check_update_whitelist permitted
347 if self.state_changed? or
348 self.priority_changed? or
349 self.container_uuid_changed?
350 act_as_system_user do
353 [self.container_uuid_was, self.container_uuid].compact).
354 map(&:update_priority!)
359 def set_requesting_container_uuid
360 return !new_record? if self.requesting_container_uuid # already set
362 token_uuid = current_api_client_authorization.andand.uuid
363 container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
364 self.requesting_container_uuid = container.uuid if container