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