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