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")
339 if runtime_constraints['cuda']
340 ['device_count'].each do |k|
341 v = runtime_constraints['cuda'][k]
342 if !v.is_a?(Integer) || v < 0
343 errors.add(:runtime_constraints,
344 "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
347 ['driver_version', 'hardware_capability'].each do |k|
348 v = runtime_constraints['cuda'][k]
350 errors.add(:runtime_constraints,
351 "[cuda.#{k}]=#{v.inspect} must be a string")
358 def validate_datatypes
361 errors.add(:command, "must be an array of strings but has entry #{c.class}")
364 environment.each do |k,v|
365 if !k.is_a?(String) || !v.is_a?(String)
366 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
369 [:mounts, :secret_mounts].each do |m|
370 self[m].each do |k, v|
371 if !k.is_a?(String) || !v.is_a?(Hash)
372 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
375 errors.add(m, "each item must have a 'kind' field")
377 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
378 "path", "commit", "repository_name", "git_url"]],
379 [Integer, ["capacity"]]].each do |t, fields|
381 if !v[f].nil? && !v[f].is_a?(t)
382 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
386 ["writable", "exclude_from_output"].each do |f|
387 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
388 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
395 def validate_scheduling_parameters
396 if self.state == Committed
397 if scheduling_parameters.include? 'partitions' and
398 (!scheduling_parameters['partitions'].is_a?(Array) ||
399 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
400 scheduling_parameters['partitions'].size)
401 errors.add :scheduling_parameters, "partitions must be an array of strings"
403 if !Rails.configuration.Containers.UsePreemptibleInstances and scheduling_parameters['preemptible']
404 errors.add :scheduling_parameters, "preemptible instances are not allowed"
406 if scheduling_parameters.include? 'max_run_time' and
407 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
408 scheduling_parameters['max_run_time'] < 0)
409 errors.add :scheduling_parameters, "max_run_time must be positive integer"
414 def check_update_whitelist
415 permitted = AttrsPermittedAlways.dup
417 if self.new_record? || self.state_was == Uncommitted
418 # Allow create-and-commit in a single operation.
419 permitted.push(*AttrsPermittedBeforeCommit)
420 elsif mounts_changed? && mounts_was.keys == mounts.keys
421 # Ignore the updated mounts if the only changes are default/zero
422 # values as added by controller, see 17774
424 mounts.each do |path, mount|
425 (mount.to_a - mounts_was[path].to_a).each do |k, v|
426 if !["", false, nil].index(v)
427 only_defaults = false
432 clear_attribute_change("mounts")
438 permitted.push :priority, :container_count_max, :container_uuid
440 if self.container_uuid.nil?
441 self.errors.add :container_uuid, "has not been resolved to a container."
444 if self.priority.nil?
445 self.errors.add :priority, "cannot be nil"
448 # Allow container count to increment by 1
449 if (self.container_uuid &&
450 self.container_uuid != self.container_uuid_was &&
451 self.container_count == 1 + (self.container_count_was || 0))
452 permitted.push :container_count
455 if current_user.andand.is_admin
456 permitted.push :log_uuid
460 if self.state_was == Committed
461 # "Cancel" means setting priority=0, state=Committed
462 permitted.push :priority
464 if current_user.andand.is_admin
465 permitted.push :output_uuid, :log_uuid
474 def secret_mounts_key_conflict
475 secret_mounts.each do |k, v|
476 if mounts.has_key?(k)
477 errors.add(:secret_mounts, 'conflict with non-secret mounts')
483 def validate_runtime_token
484 if !self.runtime_token.nil? && self.runtime_token_changed?
485 if !runtime_token[0..2] == "v2/"
486 errors.add :runtime_token, "not a v2 token"
489 if ApiClientAuthorization.validate(token: runtime_token).nil?
490 errors.add :runtime_token, "failed validation"
496 if self.state == Final
497 self.secret_mounts = {}
498 self.runtime_token = nil
503 return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
504 act_as_system_user do
506 where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
507 map(&:update_priority!)
511 def set_priority_zero
512 self.update_attributes!(priority: 0) if self.state != Final
515 def set_requesting_container_uuid
516 c = get_requesting_container()
518 self.requesting_container_uuid = c.uuid
519 # Determine the priority of container request for the requesting
521 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
525 def get_requesting_container
526 return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
527 Container.for_current_token