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