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