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