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