Merge branch '7709-api-rails4' (partial)
[arvados.git] / services / api / app / models / container.rb
1 require 'whitelist_update'
2 require 'safe_json'
3
4 class Container < ArvadosModel
5   include HasUuid
6   include KindAndEtag
7   include CommonApiTemplate
8   include WhitelistUpdate
9   extend CurrentApiClient
10
11   serialize :environment, Hash
12   serialize :mounts, Hash
13   serialize :runtime_constraints, Hash
14   serialize :command, Array
15   serialize :scheduling_parameters, Hash
16
17   before_validation :fill_field_defaults, :if => :new_record?
18   before_validation :set_timestamps
19   validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
20   validate :validate_state_change
21   validate :validate_change
22   validate :validate_lock
23   validate :validate_output
24   after_validation :assign_auth
25   before_save :sort_serialized_attrs
26   after_save :handle_completed
27
28   has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
29   belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
30
31   api_accessible :user, extend: :common do |t|
32     t.add :command
33     t.add :container_image
34     t.add :cwd
35     t.add :environment
36     t.add :exit_code
37     t.add :finished_at
38     t.add :locked_by_uuid
39     t.add :log
40     t.add :mounts
41     t.add :output
42     t.add :output_path
43     t.add :priority
44     t.add :progress
45     t.add :runtime_constraints
46     t.add :started_at
47     t.add :state
48     t.add :auth_uuid
49     t.add :scheduling_parameters
50   end
51
52   # Supported states for a container
53   States =
54     [
55      (Queued = 'Queued'),
56      (Locked = 'Locked'),
57      (Running = 'Running'),
58      (Complete = 'Complete'),
59      (Cancelled = 'Cancelled')
60     ]
61
62   State_transitions = {
63     nil => [Queued],
64     Queued => [Locked, Cancelled],
65     Locked => [Queued, Running, Cancelled],
66     Running => [Complete, Cancelled]
67   }
68
69   def state_transitions
70     State_transitions
71   end
72
73   def update_priority!
74     if [Queued, Locked, Running].include? self.state
75       # Update the priority of this container to the maximum priority of any of
76       # its committed container requests and save the record.
77       self.priority = ContainerRequest.
78         where(container_uuid: uuid,
79               state: ContainerRequest::Committed).
80         maximum('priority')
81       self.save!
82     end
83   end
84
85   # Create a new container (or find an existing one) to satisfy the
86   # given container request.
87   def self.resolve(req)
88     c_attrs = {
89       command: req.command,
90       cwd: req.cwd,
91       environment: req.environment,
92       output_path: req.output_path,
93       container_image: resolve_container_image(req.container_image),
94       mounts: resolve_mounts(req.mounts),
95       runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
96       scheduling_parameters: req.scheduling_parameters,
97     }
98     act_as_system_user do
99       if req.use_existing && (reusable = find_reusable(c_attrs))
100         reusable
101       else
102         Container.create!(c_attrs)
103       end
104     end
105   end
106
107   # Return a runtime_constraints hash that complies with requested but
108   # is suitable for saving in a container record, i.e., has specific
109   # values instead of ranges.
110   #
111   # Doing this as a step separate from other resolutions, like "git
112   # revision range to commit hash", makes sense only when there is no
113   # opportunity to reuse an existing container (e.g., container reuse
114   # is not implemented yet, or we have already found that no existing
115   # containers are suitable).
116   def self.resolve_runtime_constraints(runtime_constraints)
117     rc = {}
118     defaults = {
119       'keep_cache_ram' =>
120       Rails.configuration.container_default_keep_cache_ram,
121     }
122     defaults.merge(runtime_constraints).each do |k, v|
123       if v.is_a? Array
124         rc[k] = v[0]
125       else
126         rc[k] = v
127       end
128     end
129     rc
130   end
131
132   # Return a mounts hash suitable for a Container, i.e., with every
133   # readonly collection UUID resolved to a PDH.
134   def self.resolve_mounts(mounts)
135     c_mounts = {}
136     mounts.each do |k, mount|
137       mount = mount.dup
138       c_mounts[k] = mount
139       if mount['kind'] != 'collection'
140         next
141       end
142       if (uuid = mount.delete 'uuid')
143         c = Collection.
144           readable_by(current_user).
145           where(uuid: uuid).
146           select(:portable_data_hash).
147           first
148         if !c
149           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
150         end
151         if mount['portable_data_hash'].nil?
152           # PDH not supplied by client
153           mount['portable_data_hash'] = c.portable_data_hash
154         elsif mount['portable_data_hash'] != c.portable_data_hash
155           # UUID and PDH supplied by client, but they don't agree
156           raise ArgumentError.new "cannot mount collection #{uuid.inspect}: current portable_data_hash #{c.portable_data_hash.inspect} does not match #{c['portable_data_hash'].inspect} in request"
157         end
158       end
159     end
160     return c_mounts
161   end
162
163   # Return a container_image PDH suitable for a Container.
164   def self.resolve_container_image(container_image)
165     coll = Collection.for_latest_docker_image(container_image)
166     if !coll
167       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
168     end
169     coll.portable_data_hash
170   end
171
172   def self.find_reusable(attrs)
173     candidates = Container.
174       where_serialized(:command, attrs[:command]).
175       where('cwd = ?', attrs[:cwd]).
176       where_serialized(:environment, attrs[:environment]).
177       where('output_path = ?', attrs[:output_path]).
178       where('container_image = ?', resolve_container_image(attrs[:container_image])).
179       where_serialized(:mounts, resolve_mounts(attrs[:mounts])).
180       where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
181
182     # Check for Completed candidates whose output and log are both readable.
183     select_readable_pdh = Collection.
184       readable_by(current_user).
185       select(:portable_data_hash).
186       to_sql
187     usable = candidates.
188       where(state: Complete).
189       where(exit_code: 0).
190       where("log IN (#{select_readable_pdh})").
191       where("output IN (#{select_readable_pdh})").
192       order('finished_at ASC').
193       limit(1).
194       first
195     return usable if usable
196
197     # Check for Running candidates and return the most likely to finish sooner.
198     running = candidates.where(state: Running).
199       order('progress desc, started_at asc').limit(1).first
200     return running if not running.nil?
201
202     # Check for Locked or Queued ones and return the most likely to start first.
203     locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
204       order('state asc, priority desc, created_at asc').limit(1).first
205     return locked_or_queued if not locked_or_queued.nil?
206
207     # No suitable candidate found.
208     nil
209   end
210
211   def lock
212     with_lock do
213       if self.state == Locked
214         raise AlreadyLockedError
215       end
216       self.state = Locked
217       self.save!
218     end
219   end
220
221   def unlock
222     with_lock do
223       if self.state == Queued
224         raise InvalidStateTransitionError
225       end
226       self.state = Queued
227       self.save!
228     end
229   end
230
231   def self.readable_by(*users_list)
232     if users_list.select { |u| u.is_admin }.any?
233       return self
234     end
235     user_uuids = users_list.map { |u| u.uuid }
236     uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
237     uuid_list.uniq!
238     permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
239     joins(:container_requests).
240       where("container_requests.uuid IN #{permitted} OR "+
241             "container_requests.owner_uuid IN (:uuids)",
242             uuids: uuid_list)
243   end
244
245   def final?
246     [Complete, Cancelled].include?(self.state)
247   end
248
249   protected
250
251   def fill_field_defaults
252     self.state ||= Queued
253     self.environment ||= {}
254     self.runtime_constraints ||= {}
255     self.mounts ||= {}
256     self.cwd ||= "."
257     self.priority ||= 1
258     self.scheduling_parameters ||= {}
259   end
260
261   def permission_to_create
262     current_user.andand.is_admin
263   end
264
265   def permission_to_update
266     # Override base permission check to allow auth_uuid to set progress and
267     # output (only).  Whether it is legal to set progress and output in the current
268     # state has already been checked in validate_change.
269     current_user.andand.is_admin ||
270       (!current_api_client_authorization.nil? and
271        [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
272   end
273
274   def ensure_owner_uuid_is_permitted
275     # Override base permission check to allow auth_uuid to set progress and
276     # output (only).  Whether it is legal to set progress and output in the current
277     # state has already been checked in validate_change.
278     if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
279       check_update_whitelist [:progress, :output]
280     else
281       super
282     end
283   end
284
285   def set_timestamps
286     if self.state_changed? and self.state == Running
287       self.started_at ||= db_current_time
288     end
289
290     if self.state_changed? and [Complete, Cancelled].include? self.state
291       self.finished_at ||= db_current_time
292     end
293   end
294
295   def validate_change
296     permitted = [:state]
297
298     if self.new_record?
299       permitted.push(:owner_uuid, :command, :container_image, :cwd,
300                      :environment, :mounts, :output_path, :priority,
301                      :runtime_constraints, :scheduling_parameters)
302     end
303
304     case self.state
305     when Queued, Locked
306       permitted.push :priority
307
308     when Running
309       permitted.push :priority, :progress, :output
310       if self.state_changed?
311         permitted.push :started_at
312       end
313
314     when Complete
315       if self.state_was == Running
316         permitted.push :finished_at, :output, :log, :exit_code
317       end
318
319     when Cancelled
320       case self.state_was
321       when Running
322         permitted.push :finished_at, :output, :log
323       when Queued, Locked
324         permitted.push :finished_at
325       end
326
327     else
328       # The state_transitions check will add an error message for this
329       return false
330     end
331
332     check_update_whitelist permitted
333   end
334
335   def validate_lock
336     if [Locked, Running].include? self.state
337       # If the Container was already locked, locked_by_uuid must not
338       # changes. Otherwise, the current auth gets the lock.
339       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
340     else
341       need_lock = nil
342     end
343
344     # The caller can provide a new value for locked_by_uuid, but only
345     # if it's exactly what we expect. This allows a caller to perform
346     # an update like {"state":"Unlocked","locked_by_uuid":null}.
347     if self.locked_by_uuid_changed?
348       if self.locked_by_uuid != need_lock
349         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
350       end
351     end
352     self.locked_by_uuid = need_lock
353   end
354
355   def validate_output
356     # Output must exist and be readable by the current user.  This is so
357     # that a container cannot "claim" a collection that it doesn't otherwise
358     # have access to just by setting the output field to the collection PDH.
359     if output_changed?
360       c = Collection.unscoped do
361         Collection.
362             readable_by(current_user).
363             where(portable_data_hash: self.output).
364             first
365       end
366       if !c
367         errors.add :output, "collection must exist and be readable by current user."
368       end
369     end
370   end
371
372   def assign_auth
373     if self.auth_uuid_changed?
374       return errors.add :auth_uuid, 'is readonly'
375     end
376     if not [Locked, Running].include? self.state
377       # don't need one
378       self.auth.andand.update_attributes(expires_at: db_current_time)
379       self.auth = nil
380       return
381     elsif self.auth
382       # already have one
383       return
384     end
385     cr = ContainerRequest.
386       where('container_uuid=? and priority>0', self.uuid).
387       order('priority desc').
388       first
389     if !cr
390       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
391     end
392     self.auth = ApiClientAuthorization.
393       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
394               api_client_id: 0)
395   end
396
397   def sort_serialized_attrs
398     if self.environment_changed?
399       self.environment = self.class.deep_sort_hash(self.environment)
400     end
401     if self.mounts_changed?
402       self.mounts = self.class.deep_sort_hash(self.mounts)
403     end
404     if self.runtime_constraints_changed?
405       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
406     end
407     if self.scheduling_parameters_changed?
408       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
409     end
410   end
411
412   def handle_completed
413     # This container is finished so finalize any associated container requests
414     # that are associated with this container.
415     if self.state_changed? and self.final?
416       act_as_system_user do
417
418         if self.state == Cancelled
419           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
420         else
421           retryable_requests = []
422         end
423
424         if retryable_requests.any?
425           c_attrs = {
426             command: self.command,
427             cwd: self.cwd,
428             environment: self.environment,
429             output_path: self.output_path,
430             container_image: self.container_image,
431             mounts: self.mounts,
432             runtime_constraints: self.runtime_constraints,
433             scheduling_parameters: self.scheduling_parameters
434           }
435           c = Container.create! c_attrs
436           retryable_requests.each do |cr|
437             cr.with_lock do
438               # Use row locking because this increments container_count
439               cr.container_uuid = c.uuid
440               cr.save
441             end
442           end
443         end
444
445         # Notify container requests associated with this container
446         ContainerRequest.where(container_uuid: uuid,
447                                state: ContainerRequest::Committed).each do |cr|
448           cr.finalize!
449         end
450
451         # Try to cancel any outstanding container requests made by this container.
452         ContainerRequest.where(requesting_container_uuid: uuid,
453                                state: ContainerRequest::Committed).each do |cr|
454           cr.priority = 0
455           cr.save
456         end
457       end
458     end
459   end
460
461 end