Bump loofah from 2.2.3 to 2.3.1 in /apps/workbench
[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     return if state != Committed
123     while true
124       # get container lock first, then lock current container request
125       # (same order as Container#handle_completed). Locking always
126       # reloads the Container and ContainerRequest records.
127       c = Container.find_by_uuid(container_uuid)
128       c.lock!
129       self.lock!
130
131       if container_uuid != c.uuid
132         # After locking, we've noticed a race, the container_uuid is
133         # different than the container record we just loaded.  This
134         # can happen if Container#handle_completed scheduled a new
135         # container for retry and set container_uuid while we were
136         # waiting on the container lock.  Restart the loop and get the
137         # new container.
138         redo
139       end
140
141       if state == Committed && c.final?
142         # The current container is
143         act_as_system_user do
144           leave_modified_by_user_alone do
145             finalize!
146           end
147         end
148       end
149       return true
150     end
151   end
152
153   # Finalize the container request after the container has
154   # finished/cancelled.
155   def finalize!
156     container = Container.find_by_uuid(container_uuid)
157     update_collections(container: container)
158
159     if container.state == Container::Complete
160       log_col = Collection.where(portable_data_hash: container.log).first
161       if log_col
162         # Need to save collection
163         completed_coll = Collection.new(
164           owner_uuid: self.owner_uuid,
165           name: "Container log for container #{container_uuid}",
166           properties: {
167             'type' => 'log',
168             'container_request' => self.uuid,
169             'container_uuid' => container_uuid,
170           },
171           portable_data_hash: log_col.portable_data_hash,
172           manifest_text: log_col.manifest_text)
173         completed_coll.save_with_unique_name!
174       end
175     end
176
177     update_attributes!(state: Final)
178   end
179
180   def update_collections(container:, collections: ['log', 'output'])
181     collections.each do |out_type|
182       pdh = container.send(out_type)
183       next if pdh.nil?
184       coll_name = "Container #{out_type} for request #{uuid}"
185       trash_at = nil
186       if out_type == 'output'
187         if self.output_name
188           coll_name = self.output_name
189         end
190         if self.output_ttl > 0
191           trash_at = db_current_time + self.output_ttl
192         end
193       end
194       manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
195
196       coll_uuid = self.send(out_type + '_uuid')
197       coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
198       if !coll
199         coll = Collection.new(
200           owner_uuid: self.owner_uuid,
201           name: coll_name,
202           manifest_text: "",
203           properties: {
204             'type' => out_type,
205             'container_request' => uuid,
206           })
207       end
208
209       if out_type == "log"
210         # Copy the log into a merged collection
211         src = Arv::Collection.new(manifest)
212         dst = Arv::Collection.new(coll.manifest_text)
213         dst.cp_r("./", ".", src)
214         dst.cp_r("./", "log for container #{container.uuid}", src)
215         manifest = dst.manifest_text
216       end
217
218       coll.assign_attributes(
219         portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
220         manifest_text: manifest,
221         trash_at: trash_at,
222         delete_at: trash_at)
223       coll.save_with_unique_name!
224       self.send(out_type + '_uuid=', coll.uuid)
225     end
226   end
227
228   def self.full_text_searchable_columns
229     super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token"]
230   end
231
232   protected
233
234   def fill_field_defaults
235     self.state ||= Uncommitted
236     self.environment ||= {}
237     self.runtime_constraints ||= {}
238     self.mounts ||= {}
239     self.secret_mounts ||= {}
240     self.cwd ||= "."
241     self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
242     self.scheduling_parameters ||= {}
243     self.output_ttl ||= 0
244     self.priority ||= 0
245   end
246
247   def set_container
248     if (container_uuid_changed? and
249         not current_user.andand.is_admin and
250         not container_uuid.nil?)
251       errors.add :container_uuid, "can only be updated to nil."
252       return false
253     end
254     if state_changed? and state == Committed and container_uuid.nil?
255       while true
256         c = Container.resolve(self)
257         c.lock!
258         if c.state == Container::Cancelled
259           # Lost a race, we have a lock on the container but the
260           # container was cancelled in a different request, restart
261           # the loop and resolve request to a new container.
262           redo
263         end
264         self.container_uuid = c.uuid
265         break
266       end
267     end
268     if self.container_uuid != self.container_uuid_was
269       if self.container_count_changed?
270         errors.add :container_count, "cannot be updated directly."
271         return false
272       else
273         self.container_count += 1
274         if self.container_uuid_was
275           old_container = Container.find_by_uuid(self.container_uuid_was)
276           old_logs = Collection.where(portable_data_hash: old_container.log).first
277           if old_logs
278             log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
279             if self.log_uuid.nil?
280               log_coll = Collection.new(
281                 owner_uuid: self.owner_uuid,
282                 name: coll_name = "Container log for request #{uuid}",
283                 manifest_text: "")
284             end
285
286             # copy logs from old container into CR's log collection
287             src = Arv::Collection.new(old_logs.manifest_text)
288             dst = Arv::Collection.new(log_coll.manifest_text)
289             dst.cp_r("./", "log for container #{old_container.uuid}", src)
290             manifest = dst.manifest_text
291
292             log_coll.assign_attributes(
293               portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
294               manifest_text: manifest)
295             log_coll.save_with_unique_name!
296             self.log_uuid = log_coll.uuid
297           end
298         end
299       end
300     end
301   end
302
303   def set_default_preemptible_scheduling_parameter
304     c = get_requesting_container()
305     if self.state == Committed
306       # If preemptible instances (eg: AWS Spot Instances) are allowed,
307       # ask them on child containers by default.
308       if Rails.configuration.Containers.UsePreemptibleInstances and !c.nil? and
309         self.scheduling_parameters['preemptible'].nil?
310           self.scheduling_parameters['preemptible'] = true
311       end
312     end
313   end
314
315   def validate_runtime_constraints
316     case self.state
317     when Committed
318       [['vcpus', true],
319        ['ram', true],
320        ['keep_cache_ram', false]].each do |k, required|
321         if !required && !runtime_constraints.include?(k)
322           next
323         end
324         v = runtime_constraints[k]
325         unless (v.is_a?(Integer) && v > 0)
326           errors.add(:runtime_constraints,
327                      "[#{k}]=#{v.inspect} must be a positive integer")
328         end
329       end
330     end
331   end
332
333   def validate_datatypes
334     command.each do |c|
335       if !c.is_a? String
336         errors.add(:command, "must be an array of strings but has entry #{c.class}")
337       end
338     end
339     environment.each do |k,v|
340       if !k.is_a?(String) || !v.is_a?(String)
341         errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
342       end
343     end
344     [:mounts, :secret_mounts].each do |m|
345       self[m].each do |k, v|
346         if !k.is_a?(String) || !v.is_a?(Hash)
347           errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
348         end
349         if v["kind"].nil?
350           errors.add(m, "each item must have a 'kind' field")
351         end
352         [[String, ["kind", "portable_data_hash", "uuid", "device_type",
353                    "path", "commit", "repository_name", "git_url"]],
354          [Integer, ["capacity"]]].each do |t, fields|
355           fields.each do |f|
356             if !v[f].nil? && !v[f].is_a?(t)
357               errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
358             end
359           end
360         end
361         ["writable", "exclude_from_output"].each do |f|
362           if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
363             errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
364           end
365         end
366       end
367     end
368   end
369
370   def validate_scheduling_parameters
371     if self.state == Committed
372       if scheduling_parameters.include? 'partitions' and
373          (!scheduling_parameters['partitions'].is_a?(Array) ||
374           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
375             scheduling_parameters['partitions'].size)
376             errors.add :scheduling_parameters, "partitions must be an array of strings"
377       end
378       if !Rails.configuration.Containers.UsePreemptibleInstances and scheduling_parameters['preemptible']
379         errors.add :scheduling_parameters, "preemptible instances are not allowed"
380       end
381       if scheduling_parameters.include? 'max_run_time' and
382         (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
383           scheduling_parameters['max_run_time'] < 0)
384           errors.add :scheduling_parameters, "max_run_time must be positive integer"
385       end
386     end
387   end
388
389   def check_update_whitelist
390     permitted = AttrsPermittedAlways.dup
391
392     if self.new_record? || self.state_was == Uncommitted
393       # Allow create-and-commit in a single operation.
394       permitted.push(*AttrsPermittedBeforeCommit)
395     end
396
397     case self.state
398     when Committed
399       permitted.push :priority, :container_count_max, :container_uuid
400
401       if self.container_uuid.nil?
402         self.errors.add :container_uuid, "has not been resolved to a container."
403       end
404
405       if self.priority.nil?
406         self.errors.add :priority, "cannot be nil"
407       end
408
409       # Allow container count to increment by 1
410       if (self.container_uuid &&
411           self.container_uuid != self.container_uuid_was &&
412           self.container_count == 1 + (self.container_count_was || 0))
413         permitted.push :container_count
414       end
415
416       if current_user.andand.is_admin
417         permitted.push :log_uuid
418       end
419
420     when Final
421       if self.state_was == Committed
422         # "Cancel" means setting priority=0, state=Committed
423         permitted.push :priority
424
425         if current_user.andand.is_admin
426           permitted.push :output_uuid, :log_uuid
427         end
428       end
429
430     end
431
432     super(permitted)
433   end
434
435   def secret_mounts_key_conflict
436     secret_mounts.each do |k, v|
437       if mounts.has_key?(k)
438         errors.add(:secret_mounts, 'conflict with non-secret mounts')
439         return false
440       end
441     end
442   end
443
444   def validate_runtime_token
445     if !self.runtime_token.nil? && self.runtime_token_changed?
446       if !runtime_token[0..2] == "v2/"
447         errors.add :runtime_token, "not a v2 token"
448         return
449       end
450       if ApiClientAuthorization.validate(token: runtime_token).nil?
451         errors.add :runtime_token, "failed validation"
452       end
453     end
454   end
455
456   def scrub_secrets
457     if self.state == Final
458       self.secret_mounts = {}
459       self.runtime_token = nil
460     end
461   end
462
463   def update_priority
464     return unless state_changed? || priority_changed? || container_uuid_changed?
465     act_as_system_user do
466       Container.
467         where('uuid in (?)', [self.container_uuid_was, self.container_uuid].compact).
468         map(&:update_priority!)
469     end
470   end
471
472   def set_priority_zero
473     self.update_attributes!(priority: 0) if self.state != Final
474   end
475
476   def set_requesting_container_uuid
477     c = get_requesting_container()
478     if !c.nil?
479       self.requesting_container_uuid = c.uuid
480       # Determine the priority of container request for the requesting
481       # container.
482       self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
483     end
484   end
485
486   def get_requesting_container
487     return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
488     Container.for_current_token
489   end
490 end