10666: Version report formatting fixes on some missing tools
[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     Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
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, :log
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