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 attribute :properties, :jsonbHash, default: {}
25 attribute :secret_mounts, :jsonbHash, default: {}
26 attribute :output_storage_classes, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
28 serialize :environment, Hash
29 serialize :mounts, Hash
30 serialize :runtime_constraints, Hash
31 serialize :command, Array
32 serialize :scheduling_parameters, Hash
34 after_find :fill_container_defaults_after_find
35 before_validation :fill_field_defaults, :if => :new_record?
36 before_validation :fill_container_defaults
37 before_validation :set_default_preemptible_scheduling_parameter
38 before_validation :set_container
39 validates :command, :container_image, :output_path, :cwd, :presence => true
40 validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
41 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
42 validate :validate_datatypes
43 validate :validate_runtime_constraints
44 validate :validate_scheduling_parameters
45 validate :validate_state_change
46 validate :check_update_whitelist
47 validate :secret_mounts_key_conflict
48 validate :validate_runtime_token
49 before_save :scrub_secrets
50 before_create :set_requesting_container_uuid
51 before_destroy :set_priority_zero
52 after_save :update_priority
53 after_save :finalize_if_needed
55 api_accessible :user, extend: :common do |t|
57 t.add :container_count
58 t.add :container_count_max
59 t.add :container_image
75 t.add :requesting_container_uuid
76 t.add :runtime_constraints
77 t.add :scheduling_parameters
80 t.add :output_storage_classes
83 # Supported states for a container request
86 (Uncommitted = 'Uncommitted'),
87 (Committed = 'Committed'),
92 nil => [Uncommitted, Committed],
93 Uncommitted => [Committed],
97 AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
98 AttrsPermittedBeforeCommit = [:command, :container_count_max,
99 :container_image, :cwd, :environment, :filters, :mounts,
100 :output_path, :priority, :runtime_token,
101 :runtime_constraints, :state, :container_uuid, :use_existing,
102 :scheduling_parameters, :secret_mounts, :output_name, :output_ttl,
103 :output_storage_classes]
105 def self.limit_index_columns_read
109 def logged_attributes
110 super.except('secret_mounts', 'runtime_token')
113 def state_transitions
117 def skip_uuid_read_permission_check
118 # The uuid_read_permission_check prevents users from making
119 # references to objects they can't view. However, in this case we
120 # don't want to do that check since there's a circular dependency
121 # where user can't view the container until the user has
122 # constructed the container request that references the container.
126 def finalize_if_needed
127 return if state != Committed
129 # get container lock first, then lock current container request
130 # (same order as Container#handle_completed). Locking always
131 # reloads the Container and ContainerRequest records.
132 c = Container.find_by_uuid(container_uuid)
136 if !c.nil? && container_uuid != c.uuid
137 # After locking, we've noticed a race, the container_uuid is
138 # different than the container record we just loaded. This
139 # can happen if Container#handle_completed scheduled a new
140 # container for retry and set container_uuid while we were
141 # waiting on the container lock. Restart the loop and get the
147 if state == Committed && c.final?
148 # The current container is
149 act_as_system_user do
150 leave_modified_by_user_alone do
155 elsif state == Committed
156 # Behave as if the container is cancelled
157 update_attributes!(state: Final)
163 # Finalize the container request after the container has
164 # finished/cancelled.
166 container = Container.find_by_uuid(container_uuid)
168 update_collections(container: container)
170 if container.state == Container::Complete
171 log_col = Collection.where(portable_data_hash: container.log).first
173 # Need to save collection
174 completed_coll = Collection.new(
175 owner_uuid: self.owner_uuid,
176 name: "Container log for container #{container_uuid}",
179 'container_request' => self.uuid,
180 'container_uuid' => container_uuid,
182 portable_data_hash: log_col.portable_data_hash,
183 manifest_text: log_col.manifest_text,
184 storage_classes_desired: self.output_storage_classes
186 completed_coll.save_with_unique_name!
190 update_attributes!(state: Final)
193 def update_collections(container:, collections: ['log', 'output'])
194 collections.each do |out_type|
195 pdh = container.send(out_type)
197 c = Collection.where(portable_data_hash: pdh).first
199 manifest = c.manifest_text
201 coll_name = "Container #{out_type} for request #{uuid}"
203 if out_type == 'output'
204 if self.output_name and self.output_name != ""
205 coll_name = self.output_name
207 if self.output_ttl > 0
208 trash_at = db_current_time + self.output_ttl
212 coll_uuid = self.send(out_type + '_uuid')
213 coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
215 coll = Collection.new(
216 owner_uuid: self.owner_uuid,
219 storage_classes_desired: self.output_storage_classes,
222 'container_request' => uuid,
227 # Copy the log into a merged collection
228 src = Arv::Collection.new(manifest)
229 dst = Arv::Collection.new(coll.manifest_text)
230 dst.cp_r("./", ".", src)
231 dst.cp_r("./", "log for container #{container.uuid}", src)
232 manifest = dst.manifest_text
235 coll.assign_attributes(
236 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
237 manifest_text: manifest,
240 coll.save_with_unique_name!
241 self.send(out_type + '_uuid=', coll.uuid)
245 def self.full_text_searchable_columns
246 super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token", "output_storage_classes"]
251 def fill_field_defaults
252 self.state ||= Uncommitted
253 self.environment ||= {}
254 self.runtime_constraints ||= {}
256 self.secret_mounts ||= {}
258 self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
259 self.scheduling_parameters ||= {}
260 self.output_ttl ||= 0
265 if (container_uuid_changed? and
266 not current_user.andand.is_admin and
267 not container_uuid.nil?)
268 errors.add :container_uuid, "can only be updated to nil."
271 if state_changed? and state == Committed and container_uuid.nil?
273 c = Container.resolve(self)
275 if c.state == Container::Cancelled
276 # Lost a race, we have a lock on the container but the
277 # container was cancelled in a different request, restart
278 # the loop and resolve request to a new container.
281 self.container_uuid = c.uuid
285 if self.container_uuid != self.container_uuid_was
286 if self.container_count_changed?
287 errors.add :container_count, "cannot be updated directly."
291 self.container_count += 1
292 return if self.container_uuid_was.nil?
294 old_container = Container.find_by_uuid(self.container_uuid_was)
295 return if old_container.nil?
297 old_logs = Collection.where(portable_data_hash: old_container.log).first
298 return if old_logs.nil?
300 log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
301 if self.log_uuid.nil?
302 log_coll = Collection.new(
303 owner_uuid: self.owner_uuid,
304 name: coll_name = "Container log for request #{uuid}",
306 storage_classes_desired: self.output_storage_classes)
309 # copy logs from old container into CR's log collection
310 src = Arv::Collection.new(old_logs.manifest_text)
311 dst = Arv::Collection.new(log_coll.manifest_text)
312 dst.cp_r("./", "log for container #{old_container.uuid}", src)
313 manifest = dst.manifest_text
315 log_coll.assign_attributes(
316 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
317 manifest_text: manifest)
318 log_coll.save_with_unique_name!
319 self.log_uuid = log_coll.uuid
323 def set_default_preemptible_scheduling_parameter
324 if Rails.configuration.Containers.UsePreemptibleInstances && state == Committed && get_requesting_container()
325 self.scheduling_parameters['preemptible'] = true
329 def validate_runtime_constraints
332 ['vcpus', 'ram'].each do |k|
333 v = runtime_constraints[k]
334 if !v.is_a?(Integer) || v <= 0
335 errors.add(:runtime_constraints,
336 "[#{k}]=#{v.inspect} must be a positive integer")
342 def validate_datatypes
345 errors.add(:command, "must be an array of strings but has entry #{c.class}")
348 environment.each do |k,v|
349 if !k.is_a?(String) || !v.is_a?(String)
350 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
353 [:mounts, :secret_mounts].each do |m|
354 self[m].each do |k, v|
355 if !k.is_a?(String) || !v.is_a?(Hash)
356 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
359 errors.add(m, "each item must have a 'kind' field")
361 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
362 "path", "commit", "repository_name", "git_url"]],
363 [Integer, ["capacity"]]].each do |t, fields|
365 if !v[f].nil? && !v[f].is_a?(t)
366 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
370 ["writable", "exclude_from_output"].each do |f|
371 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
372 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
379 def validate_scheduling_parameters
380 if self.state == Committed
381 if scheduling_parameters.include? 'partitions' and
382 (!scheduling_parameters['partitions'].is_a?(Array) ||
383 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
384 scheduling_parameters['partitions'].size)
385 errors.add :scheduling_parameters, "partitions must be an array of strings"
387 if !Rails.configuration.Containers.UsePreemptibleInstances and scheduling_parameters['preemptible']
388 errors.add :scheduling_parameters, "preemptible instances are not allowed"
390 if scheduling_parameters.include? 'max_run_time' and
391 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
392 scheduling_parameters['max_run_time'] < 0)
393 errors.add :scheduling_parameters, "max_run_time must be positive integer"
398 def check_update_whitelist
399 permitted = AttrsPermittedAlways.dup
401 if self.new_record? || self.state_was == Uncommitted
402 # Allow create-and-commit in a single operation.
403 permitted.push(*AttrsPermittedBeforeCommit)
404 elsif mounts_changed? && mounts_was.keys == mounts.keys
405 # Ignore the updated mounts if the only changes are default/zero
406 # values as added by controller, see 17774
408 mounts.each do |path, mount|
409 (mount.to_a - mounts_was[path].to_a).each do |k, v|
410 if !["", false, nil].index(v)
411 only_defaults = false
416 clear_attribute_change("mounts")
422 permitted.push :priority, :container_count_max, :container_uuid
424 if self.container_uuid.nil?
425 self.errors.add :container_uuid, "has not been resolved to a container."
428 if self.priority.nil?
429 self.errors.add :priority, "cannot be nil"
432 # Allow container count to increment by 1
433 if (self.container_uuid &&
434 self.container_uuid != self.container_uuid_was &&
435 self.container_count == 1 + (self.container_count_was || 0))
436 permitted.push :container_count
439 if current_user.andand.is_admin
440 permitted.push :log_uuid
444 if self.state_was == Committed
445 # "Cancel" means setting priority=0, state=Committed
446 permitted.push :priority
448 if current_user.andand.is_admin
449 permitted.push :output_uuid, :log_uuid
458 def secret_mounts_key_conflict
459 secret_mounts.each do |k, v|
460 if mounts.has_key?(k)
461 errors.add(:secret_mounts, 'conflict with non-secret mounts')
467 def validate_runtime_token
468 if !self.runtime_token.nil? && self.runtime_token_changed?
469 if !runtime_token[0..2] == "v2/"
470 errors.add :runtime_token, "not a v2 token"
473 if ApiClientAuthorization.validate(token: runtime_token).nil?
474 errors.add :runtime_token, "failed validation"
480 if self.state == Final
481 self.secret_mounts = {}
482 self.runtime_token = nil
487 return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
488 act_as_system_user do
490 where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
491 map(&:update_priority!)
495 def set_priority_zero
496 self.update_attributes!(priority: 0) if self.state != Final
499 def set_requesting_container_uuid
500 c = get_requesting_container()
502 self.requesting_container_uuid = c.uuid
503 # Determine the priority of container request for the requesting
505 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
509 def get_requesting_container
510 return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
511 Container.for_current_token