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