Merge branch 'master' of git.curoverse.com:arvados into 11876-r-sdk
[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   serialize :properties, Hash
14   serialize :environment, Hash
15   serialize :mounts, Hash
16   serialize :runtime_constraints, Hash
17   serialize :command, Array
18   serialize :scheduling_parameters, Hash
19
20   before_validation :fill_field_defaults, :if => :new_record?
21   before_validation :validate_runtime_constraints
22   before_validation :validate_scheduling_parameters
23   before_validation :set_container
24   validates :command, :container_image, :output_path, :cwd, :presence => true
25   validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
26   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 1000 }
27   validate :validate_state_change
28   validate :check_update_whitelist
29   after_save :update_priority
30   after_save :finalize_if_needed
31   before_create :set_requesting_container_uuid
32   before_destroy :set_priority_zero
33
34   api_accessible :user, extend: :common do |t|
35     t.add :command
36     t.add :container_count
37     t.add :container_count_max
38     t.add :container_image
39     t.add :container_uuid
40     t.add :cwd
41     t.add :description
42     t.add :environment
43     t.add :expires_at
44     t.add :filters
45     t.add :log_uuid
46     t.add :mounts
47     t.add :name
48     t.add :output_name
49     t.add :output_path
50     t.add :output_uuid
51     t.add :output_ttl
52     t.add :priority
53     t.add :properties
54     t.add :requesting_container_uuid
55     t.add :runtime_constraints
56     t.add :scheduling_parameters
57     t.add :state
58     t.add :use_existing
59   end
60
61   # Supported states for a container request
62   States =
63     [
64      (Uncommitted = 'Uncommitted'),
65      (Committed = 'Committed'),
66      (Final = 'Final'),
67     ]
68
69   State_transitions = {
70     nil => [Uncommitted, Committed],
71     Uncommitted => [Committed],
72     Committed => [Final]
73   }
74
75   AttrsPermittedAlways = [:owner_uuid, :state, :name, :description]
76   AttrsPermittedBeforeCommit = [:command, :container_count_max,
77   :container_image, :cwd, :environment, :filters, :mounts,
78   :output_path, :priority, :properties, :requesting_container_uuid,
79   :runtime_constraints, :state, :container_uuid, :use_existing,
80   :scheduling_parameters, :output_name, :output_ttl]
81
82   def self.limit_index_columns_read
83     ["mounts"]
84   end
85
86   def state_transitions
87     State_transitions
88   end
89
90   def skip_uuid_read_permission_check
91     # XXX temporary until permissions are sorted out.
92     %w(modified_by_client_uuid container_uuid requesting_container_uuid)
93   end
94
95   def finalize_if_needed
96     if state == Committed && Container.find_by_uuid(container_uuid).final?
97       reload
98       act_as_system_user do
99         finalize!
100       end
101     end
102   end
103
104   # Finalize the container request after the container has
105   # finished/cancelled.
106   def finalize!
107     out_coll = nil
108     log_coll = nil
109     c = Container.find_by_uuid(container_uuid)
110     ['output', 'log'].each do |out_type|
111       pdh = c.send(out_type)
112       next if pdh.nil?
113       coll_name = "Container #{out_type} for request #{uuid}"
114       trash_at = nil
115       if out_type == 'output'
116         if self.output_name
117           coll_name = self.output_name
118         end
119         if self.output_ttl > 0
120           trash_at = db_current_time + self.output_ttl
121         end
122       end
123       manifest = Collection.unscoped do
124         Collection.where(portable_data_hash: pdh).first.manifest_text
125       end
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_changed? and not current_user.andand.is_admin
243         self.errors.add :state, "of container request can only be set to Final by system."
244       end
245
246       if self.state_was == Committed
247         permitted.push :output_uuid, :log_uuid
248       end
249
250     end
251
252     super(permitted)
253   end
254
255   def update_priority
256     if self.state_changed? or
257         self.priority_changed? or
258         self.container_uuid_changed?
259       act_as_system_user do
260         Container.
261           where('uuid in (?)',
262                 [self.container_uuid_was, self.container_uuid].compact).
263           map(&:update_priority!)
264       end
265     end
266   end
267
268   def set_priority_zero
269     self.update_attributes!(priority: 0) if self.state != Final
270   end
271
272   def set_requesting_container_uuid
273     return !new_record? if self.requesting_container_uuid   # already set
274
275     token_uuid = current_api_client_authorization.andand.uuid
276     container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
277     if container
278       self.requesting_container_uuid = container.uuid
279       self.priority = container.priority
280     end
281     true
282   end
283 end