Merge branch '8784-dir-listings'
[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     if users_list.select { |u| u.is_admin }.any?
301       return self
302     end
303     user_uuids = users_list.map { |u| u.uuid }
304     uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
305     uuid_list.uniq!
306     permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
307     joins(:container_requests).
308       where("container_requests.uuid IN #{permitted} OR "+
309             "container_requests.owner_uuid IN (:uuids)",
310             uuids: uuid_list)
311   end
312
313   def final?
314     [Complete, Cancelled].include?(self.state)
315   end
316
317   protected
318
319   def fill_field_defaults
320     self.state ||= Queued
321     self.environment ||= {}
322     self.runtime_constraints ||= {}
323     self.mounts ||= {}
324     self.cwd ||= "."
325     self.priority ||= 1
326     self.scheduling_parameters ||= {}
327   end
328
329   def permission_to_create
330     current_user.andand.is_admin
331   end
332
333   def permission_to_update
334     # Override base permission check to allow auth_uuid to set progress and
335     # output (only).  Whether it is legal to set progress and output in the current
336     # state has already been checked in validate_change.
337     current_user.andand.is_admin ||
338       (!current_api_client_authorization.nil? and
339        [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
340   end
341
342   def ensure_owner_uuid_is_permitted
343     # Override base permission check to allow auth_uuid to set progress and
344     # output (only).  Whether it is legal to set progress and output in the current
345     # state has already been checked in validate_change.
346     if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
347       check_update_whitelist [:progress, :output]
348     else
349       super
350     end
351   end
352
353   def set_timestamps
354     if self.state_changed? and self.state == Running
355       self.started_at ||= db_current_time
356     end
357
358     if self.state_changed? and [Complete, Cancelled].include? self.state
359       self.finished_at ||= db_current_time
360     end
361   end
362
363   def validate_change
364     permitted = [:state]
365
366     if self.new_record?
367       permitted.push(:owner_uuid, :command, :container_image, :cwd,
368                      :environment, :mounts, :output_path, :priority,
369                      :runtime_constraints, :scheduling_parameters)
370     end
371
372     case self.state
373     when Queued, Locked
374       permitted.push :priority
375
376     when Running
377       permitted.push :priority, :progress, :output
378       if self.state_changed?
379         permitted.push :started_at
380       end
381
382     when Complete
383       if self.state_was == Running
384         permitted.push :finished_at, :output, :log, :exit_code
385       end
386
387     when Cancelled
388       case self.state_was
389       when Running
390         permitted.push :finished_at, :output, :log
391       when Queued, Locked
392         permitted.push :finished_at
393       end
394
395     else
396       # The state_transitions check will add an error message for this
397       return false
398     end
399
400     check_update_whitelist permitted
401   end
402
403   def validate_lock
404     if [Locked, Running].include? self.state
405       # If the Container was already locked, locked_by_uuid must not
406       # changes. Otherwise, the current auth gets the lock.
407       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
408     else
409       need_lock = nil
410     end
411
412     # The caller can provide a new value for locked_by_uuid, but only
413     # if it's exactly what we expect. This allows a caller to perform
414     # an update like {"state":"Unlocked","locked_by_uuid":null}.
415     if self.locked_by_uuid_changed?
416       if self.locked_by_uuid != need_lock
417         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
418       end
419     end
420     self.locked_by_uuid = need_lock
421   end
422
423   def validate_output
424     # Output must exist and be readable by the current user.  This is so
425     # that a container cannot "claim" a collection that it doesn't otherwise
426     # have access to just by setting the output field to the collection PDH.
427     if output_changed?
428       c = Collection.unscoped do
429         Collection.
430             readable_by(current_user).
431             where(portable_data_hash: self.output).
432             first
433       end
434       if !c
435         errors.add :output, "collection must exist and be readable by current user."
436       end
437     end
438   end
439
440   def assign_auth
441     if self.auth_uuid_changed?
442       return errors.add :auth_uuid, 'is readonly'
443     end
444     if not [Locked, Running].include? self.state
445       # don't need one
446       self.auth.andand.update_attributes(expires_at: db_current_time)
447       self.auth = nil
448       return
449     elsif self.auth
450       # already have one
451       return
452     end
453     cr = ContainerRequest.
454       where('container_uuid=? and priority>0', self.uuid).
455       order('priority desc').
456       first
457     if !cr
458       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
459     end
460     self.auth = ApiClientAuthorization.
461       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
462               api_client_id: 0)
463   end
464
465   def sort_serialized_attrs
466     if self.environment_changed?
467       self.environment = self.class.deep_sort_hash(self.environment)
468     end
469     if self.mounts_changed?
470       self.mounts = self.class.deep_sort_hash(self.mounts)
471     end
472     if self.runtime_constraints_changed?
473       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
474     end
475     if self.scheduling_parameters_changed?
476       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
477     end
478   end
479
480   def handle_completed
481     # This container is finished so finalize any associated container requests
482     # that are associated with this container.
483     if self.state_changed? and self.final?
484       act_as_system_user do
485
486         if self.state == Cancelled
487           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
488         else
489           retryable_requests = []
490         end
491
492         if retryable_requests.any?
493           c_attrs = {
494             command: self.command,
495             cwd: self.cwd,
496             environment: self.environment,
497             output_path: self.output_path,
498             container_image: self.container_image,
499             mounts: self.mounts,
500             runtime_constraints: self.runtime_constraints,
501             scheduling_parameters: self.scheduling_parameters
502           }
503           c = Container.create! c_attrs
504           retryable_requests.each do |cr|
505             cr.with_lock do
506               # Use row locking because this increments container_count
507               cr.container_uuid = c.uuid
508               cr.save
509             end
510           end
511         end
512
513         # Notify container requests associated with this container
514         ContainerRequest.where(container_uuid: uuid,
515                                state: ContainerRequest::Committed).each do |cr|
516           cr.finalize!
517         end
518
519         # Try to cancel any outstanding container requests made by this container.
520         ContainerRequest.where(requesting_container_uuid: uuid,
521                                state: ContainerRequest::Committed).each do |cr|
522           cr.priority = 0
523           cr.save
524         end
525       end
526     end
527   end
528
529 end