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