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