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 }
27 attribute :output_properties, :jsonbHash, default: {}
29 serialize :environment, Hash
30 serialize :mounts, Hash
31 serialize :runtime_constraints, Hash
32 serialize :command, Array
33 serialize :scheduling_parameters, Hash
35 after_find :fill_container_defaults_after_find
36 after_initialize { @state_was_when_initialized = self.state_was } # see finalize_if_needed
37 before_validation :fill_field_defaults, :if => :new_record?
38 before_validation :fill_container_defaults
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 after_validation :scrub_secrets
50 after_validation :set_preemptible
51 after_validation :set_container
52 before_create :set_requesting_container_uuid
53 before_destroy :set_priority_zero
54 after_save :update_priority
55 after_save :finalize_if_needed
57 api_accessible :user, extend: :common do |t|
59 t.add :container_count
60 t.add :container_count_max
61 t.add :container_image
77 t.add :requesting_container_uuid
78 t.add :runtime_constraints
79 t.add :scheduling_parameters
82 t.add :output_storage_classes
83 t.add :output_properties
84 t.add :cumulative_cost
87 # Supported states for a container request
90 (Uncommitted = 'Uncommitted'),
91 (Committed = 'Committed'),
96 nil => [Uncommitted, Committed],
97 Uncommitted => [Committed],
101 AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
102 AttrsPermittedBeforeCommit = [:command, :container_count_max,
103 :container_image, :cwd, :environment, :filters, :mounts,
104 :output_path, :priority, :runtime_token,
105 :runtime_constraints, :state, :container_uuid, :use_existing,
106 :scheduling_parameters, :secret_mounts, :output_name, :output_ttl,
107 :output_storage_classes, :output_properties]
109 def self.any_preemptible_instances?
110 Rails.configuration.InstanceTypes.any? do |k, v|
115 def self.limit_index_columns_read
119 def logged_attributes
120 super.except('secret_mounts', 'runtime_token')
123 def state_transitions
127 def skip_uuid_read_permission_check
128 # The uuid_read_permission_check prevents users from making
129 # references to objects they can't view. However, in this case we
130 # don't want to do that check since there's a circular dependency
131 # where user can't view the container until the user has
132 # constructed the container request that references the container.
136 def finalize_if_needed
137 return if state != Committed
139 # get container lock first, then lock current container request
140 # (same order as Container#handle_completed). Locking always
141 # reloads the Container and ContainerRequest records.
142 c = Container.find_by_uuid(container_uuid)
146 if !c.nil? && container_uuid != c.uuid
147 # After locking, we've noticed a race, the container_uuid is
148 # different than the container record we just loaded. This
149 # can happen if Container#handle_completed scheduled a new
150 # container for retry and set container_uuid while we were
151 # waiting on the container lock. Restart the loop and get the
157 if state == Committed && c.final?
158 # The current container is
159 act_as_system_user do
160 leave_modified_by_user_alone do
165 elsif state == Committed
166 # Behave as if the container is cancelled
167 update_attributes!(state: Final)
173 # Finalize the container request after the container has
174 # finished/cancelled.
176 container = Container.find_by_uuid(container_uuid)
178 # We don't want to add the container cost if the container was
179 # already finished when this CR was committed. But we are
180 # running in an after_save hook after a lock/reload, so
181 # state_was has already been updated to Committed regardless.
182 # Hence the need for @state_was_when_initialized.
183 if @state_was_when_initialized == Committed
184 # Add the final container cost to our cumulative cost (which
185 # may already be non-zero from previous attempts if
186 # container_count_max > 1).
187 self.cumulative_cost += container.cost + container.subrequests_cost
190 # Add our cumulative cost to the subrequests_cost of the
191 # requesting container, if any.
192 if self.requesting_container_uuid
194 uuid: self.requesting_container_uuid,
195 state: Container::Running,
197 c.subrequests_cost += self.cumulative_cost
202 update_collections(container: container)
203 # update_collections makes a log collection that includes all of the logs
204 # for all of the containers associated with this request. For requests
205 # that are retried, this is the primary way users can get logs for
207 # The code below makes a log collection that is a verbatim copy of the
208 # container's logs. This is required for container reuse: a container
209 # will not be reused if the owner cannot read a collection with its logs.
210 # See the "readable log" section of Container.find_reusable().
211 if container.state == Container::Complete
212 log_col = Collection.where(portable_data_hash: container.log).first
214 # Need to save collection
215 completed_coll = Collection.new(
216 owner_uuid: self.owner_uuid,
217 name: "Container log for container #{container_uuid}",
220 'container_request' => self.uuid,
221 'container_uuid' => container_uuid,
223 portable_data_hash: log_col.portable_data_hash,
224 manifest_text: log_col.manifest_text,
225 storage_classes_desired: self.output_storage_classes
227 completed_coll.save_with_unique_name!
231 update_attributes!(state: Final)
234 def update_collections(container:, collections: ['log', 'output'])
235 collections.each do |out_type|
236 pdh = container.send(out_type)
238 c = Collection.where(portable_data_hash: pdh).first
240 manifest = c.manifest_text
242 coll_name = "Container #{out_type} for request #{uuid}"
244 if out_type == 'output'
245 if self.output_name and self.output_name != ""
246 coll_name = self.output_name
248 if self.output_ttl > 0
249 trash_at = db_current_time + self.output_ttl
253 coll_uuid = self.send(out_type + '_uuid')
254 coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
256 coll = Collection.new(
257 owner_uuid: self.owner_uuid,
260 storage_classes_desired: self.output_storage_classes)
264 # Copy the log into a merged collection
265 src = Arv::Collection.new(manifest)
266 dst = Arv::Collection.new(coll.manifest_text)
267 dst.cp_r("./", ".", src)
268 dst.cp_r("./", "log for container #{container.uuid}", src)
269 manifest = dst.manifest_text
272 merged_properties = {}
273 merged_properties['container_request'] = uuid
275 if out_type == 'output' and !requesting_container_uuid.nil?
276 # output of a child process, give it "intermediate" type by
278 merged_properties['type'] = 'intermediate'
280 merged_properties['type'] = out_type
283 if out_type == "output"
284 merged_properties.update(container.output_properties)
285 merged_properties.update(self.output_properties)
288 coll.assign_attributes(
289 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
290 manifest_text: manifest,
293 properties: merged_properties)
294 coll.save_with_unique_name!
295 self.send(out_type + '_uuid=', coll.uuid)
299 def self.full_text_searchable_columns
300 super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token", "output_storage_classes"]
303 def set_priority_zero
304 self.update_attributes!(priority: 0) if self.priority > 0 && self.state != Final
309 def fill_field_defaults
310 self.state ||= Uncommitted
311 self.environment ||= {}
312 self.runtime_constraints ||= {}
314 self.secret_mounts ||= {}
316 self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
317 self.scheduling_parameters ||= {}
318 self.output_ttl ||= 0
323 if (container_uuid_changed? and
324 not current_user.andand.is_admin and
325 not container_uuid.nil?)
326 errors.add :container_uuid, "can only be updated to nil."
329 if self.container_count_changed?
330 errors.add :container_count, "cannot be updated directly."
333 if state_changed? and state == Committed and container_uuid.nil?
334 if self.command.length > 0 and self.command[0] == "arvados-cwl-runner"
335 # Special case, arvados-cwl-runner processes are always considered "supervisors"
336 self.scheduling_parameters['supervisor'] = true
339 c = Container.resolve(self)
341 if c.state == Container::Cancelled
342 # Lost a race, we have a lock on the container but the
343 # container was cancelled in a different request, restart
344 # the loop and resolve request to a new container.
347 self.container_uuid = c.uuid
351 if self.container_uuid != self.container_uuid_was
352 self.container_count += 1
353 return if self.container_uuid_was.nil?
355 old_container_uuid = self.container_uuid_was
356 old_container_log = Container.where(uuid: old_container_uuid).pluck(:log).first
357 return if old_container_log.nil?
359 old_logs = Collection.where(portable_data_hash: old_container_log).first
360 return if old_logs.nil?
362 log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
363 if self.log_uuid.nil?
364 log_coll = Collection.new(
365 owner_uuid: self.owner_uuid,
366 name: coll_name = "Container log for request #{uuid}",
368 storage_classes_desired: self.output_storage_classes)
371 # copy logs from old container into CR's log collection
372 src = Arv::Collection.new(old_logs.manifest_text)
373 dst = Arv::Collection.new(log_coll.manifest_text)
374 dst.cp_r("./", "log for container #{old_container_uuid}", src)
375 manifest = dst.manifest_text
377 log_coll.assign_attributes(
378 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
379 manifest_text: manifest)
380 log_coll.save_with_unique_name!
381 self.log_uuid = log_coll.uuid
386 if (new_record? || state_changed?) &&
387 state == Committed &&
388 Rails.configuration.Containers.AlwaysUsePreemptibleInstances &&
389 get_requesting_container_uuid() &&
390 self.class.any_preemptible_instances?
391 self.scheduling_parameters['preemptible'] = true
395 def validate_runtime_constraints
398 ['vcpus', 'ram'].each do |k|
399 v = runtime_constraints[k]
400 if !v.is_a?(Integer) || v <= 0
401 errors.add(:runtime_constraints,
402 "[#{k}]=#{v.inspect} must be a positive integer")
405 if runtime_constraints['cuda']
406 ['device_count'].each do |k|
407 v = runtime_constraints['cuda'][k]
408 if !v.is_a?(Integer) || v < 0
409 errors.add(:runtime_constraints,
410 "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
413 ['driver_version', 'hardware_capability'].each do |k|
414 v = runtime_constraints['cuda'][k]
415 if !v.is_a?(String) || (runtime_constraints['cuda']['device_count'] > 0 && v.to_f == 0.0)
416 errors.add(:runtime_constraints,
417 "[cuda.#{k}]=#{v.inspect} must be a string in format 'X.Y'")
424 def validate_datatypes
427 errors.add(:command, "must be an array of strings but has entry #{c.class}")
430 environment.each do |k,v|
431 if !k.is_a?(String) || !v.is_a?(String)
432 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
435 [:mounts, :secret_mounts].each do |m|
436 self[m].each do |k, v|
437 if !k.is_a?(String) || !v.is_a?(Hash)
438 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
441 errors.add(m, "each item must have a 'kind' field")
443 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
444 "path", "commit", "repository_name", "git_url"]],
445 [Integer, ["capacity"]]].each do |t, fields|
447 if !v[f].nil? && !v[f].is_a?(t)
448 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
452 ["writable", "exclude_from_output"].each do |f|
453 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
454 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
461 def validate_scheduling_parameters
462 if self.state == Committed
463 if scheduling_parameters.include? 'partitions' and
464 (!scheduling_parameters['partitions'].is_a?(Array) ||
465 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
466 scheduling_parameters['partitions'].size)
467 errors.add :scheduling_parameters, "partitions must be an array of strings"
469 if scheduling_parameters['preemptible'] &&
470 (new_record? || state_changed?) &&
471 !self.class.any_preemptible_instances?
472 errors.add :scheduling_parameters, "preemptible instances are not configured in InstanceTypes"
474 if scheduling_parameters.include? 'max_run_time' and
475 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
476 scheduling_parameters['max_run_time'] < 0)
477 errors.add :scheduling_parameters, "max_run_time must be positive integer"
482 def check_update_whitelist
483 permitted = AttrsPermittedAlways.dup
485 if self.new_record? || self.state_was == Uncommitted
486 # Allow create-and-commit in a single operation.
487 permitted.push(*AttrsPermittedBeforeCommit)
488 elsif mounts_changed? && mounts_was.keys.sort == mounts.keys.sort
489 # Ignore the updated mounts if the only changes are default/zero
490 # values as added by controller, see 17774
492 mounts.each do |path, mount|
493 (mount.to_a - mounts_was[path].to_a).each do |k, v|
494 if ![0, "", false, nil].index(v)
495 only_defaults = false
500 clear_attribute_change("mounts")
506 permitted.push :priority, :container_count_max, :container_uuid, :cumulative_cost
508 if self.priority.nil?
509 self.errors.add :priority, "cannot be nil"
512 # Allow container count to increment (not by client, only by us
513 # -- see set_container)
514 permitted.push :container_count
516 if current_user.andand.is_admin
517 permitted.push :log_uuid
521 if self.state_was == Committed
522 # "Cancel" means setting priority=0, state=Committed
523 permitted.push :priority, :cumulative_cost
525 if current_user.andand.is_admin
526 permitted.push :output_uuid, :log_uuid
535 def secret_mounts_key_conflict
536 secret_mounts.each do |k, v|
537 if mounts.has_key?(k)
538 errors.add(:secret_mounts, 'conflict with non-secret mounts')
544 def validate_runtime_token
545 if !self.runtime_token.nil? && self.runtime_token_changed?
546 if !runtime_token[0..2] == "v2/"
547 errors.add :runtime_token, "not a v2 token"
550 if ApiClientAuthorization.validate(token: runtime_token).nil?
551 errors.add :runtime_token, "failed validation"
557 if self.state == Final
558 self.secret_mounts = {}
559 self.runtime_token = nil
564 return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
565 act_as_system_user do
567 where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
568 map(&:update_priority!)
572 def set_requesting_container_uuid
573 if (self.requesting_container_uuid = get_requesting_container_uuid())
574 # Determine the priority of container request for the requesting
576 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
580 def get_requesting_container_uuid
581 return self.requesting_container_uuid || Container.for_current_token.andand.uuid