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