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