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