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