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