Merge branch '22232-rails-dynamic-index-limit'
[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,
16              foreign_key: 'container_uuid',
17              primary_key: 'uuid',
18              optional: true
19   belongs_to :requesting_container,
20              class_name: 'Container',
21              foreign_key: 'requesting_container_uuid',
22              primary_key: 'uuid',
23              optional: true
24
25   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
26   # already know how to properly treat them.
27   attribute :properties, :jsonbHash, default: {}
28   attribute :secret_mounts, :jsonbHash, default: {}
29   attribute :output_storage_classes, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
30   attribute :output_properties, :jsonbHash, default: {}
31
32   serialize :environment, Hash
33   serialize :mounts, Hash
34   serialize :runtime_constraints, Hash
35   serialize :command, Array
36   serialize :scheduling_parameters, Hash
37   serialize :output_glob, Array
38
39   after_find :fill_container_defaults_after_find
40   after_initialize { @state_was_when_initialized = self.state_was } # see finalize_if_needed
41   before_validation :fill_field_defaults, :if => :new_record?
42   before_validation :fill_container_defaults
43   validates :command, :container_image, :output_path, :cwd, :presence => true
44   validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
45   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
46   validate :validate_datatypes
47   validate :validate_runtime_constraints
48   validate :validate_scheduling_parameters
49   validate :validate_state_change
50   validate :check_update_whitelist
51   validate :secret_mounts_key_conflict
52   validate :validate_runtime_token
53   after_validation :scrub_secrets
54   after_validation :set_preemptible
55   after_validation :set_container
56   before_create :set_requesting_container_uuid
57   before_destroy :set_priority_zero
58   after_save :update_priority
59   after_save :finalize_if_needed
60
61   api_accessible :user, extend: :common do |t|
62     t.add :command
63     t.add :container_count
64     t.add :container_count_max
65     t.add :container_image
66     t.add :container_uuid
67     t.add :cwd
68     t.add :description
69     t.add :environment
70     t.add :expires_at
71     t.add :filters
72     t.add :log_uuid
73     t.add :mounts
74     t.add :name
75     t.add :output_name
76     t.add :output_path
77     t.add :output_glob
78     t.add :output_uuid
79     t.add :output_ttl
80     t.add :priority
81     t.add :properties
82     t.add :requesting_container_uuid
83     t.add :runtime_constraints
84     t.add :scheduling_parameters
85     t.add :state
86     t.add :use_existing
87     t.add :output_storage_classes
88     t.add :output_properties
89     t.add :cumulative_cost
90   end
91
92   # Supported states for a container request
93   States =
94     [
95      (Uncommitted = 'Uncommitted'),
96      (Committed = 'Committed'),
97      (Final = 'Final'),
98     ]
99
100   State_transitions = {
101     nil => [Uncommitted, Committed],
102     Uncommitted => [Committed],
103     Committed => [Final]
104   }
105
106   AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
107   AttrsPermittedBeforeCommit = [:command, :container_count_max,
108   :container_image, :cwd, :environment, :filters, :mounts,
109   :output_path, :output_glob, :priority, :runtime_token,
110   :runtime_constraints, :state, :container_uuid, :use_existing,
111   :scheduling_parameters, :secret_mounts, :output_name, :output_ttl,
112   :output_storage_classes, :output_properties]
113
114   def self.any_preemptible_instances?
115     Rails.configuration.InstanceTypes.any? do |k, v|
116       v["Preemptible"]
117     end
118   end
119
120   def logged_attributes
121     super.except('secret_mounts', 'runtime_token')
122   end
123
124   def state_transitions
125     State_transitions
126   end
127
128   def skip_uuid_read_permission_check
129     # The uuid_read_permission_check prevents users from making
130     # references to objects they can't view.  However, in this case we
131     # don't want to do that check since there's a circular dependency
132     # where user can't view the container until the user has
133     # constructed the container request that references the container.
134     %w(container_uuid)
135   end
136
137   def finalize_if_needed
138     return if state != Committed
139     while true
140       # get container lock first, then lock current container request
141       # (same order as Container#handle_completed). Locking always
142       # reloads the Container and ContainerRequest records.
143       c = Container.find_by_uuid(container_uuid)
144       c.lock! if !c.nil?
145       self.lock!
146
147       if !c.nil? && container_uuid != c.uuid
148         # After locking, we've noticed a race, the container_uuid is
149         # different than the container record we just loaded.  This
150         # can happen if Container#handle_completed scheduled a new
151         # container for retry and set container_uuid while we were
152         # waiting on the container lock.  Restart the loop and get the
153         # new container.
154         redo
155       end
156
157       if !c.nil?
158         if state == Committed && c.final?
159           # The current container is
160           act_as_system_user do
161             leave_modified_by_user_alone do
162               finalize!
163             end
164           end
165         end
166       elsif state == Committed
167         # Behave as if the container is cancelled
168         update!(state: Final)
169       end
170       return true
171     end
172   end
173
174   # Finalize the container request after the container has
175   # finished/cancelled.
176   def finalize!
177     container = Container.find_by_uuid(container_uuid)
178     if !container.nil?
179       # We don't want to add the container cost if the container was
180       # already finished when this CR was committed. But we are
181       # running in an after_save hook after a lock/reload, so
182       # state_was has already been updated to Committed regardless.
183       # Hence the need for @state_was_when_initialized.
184       if @state_was_when_initialized == Committed
185         # Add the final container cost to our cumulative cost (which
186         # may already be non-zero from previous attempts if
187         # container_count_max > 1).
188         self.cumulative_cost += container.cost + container.subrequests_cost
189       end
190
191       # Add our cumulative cost to the subrequests_cost of the
192       # requesting container, if any.
193       if self.requesting_container_uuid
194         Container.where(
195           uuid: self.requesting_container_uuid,
196           state: Container::Running,
197         ).each do |c|
198           c.subrequests_cost += self.cumulative_cost
199           c.save!
200         end
201       end
202
203       update_collections(container: container)
204       # update_collections makes a log collection that includes all of the logs
205       # for all of the containers associated with this request. For requests
206       # that are retried, this is the primary way users can get logs for
207       # failed containers.
208       # The code below makes a log collection that is a verbatim copy of the
209       # container's logs. This is required for container reuse: a container
210       # will not be reused if the owner cannot read a collection with its logs.
211       # See the "readable log" section of Container.find_reusable().
212       if container.state == Container::Complete
213         log_col = Collection.where(portable_data_hash: container.log).first
214         if log_col
215           # Need to save collection
216           completed_coll = Collection.new(
217             owner_uuid: self.owner_uuid,
218             name: "Container log for container #{container_uuid}",
219             properties: {
220               'type' => 'log',
221               'container_request' => self.uuid,
222               'container_uuid' => container_uuid,
223             },
224             portable_data_hash: log_col.portable_data_hash,
225             manifest_text: log_col.manifest_text,
226             storage_classes_desired: self.output_storage_classes
227           )
228           completed_coll.save_with_unique_name!
229         end
230       end
231     end
232     update!(state: Final)
233   end
234
235   def update_collections(container:, collections: ['log', 'output'])
236
237     # Check if parent is frozen or trashed, in which case it isn't
238     # valid to create new collections in the project, so return
239     # without creating anything.
240     owner = Group.find_by_uuid(self.owner_uuid)
241     return if owner && !owner.admin_change_permitted
242
243     collections.each do |out_type|
244       pdh = container.send(out_type)
245       next if pdh.nil?
246       c = Collection.where(portable_data_hash: pdh).first
247       next if c.nil?
248       manifest = c.manifest_text
249
250       coll_name = "Container #{out_type} for request #{uuid}"
251       trash_at = nil
252       if out_type == 'output'
253         if self.output_name and self.output_name != ""
254           coll_name = self.output_name
255         end
256         if self.output_ttl > 0
257           trash_at = db_current_time + self.output_ttl
258         end
259       end
260
261       coll_uuid = self.send(out_type + '_uuid')
262       coll = coll_uuid.nil? ? nil : Collection.where(uuid: coll_uuid).first
263       if !coll
264         coll = Collection.new(
265           owner_uuid: self.owner_uuid,
266           name: coll_name,
267           manifest_text: "",
268           storage_classes_desired: self.output_storage_classes)
269       end
270
271       if out_type == "log"
272         # Copy the log into a merged collection
273         src = Arv::Collection.new(manifest)
274         dst = Arv::Collection.new(coll.manifest_text)
275         dst.cp_r("./", ".", src)
276         dst.cp_r("./", "log for container #{container.uuid}", src)
277         manifest = dst.manifest_text
278       end
279
280       merged_properties = {}
281       merged_properties['container_request'] = uuid
282
283       if out_type == 'output' and !requesting_container_uuid.nil?
284         # output of a child process, give it "intermediate" type by
285         # default.
286         merged_properties['type'] = 'intermediate'
287       else
288         merged_properties['type'] = out_type
289       end
290
291       if out_type == "output"
292         merged_properties.update(container.output_properties)
293         merged_properties.update(self.output_properties)
294       end
295
296       coll.assign_attributes(
297         portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
298         manifest_text: manifest,
299         trash_at: trash_at,
300         delete_at: trash_at,
301         properties: merged_properties)
302       coll.save_with_unique_name!
303       self.send(out_type + '_uuid=', coll.uuid)
304     end
305   end
306
307   def self.full_text_searchable_columns
308     super - ["mounts", "secret_mounts", "secret_mounts_md5", "runtime_token", "output_storage_classes", "output_glob"]
309   end
310
311   def set_priority_zero
312     self.update!(priority: 0) if self.priority > 0 && self.state != Final
313   end
314
315   protected
316
317   def fill_field_defaults
318     self.state ||= Uncommitted
319     self.environment ||= {}
320     self.runtime_constraints ||= {}
321     self.mounts ||= {}
322     self.secret_mounts ||= {}
323     self.cwd ||= "."
324     self.container_count_max ||= Rails.configuration.Containers.MaxRetryAttempts
325     self.scheduling_parameters ||= {}
326     self.output_ttl ||= 0
327     self.output_glob ||= []
328     self.priority ||= 0
329   end
330
331   def set_container
332     if (container_uuid_changed? and
333         not current_user.andand.is_admin and
334         not container_uuid.nil?)
335       errors.add :container_uuid, "can only be updated to nil."
336       return false
337     end
338     if self.container_count_changed?
339       errors.add :container_count, "cannot be updated directly."
340       return false
341     end
342     if state_changed? and state == Committed and container_uuid.nil?
343       if self.command.length > 0 and self.command[0] == "arvados-cwl-runner"
344         # Special case, arvados-cwl-runner processes are always considered "supervisors"
345         self.scheduling_parameters['supervisor'] = true
346       end
347       while true
348         c = Container.resolve(self)
349         c.lock!
350         if c.state == Container::Cancelled
351           # Lost a race, we have a lock on the container but the
352           # container was cancelled in a different request, restart
353           # the loop and resolve request to a new container.
354           redo
355         end
356         self.container_uuid = c.uuid
357         break
358       end
359     end
360     if self.container_uuid != self.container_uuid_was
361       self.container_count += 1
362       return if self.container_uuid_was.nil?
363
364       old_container_uuid = self.container_uuid_was
365       old_container_log = Container.where(uuid: old_container_uuid).pluck(:log).first
366       return if old_container_log.nil?
367
368       old_logs = Collection.where(portable_data_hash: old_container_log).first
369       return if old_logs.nil?
370
371       log_coll = self.log_uuid.nil? ? nil : Collection.where(uuid: self.log_uuid).first
372       if self.log_uuid.nil?
373         log_coll = Collection.new(
374           owner_uuid: self.owner_uuid,
375           name: coll_name = "Container log for request #{uuid}",
376           manifest_text: "",
377           storage_classes_desired: self.output_storage_classes)
378       end
379
380       # copy logs from old container into CR's log collection
381       src = Arv::Collection.new(old_logs.manifest_text)
382       dst = Arv::Collection.new(log_coll.manifest_text)
383       dst.cp_r("./", "log for container #{old_container_uuid}", src)
384       manifest = dst.manifest_text
385
386       log_coll.assign_attributes(
387         portable_data_hash: Digest::MD5.hexdigest(manifest) + '+' + manifest.bytesize.to_s,
388         manifest_text: manifest)
389       log_coll.save_with_unique_name!
390       self.log_uuid = log_coll.uuid
391     end
392   end
393
394   def set_preemptible
395     if (new_record? || state_changed?) &&
396        state == Committed &&
397        Rails.configuration.Containers.AlwaysUsePreemptibleInstances &&
398        get_requesting_container_uuid() &&
399        self.class.any_preemptible_instances?
400       self.scheduling_parameters['preemptible'] = true
401     end
402   end
403
404   def validate_runtime_constraints
405     case self.state
406     when Committed
407       ['vcpus', 'ram'].each do |k|
408         v = runtime_constraints[k]
409         if !v.is_a?(Integer) || v <= 0
410           errors.add(:runtime_constraints,
411                      "[#{k}]=#{v.inspect} must be a positive integer")
412         end
413       end
414       if runtime_constraints['cuda']
415         ['device_count'].each do |k|
416           v = runtime_constraints['cuda'][k]
417           if !v.is_a?(Integer) || v < 0
418             errors.add(:runtime_constraints,
419                        "[cuda.#{k}]=#{v.inspect} must be a positive or zero integer")
420           end
421         end
422         ['driver_version', 'hardware_capability'].each do |k|
423           v = runtime_constraints['cuda'][k]
424           if !v.is_a?(String) || (runtime_constraints['cuda']['device_count'] > 0 && v.to_f == 0.0)
425             errors.add(:runtime_constraints,
426                        "[cuda.#{k}]=#{v.inspect} must be a string in format 'X.Y'")
427           end
428         end
429       end
430     end
431   end
432
433   def validate_datatypes
434     command.each do |c|
435       if !c.is_a? String
436         errors.add(:command, "must be an array of strings but has entry #{c.class}")
437       end
438     end
439     environment.each do |k,v|
440       if !k.is_a?(String) || !v.is_a?(String)
441         errors.add(:environment, "must be an map of String to String but has entry #{k.class} to #{v.class}")
442       end
443     end
444     output_glob.each do |g|
445       if !g.is_a? String
446         errors.add(:output_glob, "must be an array of strings but has entry #{g.class}")
447       end
448     end
449     [:mounts, :secret_mounts].each do |m|
450       self[m].each do |k, v|
451         if !k.is_a?(String) || !v.is_a?(Hash)
452           errors.add(m, "must be an map of String to Hash but is has entry #{k.class} to #{v.class}")
453         end
454         if v["kind"].nil?
455           errors.add(m, "each item must have a 'kind' field")
456         end
457         [[String, ["kind", "portable_data_hash", "uuid", "device_type",
458                    "path", "commit", "repository_name", "git_url"]],
459          [Integer, ["capacity"]]].each do |t, fields|
460           fields.each do |f|
461             if !v[f].nil? && !v[f].is_a?(t)
462               errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
463             end
464           end
465         end
466         ["writable", "exclude_from_output"].each do |f|
467           if !v[f].nil? && !v[f].is_a?(TrueClass) && !v[f].is_a?(FalseClass)
468             errors.add(m, "#{k}: #{f} must be a #{t} but is #{v[f].class}")
469           end
470         end
471       end
472     end
473   end
474
475   def validate_scheduling_parameters
476     if self.state == Committed
477       if scheduling_parameters.include?('partitions') and
478         !scheduling_parameters['partitions'].nil? and
479         (!scheduling_parameters['partitions'].is_a?(Array) ||
480           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
481             scheduling_parameters['partitions'].size)
482             errors.add :scheduling_parameters, "partitions must be an array of strings"
483       end
484       if scheduling_parameters['preemptible'] &&
485          (new_record? || state_changed?) &&
486          !self.class.any_preemptible_instances?
487         errors.add :scheduling_parameters, "preemptible instances are not configured in InstanceTypes"
488       end
489       if scheduling_parameters.include? 'max_run_time' and
490         (!scheduling_parameters['max_run_time'].is_a?(Integer) ||
491           scheduling_parameters['max_run_time'] < 0)
492           errors.add :scheduling_parameters, "max_run_time must be positive integer"
493       end
494     end
495   end
496
497   def check_update_whitelist
498     permitted = AttrsPermittedAlways.dup
499
500     if self.new_record? || self.state_was == Uncommitted
501       # Allow create-and-commit in a single operation.
502       permitted.push(*AttrsPermittedBeforeCommit)
503     elsif mounts_changed? && mounts_was.keys.sort == mounts.keys.sort
504       # Ignore the updated mounts if the only changes are default/zero
505       # values as added by controller, see 17774
506       only_defaults = true
507       mounts.each do |path, mount|
508         (mount.to_a - mounts_was[path].to_a).each do |k, v|
509           if ![0, "", false, nil].index(v)
510             only_defaults = false
511           end
512         end
513       end
514       if only_defaults
515         clear_attribute_change("mounts")
516       end
517     end
518
519     case self.state
520     when Committed
521       permitted.push :priority, :container_count_max, :container_uuid, :cumulative_cost
522
523       if self.priority.nil?
524         self.errors.add :priority, "cannot be nil"
525       end
526
527       # Allow container count to increment (not by client, only by us
528       # -- see set_container)
529       permitted.push :container_count
530
531       if current_user.andand.is_admin
532         permitted.push :log_uuid
533       end
534
535     when Final
536       if self.state_was == Committed
537         # "Cancel" means setting priority=0, state=Committed
538         permitted.push :priority, :cumulative_cost
539
540         if current_user.andand.is_admin
541           permitted.push :output_uuid, :log_uuid
542         end
543       end
544
545     end
546
547     super(permitted)
548   end
549
550   def secret_mounts_key_conflict
551     secret_mounts.each do |k, v|
552       if mounts.has_key?(k)
553         errors.add(:secret_mounts, 'conflict with non-secret mounts')
554         return false
555       end
556     end
557   end
558
559   def validate_runtime_token
560     if !self.runtime_token.nil? && self.runtime_token_changed?
561       if !runtime_token[0..2] == "v2/"
562         errors.add :runtime_token, "not a v2 token"
563         return
564       end
565       if ApiClientAuthorization.validate(token: runtime_token).nil?
566         errors.add :runtime_token, "failed validation"
567       end
568     end
569   end
570
571   def scrub_secrets
572     if self.state == Final
573       self.secret_mounts = {}
574       self.runtime_token = nil
575     end
576   end
577
578   def update_priority
579     return unless saved_change_to_state? || saved_change_to_priority? || saved_change_to_container_uuid?
580     update_priorities container_uuid_before_last_save if !container_uuid_before_last_save.nil? and container_uuid_before_last_save != self.container_uuid
581     update_priorities self.container_uuid if self.container_uuid
582   end
583
584   def set_requesting_container_uuid
585     if (self.requesting_container_uuid = get_requesting_container_uuid())
586       # Determine the priority of container request for the requesting
587       # container.
588       self.priority = ContainerRequest.where(container_uuid: self.requesting_container_uuid).maximum("priority") || 0
589     end
590   end
591
592   def get_requesting_container_uuid
593     return self.requesting_container_uuid || Container.for_current_token.andand.uuid
594   end
595 end