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