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