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 # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
23 # already know how to properly treat them.
24 serialize :environment, Hash
25 serialize :mounts, Hash
26 serialize :runtime_constraints, Hash
27 serialize :command, Array
28 serialize :scheduling_parameters, 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 ||= {}
194 self.secret_mounts ||= {}
196 self.container_count_max ||= Rails.configuration.container_count_max
197 self.scheduling_parameters ||= {}
198 self.output_ttl ||= 0
203 if (container_uuid_changed? and
204 not current_user.andand.is_admin and
205 not container_uuid.nil?)
206 errors.add :container_uuid, "can only be updated to nil."
209 if state_changed? and state == Committed and container_uuid.nil?
210 self.container_uuid = Container.resolve(self).uuid
212 if self.container_uuid != self.container_uuid_was
213 if self.container_count_changed?
214 errors.add :container_count, "cannot be updated directly."
217 self.container_count += 1
218 if self.container_uuid_was
219 old_container = Container.find_by_uuid(self.container_uuid_was)
220 old_logs = Collection.where(portable_data_hash: old_container.log).first
222 log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
223 if self.log_uuid.nil?
224 log_coll = Collection.new(
225 owner_uuid: self.owner_uuid,
226 name: coll_name = "Container log for request #{uuid}",
230 # copy logs from old container into CR's log collection
231 src = Arv::Collection.new(old_logs.manifest_text)
232 dst = Arv::Collection.new(log_coll.manifest_text)
233 dst.cp_r("./", "log for container #{old_container.uuid}", src)
234 manifest = dst.manifest_text
236 log_coll.assign_attributes(
237 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
238 manifest_text: manifest)
239 log_coll.save_with_unique_name!
240 self.log_uuid = log_coll.uuid
247 def set_default_preemptible_scheduling_parameter
248 c = get_requesting_container()
249 if self.state == Committed
250 # If preemptible instances (eg: AWS Spot Instances) are allowed,
251 # ask them on child containers by default.
252 if Rails.configuration.preemptible_instances and !c.nil? and
253 self.scheduling_parameters['preemptible'].nil?
254 self.scheduling_parameters['preemptible'] = true
259 def validate_runtime_constraints
264 ['keep_cache_ram', false]].each do |k, required|
265 if !required && !runtime_constraints.include?(k)
268 v = runtime_constraints[k]
269 unless (v.is_a?(Integer) && v > 0)
270 errors.add(:runtime_constraints,
271 "[#{k}]=#{v.inspect} must be a positive integer")
277 def validate_datatypes
280 errors.add(:command, "must be an array of strings but has entry #{c.class}")
283 environment.each do |k,v|
284 if !k.is_a?(String) || !v.is_a?(String)
285 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
288 [:mounts, :secret_mounts].each do |m|
289 self[m].each do |k, v|
290 if !k.is_a?(String) || !v.is_a?(Hash)
291 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
294 errors.add(m, "each item must have a 'kind' field")
296 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
297 "path", "commit", "repository_name", "git_url"]],
298 [Integer, ["capacity"]]].each do |t, fields|
300 if !v[f].nil? && !v[f].is_a?(t)
301 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
305 ["writable", "exclude_from_output"].each do |f|
306 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
307 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
314 def validate_scheduling_parameters
315 if self.state == Committed
316 if scheduling_parameters.include? 'partitions' and
317 (!scheduling_parameters['partitions'].is_a?(Array) ||
318 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
319 scheduling_parameters['partitions'].size)
320 errors.add :scheduling_parameters, "partitions must be an array of strings"
322 if !Rails.configuration.preemptible_instances and scheduling_parameters['preemptible']
323 errors.add :scheduling_parameters, "preemptible instances are not allowed"
325 if scheduling_parameters.include? 'max_run_time' and
326 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
327 scheduling_parameters['max_run_time'] < 0)
328 errors.add :scheduling_parameters, "max_run_time must be positive integer"
333 def check_update_whitelist
334 permitted = AttrsPermittedAlways.dup
336 if self.new_record? || self.state_was == Uncommitted
337 # Allow create-and-commit in a single operation.
338 permitted.push(*AttrsPermittedBeforeCommit)
343 permitted.push :priority, :container_count_max, :container_uuid
345 if self.container_uuid.nil?
346 self.errors.add :container_uuid, "has not been resolved to a container."
349 if self.priority.nil?
350 self.errors.add :priority, "cannot be nil"
353 # Allow container count to increment by 1
354 if (self.container_uuid &&
355 self.container_uuid != self.container_uuid_was &&
356 self.container_count == 1 + (self.container_count_was || 0))
357 permitted.push :container_count
360 if current_user.andand.is_admin
361 permitted.push :log_uuid
365 if self.state_was == Committed
366 # "Cancel" means setting priority=0, state=Committed
367 permitted.push :priority
369 if current_user.andand.is_admin
370 permitted.push :output_uuid, :log_uuid
379 def secret_mounts_key_conflict
380 secret_mounts.each do |k, v|
381 if mounts.has_key?(k)
382 errors.add(:secret_mounts, 'conflict with non-secret mounts')
388 def validate_runtime_token
389 if !self.runtime_token.nil? && self.runtime_token_changed?
390 if !runtime_token[0..2] == "v2/"
391 errors.add :runtime_token, "not a v2 token"
394 if ApiClientAuthorization.validate(token: runtime_token).nil?
395 errors.add :runtime_token, "failed validation"
401 if self.state == Final
402 self.secret_mounts = {}
403 self.runtime_token = nil
408 return unless state_changed? || priority_changed? || container_uuid_changed?
409 act_as_system_user do
411 where('uuid in (?)', [self.container_uuid_was, self.container_uuid].compact).
412 map(&:update_priority!)
416 def set_priority_zero
417 self.update_attributes!(priority: 0) if self.state != Final
420 def set_requesting_container_uuid
421 c = get_requesting_container()
423 self.requesting_container_uuid = c.uuid
424 # Determine the priority of container request for the requesting
426 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
430 def get_requesting_container
431 return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
432 Container.for_current_token