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