Merge branch '13973-child-priority' refs #13973
[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
7 class ContainerRequest < ArvadosModel
8   include ArvadosModelUpdates
9   include HasUuid
10   include KindAndEtag
11   include CommonApiTemplate
12   include WhitelistUpdate
13
14   belongs_to :container, foreign_key: :container_uuid, primary_key: :uuid
15   belongs_to :requesting_container, {
16                class_name: 'Container',
17                foreign_key: :requesting_container_uuid,
18                primary_key: :uuid,
19              }
20
21   serialize :properties, Hash
22   serialize :environment, Hash
23   serialize :mounts, Hash
24   serialize :runtime_constraints, Hash
25   serialize :command, Array
26   serialize :scheduling_parameters, Hash
27   serialize :secret_mounts, Hash
28
29   before_validation :fill_field_defaults, :if => :new_record?
30   before_validation :validate_runtime_constraints
31   before_validation :set_default_preemptible_scheduling_parameter
32   before_validation :set_container
33   validates :command, :container_image, :output_path, :cwd, :presence => true
34   validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
35   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
36   validate :validate_datatypes
37   validate :validate_scheduling_parameters
38   validate :validate_state_change
39   validate :check_update_whitelist
40   validate :secret_mounts_key_conflict
41   before_save :scrub_secret_mounts
42   before_create :set_requesting_container_uuid
43   before_destroy :set_priority_zero
44   after_save :update_priority
45   after_save :finalize_if_needed
46
47   api_accessible :user, extend: :common do |t|
48     t.add :command
49     t.add :container_count
50     t.add :container_count_max
51     t.add :container_image
52     t.add :container_uuid
53     t.add :cwd
54     t.add :description
55     t.add :environment
56     t.add :expires_at
57     t.add :filters
58     t.add :log_uuid
59     t.add :mounts
60     t.add :name
61     t.add :output_name
62     t.add :output_path
63     t.add :output_uuid
64     t.add :output_ttl
65     t.add :priority
66     t.add :properties
67     t.add :requesting_container_uuid
68     t.add :runtime_constraints
69     t.add :scheduling_parameters
70     t.add :state
71     t.add :use_existing
72   end
73
74   # Supported states for a container request
75   States =
76     [
77      (Uncommitted = 'Uncommitted'),
78      (Committed = 'Committed'),
79      (Final = 'Final'),
80     ]
81
82   State_transitions = {
83     nil => [Uncommitted, Committed],
84     Uncommitted => [Committed],
85     Committed => [Final]
86   }
87
88   AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
89   AttrsPermittedBeforeCommit = [:command, :container_count_max,
90   :container_image, :cwd, :environment, :filters, :mounts,
91   :output_path, :priority,
92   :runtime_constraints, :state, :container_uuid, :use_existing,
93   :scheduling_parameters, :secret_mounts, :output_name, :output_ttl]
94
95   def self.limit_index_columns_read
96     ["mounts"]
97   end
98
99   def logged_attributes
100     super.except('secret_mounts')
101   end
102
103   def state_transitions
104     State_transitions
105   end
106
107   def skip_uuid_read_permission_check
108     # XXX temporary until permissions are sorted out.
109     %w(modified_by_client_uuid container_uuid requesting_container_uuid)
110   end
111
112   def finalize_if_needed
113     if state == Committed && Container.find_by_uuid(container_uuid).final?
114       reload
115       act_as_system_user do
116         leave_modified_by_user_alone do
117           finalize!
118         end
119       end
120     end
121   end
122
123   # Finalize the container request after the container has
124   # finished/cancelled.
125   def finalize!
126     out_coll = nil
127     log_coll = nil
128     c = Container.find_by_uuid(container_uuid)
129     ['output', 'log'].each do |out_type|
130       pdh = c.send(out_type)
131       next if pdh.nil?
132       coll_name = "Container #{out_type} for request #{uuid}"
133       trash_at = nil
134       if out_type == 'output'
135         if self.output_name
136           coll_name = self.output_name
137         end
138         if self.output_ttl > 0
139           trash_at = db_current_time + self.output_ttl
140         end
141       end
142       manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
143
144       coll = Collection.new(owner_uuid: owner_uuid,
145                             manifest_text: manifest,
146                             portable_data_hash: pdh,
147                             name: coll_name,
148                             trash_at: trash_at,
149                             delete_at: trash_at,
150                             properties: {
151                               'type' => out_type,
152                               'container_request' => uuid,
153                             })
154       coll.save_with_unique_name!
155       if out_type == 'output'
156         out_coll = coll.uuid
157       else
158         log_coll = coll.uuid
159       end
160     end
161     update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)
162   end
163
164   def self.full_text_searchable_columns
165     super - ["mounts", "secret_mounts", "secret_mounts_md5"]
166   end
167
168   protected
169
170   def fill_field_defaults
171     self.state ||= Uncommitted
172     self.environment ||= {}
173     self.runtime_constraints ||= {}
174     self.mounts ||= {}
175     self.cwd ||= "."
176     self.container_count_max ||= Rails.configuration.container_count_max
177     self.scheduling_parameters ||= {}
178     self.output_ttl ||= 0
179     self.priority ||= 0
180   end
181
182   def set_container
183     if (container_uuid_changed? and
184         not current_user.andand.is_admin and
185         not container_uuid.nil?)
186       errors.add :container_uuid, "can only be updated to nil."
187       return false
188     end
189     if state_changed? and state == Committed and container_uuid.nil?
190       self.container_uuid = Container.resolve(self).uuid
191     end
192     if self.container_uuid != self.container_uuid_was
193       if self.container_count_changed?
194         errors.add :container_count, "cannot be updated directly."
195         return false
196       else
197         self.container_count += 1
198       end
199     end
200   end
201
202   def set_default_preemptible_scheduling_parameter
203     c = get_requesting_container()
204     if self.state == Committed
205       # If preemptible instances (eg: AWS Spot Instances) are allowed,
206       # ask them on child containers by default.
207       if Rails.configuration.preemptible_instances and !c.nil? and
208         self.scheduling_parameters['preemptible'].nil?
209           self.scheduling_parameters['preemptible'] = true
210       end
211     end
212   end
213
214   def validate_runtime_constraints
215     case self.state
216     when Committed
217       [['vcpus', true],
218        ['ram', true],
219        ['keep_cache_ram', false]].each do |k, required|
220         if !required && !runtime_constraints.include?(k)
221           next
222         end
223         v = runtime_constraints[k]
224         unless (v.is_a?(Integer) && v > 0)
225           errors.add(:runtime_constraints,
226                      "[#{k}]=#{v.inspect} must be a positive integer")
227         end
228       end
229     end
230   end
231
232   def validate_datatypes
233     command.each do |c|
234       if !c.is_a? String
235         errors.add(:command, "must be an array of strings but has entry #{c.class}")
236       end
237     end
238     environment.each do |k,v|
239       if !k.is_a?(String) || !v.is_a?(String)
240         errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
241       end
242     end
243     [:mounts, :secret_mounts].each do |m|
244       self[m].each do |k, v|
245         if !k.is_a?(String) || !v.is_a?(Hash)
246           errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
247         end
248         if v["kind"].nil?
249           errors.add(m, "each item must have a 'kind' field")
250         end
251         [[String, ["kind", "portable_data_hash", "uuid", "device_type",
252                    "path", "commit", "repository_name", "git_url"]],
253          [Integer, ["capacity"]]].each do |t, fields|
254           fields.each do |f|
255             if !v[f].nil? && !v[f].is_a?(t)
256               errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
257             end
258           end
259         end
260         ["writable", "exclude_from_output"].each do |f|
261           if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
262             errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
263           end
264         end
265       end
266     end
267   end
268
269   def validate_scheduling_parameters
270     if self.state == Committed
271       if scheduling_parameters.include? 'partitions' and
272          (!scheduling_parameters['partitions'].is_a?(Array) ||
273           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
274             scheduling_parameters['partitions'].size)
275             errors.add :scheduling_parameters, "partitions must be an array of strings"
276       end
277       if !Rails.configuration.preemptible_instances and scheduling_parameters['preemptible']
278         errors.add :scheduling_parameters, "preemptible instances are not allowed"
279       end
280       if scheduling_parameters.include? 'max_run_time' and
281         (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
282           scheduling_parameters['max_run_time'] < 0)
283           errors.add :scheduling_parameters, "max_run_time must be positive integer"
284       end
285     end
286   end
287
288   def check_update_whitelist
289     permitted = AttrsPermittedAlways.dup
290
291     if self.new_record? || self.state_was == Uncommitted
292       # Allow create-and-commit in a single operation.
293       permitted.push(*AttrsPermittedBeforeCommit)
294     end
295
296     case self.state
297     when Committed
298       permitted.push :priority, :container_count_max, :container_uuid
299
300       if self.container_uuid.nil?
301         self.errors.add :container_uuid, "has not been resolved to a container."
302       end
303
304       if self.priority.nil?
305         self.errors.add :priority, "cannot be nil"
306       end
307
308       # Allow container count to increment by 1
309       if (self.container_uuid &&
310           self.container_uuid != self.container_uuid_was &&
311           self.container_count == 1 + (self.container_count_was || 0))
312         permitted.push :container_count
313       end
314
315     when Final
316       if self.state_was == Committed
317         # "Cancel" means setting priority=0, state=Committed
318         permitted.push :priority
319
320         if current_user.andand.is_admin
321           permitted.push :output_uuid, :log_uuid
322         end
323       end
324
325     end
326
327     super(permitted)
328   end
329
330   def secret_mounts_key_conflict
331     secret_mounts.each do |k, v|
332       if mounts.has_key?(k)
333         errors.add(:secret_mounts, 'conflict with non-secret mounts')
334         return false
335       end
336     end
337   end
338
339   def scrub_secret_mounts
340     if self.state == Final
341       self.secret_mounts = {}
342     end
343   end
344
345   def update_priority
346     return unless state_changed? || priority_changed? || container_uuid_changed?
347     act_as_system_user do
348       Container.
349         where('uuid in (?)', [self.container_uuid_was, self.container_uuid].compact).
350         map(&:update_priority!)
351     end
352   end
353
354   def set_priority_zero
355     self.update_attributes!(priority: 0) if self.state != Final
356   end
357
358   def set_requesting_container_uuid
359     c = get_requesting_container()
360     if !c.nil?
361       self.requesting_container_uuid = c.uuid
362       # Determine the priority of container request for the requesting
363       # container.
364       self.priority = ContainerRequest.
365             where('container_uuid=? and priority>0', self.requesting_container_uuid).
366             map do |cr|
367         cr.priority
368       end.max || 0
369     end
370   end
371
372   def get_requesting_container
373     return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
374     return if !current_api_client_authorization
375     if (c = Container.where('auth_uuid=?', current_api_client_authorization.uuid).select([:uuid, :priority]).first)
376       return c
377     end
378   end
379 end