7478: Replaces term 'preemptable' with 'preemptible'
[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
7 class ContainerRequest < ArvadosModel
8   include ArvadosModelUpdates
9   include HasUuid
10   include KindAndEtag
11   include CommonApiTemplate
12   include WhitelistUpdate
13
14   belongs_to :container, foreign_key: :container_uuid, primary_key: :uuid
15   belongs_to :requesting_container, {
16                class_name: 'Container',
17                foreign_key: :requesting_container_uuid,
18                primary_key: :uuid,
19              }
20
21   serialize :properties, Hash
22   serialize :environment, Hash
23   serialize :mounts, Hash
24   serialize :runtime_constraints, Hash
25   serialize :command, Array
26   serialize :scheduling_parameters, Hash
27   serialize :secret_mounts, Hash
28
29   before_validation :fill_field_defaults, :if => :new_record?
30   before_validation :validate_runtime_constraints
31   before_validation :set_container
32   before_validation :set_default_preemptible_scheduling_parameter
33   validates :command, :container_image, :output_path, :cwd, :presence => true
34   validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
35   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
36   validate :validate_scheduling_parameters
37   validate :validate_state_change
38   validate :check_update_whitelist
39   validate :secret_mounts_key_conflict
40   before_save :scrub_secret_mounts
41   before_create :set_requesting_container_uuid
42   before_destroy :set_priority_zero
43   after_save :update_priority
44   after_save :finalize_if_needed
45
46   api_accessible :user, extend: :common do |t|
47     t.add :command
48     t.add :container_count
49     t.add :container_count_max
50     t.add :container_image
51     t.add :container_uuid
52     t.add :cwd
53     t.add :description
54     t.add :environment
55     t.add :expires_at
56     t.add :filters
57     t.add :log_uuid
58     t.add :mounts
59     t.add :name
60     t.add :output_name
61     t.add :output_path
62     t.add :output_uuid
63     t.add :output_ttl
64     t.add :priority
65     t.add :properties
66     t.add :requesting_container_uuid
67     t.add :runtime_constraints
68     t.add :scheduling_parameters
69     t.add :state
70     t.add :use_existing
71   end
72
73   # Supported states for a container request
74   States =
75     [
76      (Uncommitted = 'Uncommitted'),
77      (Committed = 'Committed'),
78      (Final = 'Final'),
79     ]
80
81   State_transitions = {
82     nil => [Uncommitted, Committed],
83     Uncommitted => [Committed],
84     Committed => [Final]
85   }
86
87   AttrsPermittedAlways = [:owner_uuid, :state, :name, :description, :properties]
88   AttrsPermittedBeforeCommit = [:command, :container_count_max,
89   :container_image, :cwd, :environment, :filters, :mounts,
90   :output_path, :priority,
91   :runtime_constraints, :state, :container_uuid, :use_existing,
92   :scheduling_parameters, :secret_mounts, :output_name, :output_ttl]
93
94   def self.limit_index_columns_read
95     ["mounts"]
96   end
97
98   def logged_attributes
99     super.except('secret_mounts')
100   end
101
102   def state_transitions
103     State_transitions
104   end
105
106   def skip_uuid_read_permission_check
107     # XXX temporary until permissions are sorted out.
108     %w(modified_by_client_uuid container_uuid requesting_container_uuid)
109   end
110
111   def finalize_if_needed
112     if state == Committed && Container.find_by_uuid(container_uuid).final?
113       reload
114       act_as_system_user do
115         leave_modified_by_user_alone do
116           finalize!
117         end
118       end
119     end
120   end
121
122   # Finalize the container request after the container has
123   # finished/cancelled.
124   def finalize!
125     out_coll = nil
126     log_coll = nil
127     c = Container.find_by_uuid(container_uuid)
128     ['output', 'log'].each do |out_type|
129       pdh = c.send(out_type)
130       next if pdh.nil?
131       coll_name = "Container #{out_type} for request #{uuid}"
132       trash_at = nil
133       if out_type == 'output'
134         if self.output_name
135           coll_name = self.output_name
136         end
137         if self.output_ttl > 0
138           trash_at = db_current_time + self.output_ttl
139         end
140       end
141       manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
142
143       coll = Collection.new(owner_uuid: owner_uuid,
144                             manifest_text: manifest,
145                             portable_data_hash: pdh,
146                             name: coll_name,
147                             trash_at: trash_at,
148                             delete_at: trash_at,
149                             properties: {
150                               'type' => out_type,
151                               'container_request' => uuid,
152                             })
153       coll.save_with_unique_name!
154       if out_type == 'output'
155         out_coll = coll.uuid
156       else
157         log_coll = coll.uuid
158       end
159     end
160     update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)
161   end
162
163   def self.full_text_searchable_columns
164     super - ["mounts", "secret_mounts", "secret_mounts_md5"]
165   end
166
167   protected
168
169   def fill_field_defaults
170     self.state ||= Uncommitted
171     self.environment ||= {}
172     self.runtime_constraints ||= {}
173     self.mounts ||= {}
174     self.cwd ||= "."
175     self.container_count_max ||= Rails.configuration.container_count_max
176     self.scheduling_parameters ||= {}
177     self.output_ttl ||= 0
178     self.priority ||= 0
179   end
180
181   def set_container
182     if (container_uuid_changed? and
183         not current_user.andand.is_admin and
184         not container_uuid.nil?)
185       errors.add :container_uuid, "can only be updated to nil."
186       return false
187     end
188     if state_changed? and state == Committed and container_uuid.nil?
189       self.container_uuid = Container.resolve(self).uuid
190     end
191     if self.container_uuid != self.container_uuid_was
192       if self.container_count_changed?
193         errors.add :container_count, "cannot be updated directly."
194         return false
195       else
196         self.container_count += 1
197       end
198     end
199   end
200
201   def set_default_preemptible_scheduling_parameter
202     if self.state == Committed
203       # If preemptible instances (eg: AWS Spot Instances) are allowed,
204       # ask them on child containers by default.
205       if Rails.configuration.preemptible_instances and
206         !self.requesting_container_uuid.nil? and
207         self.scheduling_parameters['preemptible'].nil?
208           self.scheduling_parameters['preemptible'] = true
209       end
210     end
211   end
212
213   def validate_runtime_constraints
214     case self.state
215     when Committed
216       [['vcpus', true],
217        ['ram', true],
218        ['keep_cache_ram', false]].each do |k, required|
219         if !required && !runtime_constraints.include?(k)
220           next
221         end
222         v = runtime_constraints[k]
223         unless (v.is_a?(Integer) && v > 0)
224           errors.add(:runtime_constraints,
225                      "[#{k}]=#{v.inspect} must be a positive integer")
226         end
227       end
228     end
229   end
230
231   def validate_scheduling_parameters
232     if self.state == Committed
233       if scheduling_parameters.include? 'partitions' and
234          (!scheduling_parameters['partitions'].is_a?(Array) ||
235           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
236             scheduling_parameters['partitions'].size)
237             errors.add :scheduling_parameters, "partitions must be an array of strings"
238       end
239       if !Rails.configuration.preemptible_instances and scheduling_parameters['preemptible']
240         errors.add :scheduling_parameters, "preemptible instances are not allowed"
241       end
242     end
243   end
244
245   def check_update_whitelist
246     permitted = AttrsPermittedAlways.dup
247
248     if self.new_record? || self.state_was == Uncommitted
249       # Allow create-and-commit in a single operation.
250       permitted.push(*AttrsPermittedBeforeCommit)
251     end
252
253     case self.state
254     when Committed
255       permitted.push :priority, :container_count_max, :container_uuid
256
257       if self.container_uuid.nil?
258         self.errors.add :container_uuid, "has not been resolved to a container."
259       end
260
261       if self.priority.nil?
262         self.errors.add :priority, "cannot be nil"
263       end
264
265       # Allow container count to increment by 1
266       if (self.container_uuid &&
267           self.container_uuid != self.container_uuid_was &&
268           self.container_count == 1 + (self.container_count_was || 0))
269         permitted.push :container_count
270       end
271
272     when Final
273       if self.state_was == Committed
274         # "Cancel" means setting priority=0, state=Committed
275         permitted.push :priority
276
277         if current_user.andand.is_admin
278           permitted.push :output_uuid, :log_uuid
279         end
280       end
281
282     end
283
284     super(permitted)
285   end
286
287   def secret_mounts_key_conflict
288     secret_mounts.each do |k, v|
289       if mounts.has_key?(k)
290         errors.add(:secret_mounts, 'conflict with non-secret mounts')
291         return false
292       end
293     end
294   end
295
296   def scrub_secret_mounts
297     if self.state == Final
298       self.secret_mounts = {}
299     end
300   end
301
302   def update_priority
303     return unless state_changed? || priority_changed? || container_uuid_changed?
304     act_as_system_user do
305       Container.
306         where('uuid in (?)', [self.container_uuid_was, self.container_uuid].compact).
307         map(&:update_priority!)
308     end
309   end
310
311   def set_priority_zero
312     self.update_attributes!(priority: 0) if self.state != Final
313   end
314
315   def set_requesting_container_uuid
316     return if !current_api_client_authorization
317     if (c = Container.where('auth_uuid=?', current_api_client_authorization.uuid).select([:uuid, :priority]).first)
318       self.requesting_container_uuid = c.uuid
319       self.priority = c.priority>0 ? 1 : 0
320     end
321   end
322 end