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