1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 require 'whitelist_update'
6 require 'arvados/collection'
8 class ContainerRequest < ArvadosModel
9 include ArvadosModelUpdates
12 include CommonApiTemplate
13 include WhitelistUpdate
15 belongs_to :container, foreign_key: :container_uuid, primary_key: :uuid
16 belongs_to :requesting_container, {
17 class_name: 'Container',
18 foreign_key: :requesting_container_uuid,
22 serialize :properties, Hash
23 serialize :environment, Hash
24 serialize :mounts, Hash
25 serialize :runtime_constraints, Hash
26 serialize :command, Array
27 serialize :scheduling_parameters, Hash
28 serialize :secret_mounts, Hash
30 before_validation :fill_field_defaults, :if => :new_record?
31 before_validation :validate_runtime_constraints
32 before_validation :set_default_preemptible_scheduling_parameter
33 before_validation :set_container
34 validates :command, :container_image, :output_path, :cwd, :presence => true
35 validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
36 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
37 validate :validate_datatypes
38 validate :validate_scheduling_parameters
39 validate :validate_state_change
40 validate :check_update_whitelist
41 validate :secret_mounts_key_conflict
42 validate :validate_runtime_token
43 before_save :scrub_secrets
44 before_create :set_requesting_container_uuid
45 before_destroy :set_priority_zero
46 after_save :update_priority
47 after_save :finalize_if_needed
49 api_accessible :user, extend: :common do |t|
51 t.add :container_count
52 t.add :container_count_max
53 t.add :container_image
69 t.add :requesting_container_uuid
70 t.add :runtime_constraints
71 t.add :scheduling_parameters
76 # Supported states for a container request
79 (Uncommitted = 'Uncommitted'),
80 (Committed = 'Committed'),
85 nil => [Uncommitted, Committed],
86 Uncommitted => [Committed],
90 AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
91 AttrsPermittedBeforeCommit = [:command, :container_count_max,
92 :container_image, :cwd, :environment, :filters, :mounts,
93 :output_path, :priority, :runtime_token,
94 :runtime_constraints, :state, :container_uuid, :use_existing,
95 :scheduling_parameters, :secret_mounts, :output_name, :output_ttl]
97 def self.limit_index_columns_read
101 def logged_attributes
102 super.except('secret_mounts', 'runtime_token')
105 def state_transitions
109 def skip_uuid_read_permission_check
110 # The uuid_read_permission_check prevents users from making
111 # references to objects they can't view. However, in this case we
112 # don't want to do that check since there's a circular dependency
113 # where user can't view the container until the user has
114 # constructed the container request that references the container.
118 def finalize_if_needed
119 if state == Committed && Container.find_by_uuid(container_uuid).final?
121 act_as_system_user do
122 leave_modified_by_user_alone do
129 # Finalize the container request after the container has
130 # finished/cancelled.
132 update_collections(container: Container.find_by_uuid(container_uuid))
133 update_attributes!(state: Final)
136 def update_collections(container:, collections: ['log', 'output'])
137 collections.each do |out_type|
138 pdh = container.send(out_type)
140 coll_name = "Container #{out_type} for request #{uuid}"
142 if out_type == 'output'
144 coll_name = self.output_name
146 if self.output_ttl > 0
147 trash_at = db_current_time + self.output_ttl
150 manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
152 coll_uuid = self.send(out_type + '_uuid')
153 coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
155 coll = Collection.new(
156 owner_uuid: self.owner_uuid,
161 'container_request' => uuid,
166 src = Arv::Collection.new(manifest)
167 dst = Arv::Collection.new(coll.manifest_text)
168 dst.cp_r("./", ".", src)
169 dst.cp_r("./", "log for container #{container.uuid}", src)
170 manifest = dst.manifest_text
173 coll.assign_attributes(
174 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
175 manifest_text: manifest,
178 coll.save_with_unique_name!
179 self.send(out_type + '_uuid=', coll.uuid)
183 def self.full_text_searchable_columns
184 super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token"]
189 def fill_field_defaults
190 self.state ||= Uncommitted
191 self.environment ||= {}
192 self.runtime_constraints ||= {}
195 self.container_count_max ||= Rails.configuration.container_count_max
196 self.scheduling_parameters ||= {}
197 self.output_ttl ||= 0
202 if (container_uuid_changed? and
203 not current_user.andand.is_admin and
204 not container_uuid.nil?)
205 errors.add :container_uuid, "can only be updated to nil."
208 if state_changed? and state == Committed and container_uuid.nil?
209 self.container_uuid = Container.resolve(self).uuid
211 if self.container_uuid != self.container_uuid_was
212 if self.container_count_changed?
213 errors.add :container_count, "cannot be updated directly."
216 self.container_count += 1
217 if self.container_uuid_was
218 old_container = Container.find_by_uuid(self.container_uuid_was)
219 old_logs = Collection.where(portable_data_hash: old_container.log).first
221 log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
222 if self.log_uuid.nil?
223 log_coll = Collection.new(
224 owner_uuid: self.owner_uuid,
225 name: coll_name = "Container log for request #{uuid}",
229 # copy logs from old container into CR's log collection
230 src = Arv::Collection.new(old_logs.manifest_text)
231 dst = Arv::Collection.new(log_coll.manifest_text)
232 dst.cp_r("./", "log for container #{old_container.uuid}", src)
233 manifest = dst.manifest_text
235 log_coll.assign_attributes(
236 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
237 manifest_text: manifest)
238 log_coll.save_with_unique_name!
239 self.log_uuid = log_coll.uuid
246 def set_default_preemptible_scheduling_parameter
247 c = get_requesting_container()
248 if self.state == Committed
249 # If preemptible instances (eg: AWS Spot Instances) are allowed,
250 # ask them on child containers by default.
251 if Rails.configuration.preemptible_instances and !c.nil? and
252 self.scheduling_parameters['preemptible'].nil?
253 self.scheduling_parameters['preemptible'] = true
258 def validate_runtime_constraints
263 ['keep_cache_ram', false]].each do |k, required|
264 if !required && !runtime_constraints.include?(k)
267 v = runtime_constraints[k]
268 unless (v.is_a?(Integer) && v > 0)
269 errors.add(:runtime_constraints,
270 "[#{k}]=#{v.inspect} must be a positive integer")
276 def validate_datatypes
279 errors.add(:command, "must be an array of strings but has entry #{c.class}")
282 environment.each do |k,v|
283 if !k.is_a?(String) || !v.is_a?(String)
284 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
287 [:mounts, :secret_mounts].each do |m|
288 self[m].each do |k, v|
289 if !k.is_a?(String) || !v.is_a?(Hash)
290 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
293 errors.add(m, "each item must have a 'kind' field")
295 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
296 "path", "commit", "repository_name", "git_url"]],
297 [Integer, ["capacity"]]].each do |t, fields|
299 if !v[f].nil? && !v[f].is_a?(t)
300 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
304 ["writable", "exclude_from_output"].each do |f|
305 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
306 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
313 def validate_scheduling_parameters
314 if self.state == Committed
315 if scheduling_parameters.include? 'partitions' and
316 (!scheduling_parameters['partitions'].is_a?(Array) ||
317 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
318 scheduling_parameters['partitions'].size)
319 errors.add :scheduling_parameters, "partitions must be an array of strings"
321 if !Rails.configuration.preemptible_instances and scheduling_parameters['preemptible']
322 errors.add :scheduling_parameters, "preemptible instances are not allowed"
324 if scheduling_parameters.include? 'max_run_time' and
325 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
326 scheduling_parameters['max_run_time'] < 0)
327 errors.add :scheduling_parameters, "max_run_time must be positive integer"
332 def check_update_whitelist
333 permitted = AttrsPermittedAlways.dup
335 if self.new_record? || self.state_was == Uncommitted
336 # Allow create-and-commit in a single operation.
337 permitted.push(*AttrsPermittedBeforeCommit)
342 permitted.push :priority, :container_count_max, :container_uuid
344 if self.container_uuid.nil?
345 self.errors.add :container_uuid, "has not been resolved to a container."
348 if self.priority.nil?
349 self.errors.add :priority, "cannot be nil"
352 # Allow container count to increment by 1
353 if (self.container_uuid &&
354 self.container_uuid != self.container_uuid_was &&
355 self.container_count == 1 + (self.container_count_was || 0))
356 permitted.push :container_count
359 if current_user.andand.is_admin
360 permitted.push :log_uuid
364 if self.state_was == Committed
365 # "Cancel" means setting priority=0, state=Committed
366 permitted.push :priority
368 if current_user.andand.is_admin
369 permitted.push :output_uuid, :log_uuid
378 def secret_mounts_key_conflict
379 secret_mounts.each do |k, v|
380 if mounts.has_key?(k)
381 errors.add(:secret_mounts, 'conflict with non-secret mounts')
387 def validate_runtime_token
388 if !self.runtime_token.nil? && self.runtime_token_changed?
389 if !runtime_token[0..2] == "v2/"
390 errors.add :runtime_token, "not a v2 token"
393 if ApiClientAuthorization.validate(token: runtime_token).nil?
394 errors.add :runtime_token, "failed validation"
400 if self.state == Final
401 self.secret_mounts = {}
402 self.runtime_token = nil
407 return unless state_changed? || priority_changed? || container_uuid_changed?
408 act_as_system_user do
410 where('uuid in (?)', [self.container_uuid_was, self.container_uuid].compact).
411 map(&:update_priority!)
415 def set_priority_zero
416 self.update_attributes!(priority: 0) if self.state != Final
419 def set_requesting_container_uuid
420 c = get_requesting_container()
422 self.requesting_container_uuid = c.uuid
423 # Determine the priority of container request for the requesting
425 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
429 def get_requesting_container
430 return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
431 Container.for_current_token