18321: Check runtime constraints md5 with/without empty cuda section
[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       if runtime_constraints['cuda']
340         ['device_count'].each do |k|
341           v = runtime_constraints['cuda'][k]
342           if !v.is_a?(Integer) || v < 0
343             errors.add(:runtime_constraints,
344                        "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
345           end
346         end
347         ['driver_version', 'hardware_capability'].each do |k|
348           v = runtime_constraints['cuda'][k]
349           if !v.is_a?(String) || (runtime_constraints['cuda']['device_count'] > 0 && v.to_f == 0.0)
350             errors.add(:runtime_constraints,
351                        "[cuda.#{k}]=#{v.inspect} must be a string in format 'X.Y' version")
352           end
353         end
354       end
355     end
356   end
357
358   def validate_datatypes
359     command.each do |c|
360       if !c.is_a? String
361         errors.add(:command, "must be an array of strings but has entry #{c.class}")
362       end
363     end
364     environment.each do |k,v|
365       if !k.is_a?(String) || !v.is_a?(String)
366         errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
367       end
368     end
369     [:mounts, :secret_mounts].each do |m|
370       self[m].each do |k, v|
371         if !k.is_a?(String) || !v.is_a?(Hash)
372           errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
373         end
374         if v["kind"].nil?
375           errors.add(m, "each item must have a 'kind' field")
376         end
377         [[String, ["kind", "portable_data_hash", "uuid", "device_type",
378                    "path", "commit", "repository_name", "git_url"]],
379          [Integer, ["capacity"]]].each do |t, fields|
380           fields.each do |f|
381             if !v[f].nil? && !v[f].is_a?(t)
382               errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
383             end
384           end
385         end
386         ["writable", "exclude_from_output"].each do |f|
387           if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
388             errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
389           end
390         end
391       end
392     end
393   end
394
395   def validate_scheduling_parameters
396     if self.state == Committed
397       if scheduling_parameters.include? 'partitions' and
398          (!scheduling_parameters['partitions'].is_a?(Array) ||
399           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
400             scheduling_parameters['partitions'].size)
401             errors.add :scheduling_parameters, "partitions must be an array of strings"
402       end
403       if !Rails.configuration.Containers.UsePreemptibleInstances and scheduling_parameters['preemptible']
404         errors.add :scheduling_parameters, "preemptible instances are not allowed"
405       end
406       if scheduling_parameters.include? 'max_run_time' and
407         (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
408           scheduling_parameters['max_run_time'] < 0)
409           errors.add :scheduling_parameters, "max_run_time must be positive integer"
410       end
411     end
412   end
413
414   def check_update_whitelist
415     permitted = AttrsPermittedAlways.dup
416
417     if self.new_record? || self.state_was == Uncommitted
418       # Allow create-and-commit in a single operation.
419       permitted.push(*AttrsPermittedBeforeCommit)
420     elsif mounts_changed? && mounts_was.keys == mounts.keys
421       # Ignore the updated mounts if the only changes are default/zero
422       # values as added by controller, see 17774
423       only_defaults = true
424       mounts.each do |path, mount|
425         (mount.to_a - mounts_was[path].to_a).each do |k, v|
426           if !["", false, nil].index(v)
427             only_defaults = false
428           end
429         end
430       end
431       if only_defaults
432         clear_attribute_change("mounts")
433       end
434     end
435
436     case self.state
437     when Committed
438       permitted.push :priority, :container_count_max, :container_uuid
439
440       if self.container_uuid.nil?
441         self.errors.add :container_uuid, "has not been resolved to a container."
442       end
443
444       if self.priority.nil?
445         self.errors.add :priority, "cannot be nil"
446       end
447
448       # Allow container count to increment by 1
449       if (self.container_uuid &&
450           self.container_uuid != self.container_uuid_was &&
451           self.container_count == 1 + (self.container_count_was || 0))
452         permitted.push :container_count
453       end
454
455       if current_user.andand.is_admin
456         permitted.push :log_uuid
457       end
458
459     when Final
460       if self.state_was == Committed
461         # "Cancel" means setting priority=0, state=Committed
462         permitted.push :priority
463
464         if current_user.andand.is_admin
465           permitted.push :output_uuid, :log_uuid
466         end
467       end
468
469     end
470
471     super(permitted)
472   end
473
474   def secret_mounts_key_conflict
475     secret_mounts.each do |k, v|
476       if mounts.has_key?(k)
477         errors.add(:secret_mounts, 'conflict with non-secret mounts')
478         return false
479       end
480     end
481   end
482
483   def validate_runtime_token
484     if !self.runtime_token.nil? && self.runtime_token_changed?
485       if !runtime_token[0..2] == "v2/"
486         errors.add :runtime_token, "not a v2 token"
487         return
488       end
489       if ApiClientAuthorization.validate(token: runtime_token).nil?
490         errors.add :runtime_token, "failed validation"
491       end
492     end
493   end
494
495   def scrub_secrets
496     if self.state == Final
497       self.secret_mounts = {}
498       self.runtime_token = nil
499     end
500   end
501
502   def update_priority
503     return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
504     act_as_system_user do
505       Container.
506         where('uuid in (?)', [container_uuid_before_last_save, self.container_uuid].compact).
507         map(&:update_priority!)
508     end
509   end
510
511   def set_priority_zero
512     self.update_attributes!(priority: 0) if self.state != Final
513   end
514
515   def set_requesting_container_uuid
516     c = get_requesting_container()
517     if !c.nil?
518       self.requesting_container_uuid = c.uuid
519       # Determine the priority of container request for the requesting
520       # container.
521       self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
522     end
523   end
524
525   def get_requesting_container
526     return self.requesting_container_uuid if !self.requesting_container_uuid.nil?
527     Container.for_current_token
528   end
529 end