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 = {
160 Rails.configuration.container_default_keep_cache_ram,
161 }.merge(runtime_constraints_for_container)
162 c_container_image = container_image_for_container
163 c = act_as_system_user do
164 c_attrs = {command: self.command,
166 environment: self.environment,
167 output_path: self.output_path,
168 container_image: c_container_image,
170 runtime_constraints: c_runtime_constraints}
172 reusable = self.use_existing ? Container.find_reusable(c_attrs) : nil
176 c_attrs[:scheduling_parameters] = self.scheduling_parameters
177 Container.create!(c_attrs)
180 self.container_uuid = c.uuid
183 # Return a runtime_constraints hash that complies with
184 # self.runtime_constraints but is suitable for saving in a container
185 # record, i.e., has specific values instead of ranges.
187 # Doing this as a step separate from other resolutions, like "git
188 # revision range to commit hash", makes sense only when there is no
189 # opportunity to reuse an existing container (e.g., container reuse
190 # is not implemented yet, or we have already found that no existing
191 # containers are suitable).
192 def runtime_constraints_for_container
194 runtime_constraints.each do |k, v|
204 # Return a mounts hash suitable for a Container, i.e., with every
205 # readonly collection UUID resolved to a PDH.
206 def mounts_for_container
208 mounts.each do |k, mount|
211 if mount['kind'] != 'collection'
214 if (uuid = mount.delete 'uuid')
216 readable_by(current_user).
218 select(:portable_data_hash).
221 raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
223 if mount['portable_data_hash'].nil?
224 # PDH not supplied by client
225 mount['portable_data_hash'] = c.portable_data_hash
226 elsif mount['portable_data_hash'] != c.portable_data_hash
227 # UUID and PDH supplied by client, but they don't agree
228 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"
235 # Return a container_image PDH suitable for a Container.
236 def container_image_for_container
237 coll = Collection.for_latest_docker_image(container_image)
239 raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
241 coll.portable_data_hash
245 if (container_uuid_changed? and
246 not current_user.andand.is_admin and
247 not container_uuid.nil?)
248 errors.add :container_uuid, "can only be updated to nil."
251 if state_changed? and state == Committed and container_uuid.nil?
254 if self.container_uuid != self.container_uuid_was
255 if self.container_count_changed?
256 errors.add :container_count, "cannot be updated directly."
259 self.container_count += 1
264 def validate_runtime_constraints
269 ['keep_cache_ram', false]].each do |k, required|
270 if !required && !runtime_constraints.include?(k)
273 v = runtime_constraints[k]
274 unless (v.is_a?(Integer) && v > 0)
275 errors.add(:runtime_constraints,
276 "[#{k}]=#{v.inspect} must be a positive integer")
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