18205: Add container cost accounting fields.
[arvados.git] / services / api / app / models / container_request.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 require 'whitelist_update'
6 require 'arvados/collection'
7
8 class ContainerRequest < ArvadosModel
9   include ArvadosModelUpdates
10   include HasUuid
11   include KindAndEtag
12   include CommonApiTemplate
13   include WhitelistUpdate
14
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,
19                primary_key: :uuid,
20              }
21
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: {}
28
29   serialize :environment, Hash
30   serialize :mounts, Hash
31   serialize :runtime_constraints, Hash
32   serialize :command, Array
33   serialize :scheduling_parameters, Hash
34
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
56
57   api_accessible :user, extend: :common do |t|
58     t.add :command
59     t.add :container_count
60     t.add :container_count_max
61     t.add :container_image
62     t.add :container_uuid
63     t.add :cwd
64     t.add :description
65     t.add :environment
66     t.add :expires_at
67     t.add :filters
68     t.add :log_uuid
69     t.add :mounts
70     t.add :name
71     t.add :output_name
72     t.add :output_path
73     t.add :output_uuid
74     t.add :output_ttl
75     t.add :priority
76     t.add :properties
77     t.add :requesting_container_uuid
78     t.add :runtime_constraints
79     t.add :scheduling_parameters
80     t.add :state
81     t.add :use_existing
82     t.add :output_storage_classes
83     t.add :output_properties
84     t.add :cumulative_cost
85   end
86
87   # Supported states for a container request
88   States =
89     [
90      (Uncommitted = 'Uncommitted'),
91      (Committed = 'Committed'),
92      (Final = 'Final'),
93     ]
94
95   State_transitions = {
96     nil => [Uncommitted, Committed],
97     Uncommitted => [Committed],
98     Committed => [Final]
99   }
100
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]
108
109   def self.any_preemptible_instances?
110     Rails.configuration.InstanceTypes.any? do |k, v|
111       v["Preemptible"]
112     end
113   end
114
115   def self.limit_index_columns_read
116     ["mounts"]
117   end
118
119   def logged_attributes
120     super.except('secret_mounts', 'runtime_token')
121   end
122
123   def state_transitions
124     State_transitions
125   end
126
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.
133     %w(container_uuid)
134   end
135
136   def finalize_if_needed
137     return if state != Committed
138     while true
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)
143       c.lock! if !c.nil?
144       self.lock!
145
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
152         # new container.
153         redo
154       end
155
156       if !c.nil?
157         if state == Committed && c.final?
158           # The current container is
159           act_as_system_user do
160             leave_modified_by_user_alone do
161               finalize!
162             end
163           end
164         end
165       elsif state == Committed
166         # Behave as if the container is cancelled
167         update_attributes!(state: Final)
168       end
169       return true
170     end
171   end
172
173   # Finalize the container request after the container has
174   # finished/cancelled.
175   def finalize!
176     container = Container.find_by_uuid(container_uuid)
177     if !container.nil?
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
188       end
189
190       # Add our cumulative cost to the subrequests_cost of the
191       # requesting container, if any.
192       if self.requesting_container_uuid
193         Container.where(
194           uuid: self.requesting_container_uuid,
195           state: Container::Running,
196         ).each do |c|
197           c.subrequests_cost += self.cumulative_cost
198           c.save!
199         end
200       end
201
202       update_collections(container: container)
203
204       if container.state == Container::Complete
205         log_col = Collection.where(portable_data_hash: container.log).first
206         if log_col
207           # Need to save collection
208           completed_coll = Collection.new(
209             owner_uuid: self.owner_uuid,
210             name: "Container log for container #{container_uuid}",
211             properties: {
212               'type' => 'log',
213               'container_request' => self.uuid,
214               'container_uuid' => container_uuid,
215             },
216             portable_data_hash: log_col.portable_data_hash,
217             manifest_text: log_col.manifest_text,
218             storage_classes_desired: self.output_storage_classes
219           )
220           completed_coll.save_with_unique_name!
221         end
222       end
223     end
224     update_attributes!(state: Final)
225   end
226
227   def update_collections(container:, collections: ['log', 'output'])
228     collections.each do |out_type|
229       pdh = container.send(out_type)
230       next if pdh.nil?
231       c = Collection.where(portable_data_hash: pdh).first
232       next if c.nil?
233       manifest = c.manifest_text
234
235       coll_name = "Container #{out_type} for request #{uuid}"
236       trash_at = nil
237       if out_type == 'output'
238         if self.output_name and self.output_name != ""
239           coll_name = self.output_name
240         end
241         if self.output_ttl > 0
242           trash_at = db_current_time + self.output_ttl
243         end
244       end
245
246       coll_uuid = self.send(out_type + '_uuid')
247       coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
248       if !coll
249         coll = Collection.new(
250           owner_uuid: self.owner_uuid,
251           name: coll_name,
252           manifest_text: "",
253           storage_classes_desired: self.output_storage_classes)
254       end
255
256       if out_type == "log"
257         # Copy the log into a merged collection
258         src = Arv::Collection.new(manifest)
259         dst = Arv::Collection.new(coll.manifest_text)
260         dst.cp_r("./", ".", src)
261         dst.cp_r("./", "log for container #{container.uuid}", src)
262         manifest = dst.manifest_text
263       end
264
265       merged_properties = {}
266       merged_properties['container_request'] = uuid
267
268       if out_type == 'output' and !requesting_container_uuid.nil?
269         # output of a child process, give it "intermediate" type by
270         # default.
271         merged_properties['type'] = 'intermediate'
272       else
273         merged_properties['type'] = out_type
274       end
275
276       if out_type == "output"
277         merged_properties.update(container.output_properties)
278         merged_properties.update(self.output_properties)
279       end
280
281       coll.assign_attributes(
282         portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
283         manifest_text: manifest,
284         trash_at: trash_at,
285         delete_at: trash_at,
286         properties: merged_properties)
287       coll.save_with_unique_name!
288       self.send(out_type + '_uuid=', coll.uuid)
289     end
290   end
291
292   def self.full_text_searchable_columns
293     super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token", "output_storage_classes"]
294   end
295
296   protected
297
298   def fill_field_defaults
299     self.state ||= Uncommitted
300     self.environment ||= {}
301     self.runtime_constraints ||= {}
302     self.mounts ||= {}
303     self.secret_mounts ||= {}
304     self.cwd ||= "."
305     self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
306     self.scheduling_parameters ||= {}
307     self.output_ttl ||= 0
308     self.priority ||= 0
309   end
310
311   def set_container
312     if (container_uuid_changed? and
313         not current_user.andand.is_admin and
314         not container_uuid.nil?)
315       errors.add :container_uuid, "can only be updated to nil."
316       return false
317     end
318     if self.container_count_changed?
319       errors.add :container_count, "cannot be updated directly."
320       return false
321     end
322     if state_changed? and state == Committed and container_uuid.nil?
323       while true
324         c = Container.resolve(self)
325         c.lock!
326         if c.state == Container::Cancelled
327           # Lost a race, we have a lock on the container but the
328           # container was cancelled in a different request, restart
329           # the loop and resolve request to a new container.
330           redo
331         end
332         self.container_uuid = c.uuid
333         break
334       end
335     end
336     if self.container_uuid != self.container_uuid_was
337       self.container_count += 1
338       return if self.container_uuid_was.nil?
339
340       old_container = Container.find_by_uuid(self.container_uuid_was)
341       return if old_container.nil?
342
343       old_logs = Collection.where(portable_data_hash: old_container.log).first
344       return if old_logs.nil?
345
346       log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
347       if self.log_uuid.nil?
348         log_coll = Collection.new(
349           owner_uuid: self.owner_uuid,
350           name: coll_name = "Container log for request #{uuid}",
351           manifest_text: "",
352           storage_classes_desired: self.output_storage_classes)
353       end
354
355       # copy logs from old container into CR's log collection
356       src = Arv::Collection.new(old_logs.manifest_text)
357       dst = Arv::Collection.new(log_coll.manifest_text)
358       dst.cp_r("./", "log for container #{old_container.uuid}", src)
359       manifest = dst.manifest_text
360
361       log_coll.assign_attributes(
362         portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
363         manifest_text: manifest)
364       log_coll.save_with_unique_name!
365       self.log_uuid = log_coll.uuid
366     end
367   end
368
369   def set_preemptible
370     if (new_record? || state_changed?) &&
371        state == Committed &&
372        Rails.configuration.Containers.AlwaysUsePreemptibleInstances &&
373        get_requesting_container_uuid() &&
374        self.class.any_preemptible_instances?
375       self.scheduling_parameters['preemptible'] = true
376     end
377   end
378
379   def validate_runtime_constraints
380     case self.state
381     when Committed
382       ['vcpus', 'ram'].each do |k|
383         v = runtime_constraints[k]
384         if !v.is_a?(Integer) || v <= 0
385           errors.add(:runtime_constraints,
386                      "[#{k}]=#{v.inspect} must be a positive integer")
387         end
388       end
389       if runtime_constraints['cuda']
390         ['device_count'].each do |k|
391           v = runtime_constraints['cuda'][k]
392           if !v.is_a?(Integer) || v < 0
393             errors.add(:runtime_constraints,
394                        "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
395           end
396         end
397         ['driver_version', 'hardware_capability'].each do |k|
398           v = runtime_constraints['cuda'][k]
399           if !v.is_a?(String) || (runtime_constraints['cuda']['device_count'] > 0 && v.to_f == 0.0)
400             errors.add(:runtime_constraints,
401                        "[cuda.#{k}]=#{v.inspect} must be a string in format 'X.Y'")
402           end
403         end
404       end
405     end
406   end
407
408   def validate_datatypes
409     command.each do |c|
410       if !c.is_a? String
411         errors.add(:command, "must be an array of strings but has entry #{c.class}")
412       end
413     end
414     environment.each do |k,v|
415       if !k.is_a?(String) || !v.is_a?(String)
416         errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
417       end
418     end
419     [:mounts, :secret_mounts].each do |m|
420       self[m].each do |k, v|
421         if !k.is_a?(String) || !v.is_a?(Hash)
422           errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
423         end
424         if v["kind"].nil?
425           errors.add(m, "each item must have a 'kind' field")
426         end
427         [[String, ["kind", "portable_data_hash", "uuid", "device_type",
428                    "path", "commit", "repository_name", "git_url"]],
429          [Integer, ["capacity"]]].each do |t, fields|
430           fields.each do |f|
431             if !v[f].nil? && !v[f].is_a?(t)
432               errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
433             end
434           end
435         end
436         ["writable", "exclude_from_output"].each do |f|
437           if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
438             errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
439           end
440         end
441       end
442     end
443   end
444
445   def validate_scheduling_parameters
446     if self.state == Committed
447       if scheduling_parameters.include? 'partitions' and
448          (!scheduling_parameters['partitions'].is_a?(Array) ||
449           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
450             scheduling_parameters['partitions'].size)
451             errors.add :scheduling_parameters, "partitions must be an array of strings"
452       end
453       if scheduling_parameters['preemptible'] &&
454          (new_record? || state_changed?) &&
455          !self.class.any_preemptible_instances?
456         errors.add :scheduling_parameters, "preemptible instances are not configured in InstanceTypes"
457       end
458       if scheduling_parameters.include? 'max_run_time' and
459         (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
460           scheduling_parameters['max_run_time'] < 0)
461           errors.add :scheduling_parameters, "max_run_time must be positive integer"
462       end
463     end
464   end
465
466   def check_update_whitelist
467     permitted = AttrsPermittedAlways.dup
468
469     if self.new_record? || self.state_was == Uncommitted
470       # Allow create-and-commit in a single operation.
471       permitted.push(*AttrsPermittedBeforeCommit)
472     elsif mounts_changed? && mounts_was.keys.sort == mounts.keys.sort
473       # Ignore the updated mounts if the only changes are default/zero
474       # values as added by controller, see 17774
475       only_defaults = true
476       mounts.each do |path, mount|
477         (mount.to_a - mounts_was[path].to_a).each do |k, v|
478           if ![0, "", false, nil].index(v)
479             only_defaults = false
480           end
481         end
482       end
483       if only_defaults
484         clear_attribute_change("mounts")
485       end
486     end
487
488     case self.state
489     when Committed
490       permitted.push :priority, :container_count_max, :container_uuid, :cumulative_cost
491
492       if self.priority.nil?
493         self.errors.add :priority, "cannot be nil"
494       end
495
496       # Allow container count to increment (not by client, only by us
497       # -- see set_container)
498       permitted.push :container_count
499
500       if current_user.andand.is_admin
501         permitted.push :log_uuid
502       end
503
504     when Final
505       if self.state_was == Committed
506         # "Cancel" means setting priority=0, state=Committed
507         permitted.push :priority, :cumulative_cost
508
509         if current_user.andand.is_admin
510           permitted.push :output_uuid, :log_uuid
511         end
512       end
513
514     end
515
516     super(permitted)
517   end
518
519   def secret_mounts_key_conflict
520     secret_mounts.each do |k, v|
521       if mounts.has_key?(k)
522         errors.add(:secret_mounts, 'conflict with non-secret mounts')
523         return false
524       end
525     end
526   end
527
528   def validate_runtime_token
529     if !self.runtime_token.nil? && self.runtime_token_changed?
530       if !runtime_token[0..2] == "v2/"
531         errors.add :runtime_token, "not a v2 token"
532         return
533       end
534       if ApiClientAuthorization.validate(token: runtime_token).nil?
535         errors.add :runtime_token, "failed validation"
536       end
537     end
538   end
539
540   def scrub_secrets
541     if self.state == Final
542       self.secret_mounts = {}
543       self.runtime_token = nil
544     end
545   end
546
547   def update_priority
548     return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
549     act_as_system_user do
550       Container.
551         where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
552         map(&:update_priority!)
553     end
554   end
555
556   def set_priority_zero
557     self.update_attributes!(priority: 0) if self.state != Final
558   end
559
560   def set_requesting_container_uuid
561     if (self.requesting_container_uuid = get_requesting_container_uuid())
562       # Determine the priority of container request for the requesting
563       # container.
564       self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
565     end
566   end
567
568   def get_requesting_container_uuid
569     return self.requesting_container_uuid || Container.for_current_token.andand.uuid
570   end
571 end