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 before_validation :fill_field_defaults, :if => :new_record?
37 before_validation :fill_container_defaults
38 validates :command, :container_image, :output_path, :cwd, :presence => true
39 validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
40 validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
41 validate :validate_datatypes
42 validate :validate_runtime_constraints
43 validate :validate_scheduling_parameters
44 validate :validate_state_change
45 validate :check_update_whitelist
46 validate :secret_mounts_key_conflict
47 validate :validate_runtime_token
48 after_validation :scrub_secrets
49 after_validation :set_preemptible
50 after_validation :set_container
51 before_create :set_requesting_container_uuid
52 before_destroy :set_priority_zero
53 after_save :update_priority
54 after_save :finalize_if_needed
56 api_accessible :user, extend: :common do |t|
58 t.add :container_count
59 t.add :container_count_max
60 t.add :container_image
76 t.add :requesting_container_uuid
77 t.add :runtime_constraints
78 t.add :scheduling_parameters
81 t.add :output_storage_classes
82 t.add :output_properties
85 # Supported states for a container request
88 (Uncommitted = 'Uncommitted'),
89 (Committed = 'Committed'),
94 nil => [Uncommitted, Committed],
95 Uncommitted => [Committed],
99 AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
100 AttrsPermittedBeforeCommit = [:command, :container_count_max,
101 :container_image, :cwd, :environment, :filters, :mounts,
102 :output_path, :priority, :runtime_token,
103 :runtime_constraints, :state, :container_uuid, :use_existing,
104 :scheduling_parameters, :secret_mounts, :output_name, :output_ttl,
105 :output_storage_classes, :output_properties]
107 def self.any_preemptible_instances?
108 Rails.configuration.InstanceTypes.any? do |k, v|
113 def self.limit_index_columns_read
117 def logged_attributes
118 super.except('secret_mounts', 'runtime_token')
121 def state_transitions
125 def skip_uuid_read_permission_check
126 # The uuid_read_permission_check prevents users from making
127 # references to objects they can't view. However, in this case we
128 # don't want to do that check since there's a circular dependency
129 # where user can't view the container until the user has
130 # constructed the container request that references the container.
134 def finalize_if_needed
135 return if state != Committed
137 # get container lock first, then lock current container request
138 # (same order as Container#handle_completed). Locking always
139 # reloads the Container and ContainerRequest records.
140 c = Container.find_by_uuid(container_uuid)
144 if !c.nil? && container_uuid != c.uuid
145 # After locking, we've noticed a race, the container_uuid is
146 # different than the container record we just loaded. This
147 # can happen if Container#handle_completed scheduled a new
148 # container for retry and set container_uuid while we were
149 # waiting on the container lock. Restart the loop and get the
155 if state == Committed && c.final?
156 # The current container is
157 act_as_system_user do
158 leave_modified_by_user_alone do
163 elsif state == Committed
164 # Behave as if the container is cancelled
165 update_attributes!(state: Final)
171 # Finalize the container request after the container has
172 # finished/cancelled.
174 container = Container.find_by_uuid(container_uuid)
176 update_collections(container: container)
178 if container.state == Container::Complete
179 log_col = Collection.where(portable_data_hash: container.log).first
181 # Need to save collection
182 completed_coll = Collection.new(
183 owner_uuid: self.owner_uuid,
184 name: "Container log for container #{container_uuid}",
187 'container_request' => self.uuid,
188 'container_uuid' => container_uuid,
190 portable_data_hash: log_col.portable_data_hash,
191 manifest_text: log_col.manifest_text,
192 storage_classes_desired: self.output_storage_classes
194 completed_coll.save_with_unique_name!
198 update_attributes!(state: Final)
201 def update_collections(container:, collections: ['log', 'output'])
202 collections.each do |out_type|
203 pdh = container.send(out_type)
205 c = Collection.where(portable_data_hash: pdh).first
207 manifest = c.manifest_text
209 coll_name = "Container #{out_type} for request #{uuid}"
211 if out_type == 'output'
212 if self.output_name and self.output_name != ""
213 coll_name = self.output_name
215 if self.output_ttl > 0
216 trash_at = db_current_time + self.output_ttl
220 coll_uuid = self.send(out_type + '_uuid')
221 coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
223 coll = Collection.new(
224 owner_uuid: self.owner_uuid,
227 storage_classes_desired: self.output_storage_classes)
231 # Copy the log into a merged collection
232 src = Arv::Collection.new(manifest)
233 dst = Arv::Collection.new(coll.manifest_text)
234 dst.cp_r("./", ".", src)
235 dst.cp_r("./", "log for container #{container.uuid}", src)
236 manifest = dst.manifest_text
239 merged_properties = {}
240 merged_properties['container_request'] = uuid
242 if out_type == 'output' and !requesting_container_uuid.nil?
243 # output of a child process, give it "intermediate" type by
245 merged_properties['type'] = 'intermediate'
247 merged_properties['type'] = out_type
250 if out_type == "output"
251 merged_properties.update(container.output_properties)
252 merged_properties.update(self.output_properties)
255 coll.assign_attributes(
256 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
257 manifest_text: manifest,
260 properties: merged_properties)
261 coll.save_with_unique_name!
262 self.send(out_type + '_uuid=', coll.uuid)
266 def self.full_text_searchable_columns
267 super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token", "output_storage_classes"]
272 def fill_field_defaults
273 self.state ||= Uncommitted
274 self.environment ||= {}
275 self.runtime_constraints ||= {}
277 self.secret_mounts ||= {}
279 self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
280 self.scheduling_parameters ||= {}
281 self.output_ttl ||= 0
286 if (container_uuid_changed? and
287 not current_user.andand.is_admin and
288 not container_uuid.nil?)
289 errors.add :container_uuid, "can only be updated to nil."
292 if self.container_count_changed?
293 errors.add :container_count, "cannot be updated directly."
296 if state_changed? and state == Committed and container_uuid.nil?
298 c = Container.resolve(self)
300 if c.state == Container::Cancelled
301 # Lost a race, we have a lock on the container but the
302 # container was cancelled in a different request, restart
303 # the loop and resolve request to a new container.
306 self.container_uuid = c.uuid
310 if self.container_uuid != self.container_uuid_was
311 self.container_count += 1
312 return if self.container_uuid_was.nil?
314 old_container = Container.find_by_uuid(self.container_uuid_was)
315 return if old_container.nil?
317 old_logs = Collection.where(portable_data_hash: old_container.log).first
318 return if old_logs.nil?
320 log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
321 if self.log_uuid.nil?
322 log_coll = Collection.new(
323 owner_uuid: self.owner_uuid,
324 name: coll_name = "Container log for request #{uuid}",
326 storage_classes_desired: self.output_storage_classes)
329 # copy logs from old container into CR's log collection
330 src = Arv::Collection.new(old_logs.manifest_text)
331 dst = Arv::Collection.new(log_coll.manifest_text)
332 dst.cp_r("./", "log for container #{old_container.uuid}", src)
333 manifest = dst.manifest_text
335 log_coll.assign_attributes(
336 portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
337 manifest_text: manifest)
338 log_coll.save_with_unique_name!
339 self.log_uuid = log_coll.uuid
344 if (new_record? || state_changed?) &&
345 state == Committed &&
346 Rails.configuration.Containers.AlwaysUsePreemptibleInstances &&
347 get_requesting_container_uuid() &&
348 self.class.any_preemptible_instances?
349 self.scheduling_parameters['preemptible'] = true
353 def validate_runtime_constraints
356 ['vcpus', 'ram'].each do |k|
357 v = runtime_constraints[k]
358 if !v.is_a?(Integer) || v <= 0
359 errors.add(:runtime_constraints,
360 "[#{k}]=#{v.inspect} must be a positive integer")
363 if runtime_constraints['cuda']
364 ['device_count'].each do |k|
365 v = runtime_constraints['cuda'][k]
366 if !v.is_a?(Integer) || v < 0
367 errors.add(:runtime_constraints,
368 "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
371 ['driver_version', 'hardware_capability'].each do |k|
372 v = runtime_constraints['cuda'][k]
373 if !v.is_a?(String) || (runtime_constraints['cuda']['device_count'] > 0 && v.to_f == 0.0)
374 errors.add(:runtime_constraints,
375 "[cuda.#{k}]=#{v.inspect} must be a string in format 'X.Y'")
382 def validate_datatypes
385 errors.add(:command, "must be an array of strings but has entry #{c.class}")
388 environment.each do |k,v|
389 if !k.is_a?(String) || !v.is_a?(String)
390 errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
393 [:mounts, :secret_mounts].each do |m|
394 self[m].each do |k, v|
395 if !k.is_a?(String) || !v.is_a?(Hash)
396 errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
399 errors.add(m, "each item must have a 'kind' field")
401 [[String, ["kind", "portable_data_hash", "uuid", "device_type",
402 "path", "commit", "repository_name", "git_url"]],
403 [Integer, ["capacity"]]].each do |t, fields|
405 if !v[f].nil? && !v[f].is_a?(t)
406 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
410 ["writable", "exclude_from_output"].each do |f|
411 if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
412 errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
419 def validate_scheduling_parameters
420 if self.state == Committed
421 if scheduling_parameters.include? 'partitions' and
422 (!scheduling_parameters['partitions'].is_a?(Array) ||
423 scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
424 scheduling_parameters['partitions'].size)
425 errors.add :scheduling_parameters, "partitions must be an array of strings"
427 if scheduling_parameters['preemptible'] &&
428 (new_record? || state_changed?) &&
429 !self.class.any_preemptible_instances?
430 errors.add :scheduling_parameters, "preemptible instances are not configured in InstanceTypes"
432 if scheduling_parameters.include? 'max_run_time' and
433 (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
434 scheduling_parameters['max_run_time'] < 0)
435 errors.add :scheduling_parameters, "max_run_time must be positive integer"
440 def check_update_whitelist
441 permitted = AttrsPermittedAlways.dup
443 if self.new_record? || self.state_was == Uncommitted
444 # Allow create-and-commit in a single operation.
445 permitted.push(*AttrsPermittedBeforeCommit)
446 elsif mounts_changed? && mounts_was.keys.sort == mounts.keys.sort
447 # Ignore the updated mounts if the only changes are default/zero
448 # values as added by controller, see 17774
450 mounts.each do |path, mount|
451 (mount.to_a - mounts_was[path].to_a).each do |k, v|
452 if ![0, "", false, nil].index(v)
453 only_defaults = false
458 clear_attribute_change("mounts")
464 permitted.push :priority, :container_count_max, :container_uuid
466 if self.priority.nil?
467 self.errors.add :priority, "cannot be nil"
470 # Allow container count to increment (not by client, only by us
471 # -- see set_container)
472 permitted.push :container_count
474 if current_user.andand.is_admin
475 permitted.push :log_uuid
479 if self.state_was == Committed
480 # "Cancel" means setting priority=0, state=Committed
481 permitted.push :priority
483 if current_user.andand.is_admin
484 permitted.push :output_uuid, :log_uuid
493 def secret_mounts_key_conflict
494 secret_mounts.each do |k, v|
495 if mounts.has_key?(k)
496 errors.add(:secret_mounts, 'conflict with non-secret mounts')
502 def validate_runtime_token
503 if !self.runtime_token.nil? && self.runtime_token_changed?
504 if !runtime_token[0..2] == "v2/"
505 errors.add :runtime_token, "not a v2 token"
508 if ApiClientAuthorization.validate(token: runtime_token).nil?
509 errors.add :runtime_token, "failed validation"
515 if self.state == Final
516 self.secret_mounts = {}
517 self.runtime_token = nil
522 return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
523 act_as_system_user do
525 where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
526 map(&:update_priority!)
530 def set_priority_zero
531 self.update_attributes!(priority: 0) if self.state != Final
534 def set_requesting_container_uuid
535 if (self.requesting_container_uuid = get_requesting_container_uuid())
536 # Determine the priority of container request for the requesting
538 self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
542 def get_requesting_container_uuid
543 return self.requesting_container_uuid || Container.for_current_token.andand.uuid