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