Merge branch '20468-installer-perf-knobs'. Closes #20468
[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_priorities'
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   # Posgresql JSONB columns should NOT be declared as serialized, Rails 5
21   # already know how to properly treat them.
22   attribute :secret_mounts, :jsonbHash, default: {}
23   attribute :runtime_status, :jsonbHash, default: {}
24   attribute :runtime_auth_scopes, :jsonbArray, default: []
25   attribute :output_storage_classes, :jsonbArray, default: lambda { Rails.configuration.DefaultStorageClasses }
26   attribute :output_properties, :jsonbHash, default: {}
27
28   serialize :environment, Hash
29   serialize :mounts, Hash
30   serialize :runtime_constraints, Hash
31   serialize :command, Array
32   serialize :scheduling_parameters, Hash
33
34   after_find :fill_container_defaults_after_find
35   before_validation :fill_field_defaults, :if => :new_record?
36   before_validation :set_timestamps
37   before_validation :check_lock
38   before_validation :check_unlock
39   validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
40   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
41   validate :validate_runtime_status
42   validate :validate_state_change
43   validate :validate_change
44   validate :validate_lock
45   validate :validate_output
46   after_validation :assign_auth
47   before_save :sort_serialized_attrs
48   before_save :update_secret_mounts_md5
49   before_save :scrub_secrets
50   before_save :clear_runtime_status_when_queued
51   after_save :update_cr_logs
52   after_save :handle_completed
53
54   has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
55   belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
56
57   api_accessible :user, extend: :common do |t|
58     t.add :command
59     t.add :container_image
60     t.add :cwd
61     t.add :environment
62     t.add :exit_code
63     t.add :finished_at
64     t.add :locked_by_uuid
65     t.add :log
66     t.add :mounts
67     t.add :output
68     t.add :output_path
69     t.add :priority
70     t.add :progress
71     t.add :runtime_constraints
72     t.add :runtime_status
73     t.add :started_at
74     t.add :state
75     t.add :auth_uuid
76     t.add :scheduling_parameters
77     t.add :runtime_user_uuid
78     t.add :runtime_auth_scopes
79     t.add :lock_count
80     t.add :gateway_address
81     t.add :interactive_session_started
82     t.add :output_storage_classes
83     t.add :output_properties
84     t.add :cost
85     t.add :subrequests_cost
86   end
87
88   # Supported states for a container
89   States =
90     [
91      (Queued = 'Queued'),
92      (Locked = 'Locked'),
93      (Running = 'Running'),
94      (Complete = 'Complete'),
95      (Cancelled = 'Cancelled')
96     ]
97
98   State_transitions = {
99     nil => [Queued],
100     Queued => [Locked, Cancelled],
101     Locked => [Queued, Running, Cancelled],
102     Running => [Complete, Cancelled],
103     Complete => [Cancelled]
104   }
105
106   def self.limit_index_columns_read
107     ["mounts"]
108   end
109
110   def self.full_text_searchable_columns
111     super - ["secret_mounts", "secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
112   end
113
114   def self.searchable_columns *args
115     super - ["secret_mounts_md5", "runtime_token", "gateway_address", "output_storage_classes"]
116   end
117
118   def logged_attributes
119     super.except('secret_mounts', 'runtime_token')
120   end
121
122   def state_transitions
123     State_transitions
124   end
125
126   # Container priority is the highest "computed priority" of any
127   # matching request. The computed priority of a container-submitted
128   # request is the priority of the submitting container. The computed
129   # priority of a user-submitted request is a function of
130   # user-assigned priority and request creation time.
131   def update_priority!
132     update_priorities uuid
133     reload
134   end
135
136   # Create a new container (or find an existing one) to satisfy the
137   # given container request.
138   def self.resolve(req)
139     if req.runtime_token.nil?
140       runtime_user = if req.modified_by_user_uuid.nil?
141                        current_user
142                      else
143                        User.find_by_uuid(req.modified_by_user_uuid)
144                      end
145       runtime_auth_scopes = ["all"]
146     else
147       auth = ApiClientAuthorization.validate(token: req.runtime_token)
148       if auth.nil?
149         raise ArgumentError.new "Invalid runtime token"
150       end
151       runtime_user = User.find_by_id(auth.user_id)
152       runtime_auth_scopes = auth.scopes
153     end
154     c_attrs = act_as_user runtime_user do
155       {
156         command: req.command,
157         cwd: req.cwd,
158         environment: req.environment,
159         output_path: req.output_path,
160         container_image: resolve_container_image(req.container_image),
161         mounts: resolve_mounts(req.mounts),
162         runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
163         scheduling_parameters: req.scheduling_parameters,
164         secret_mounts: req.secret_mounts,
165         runtime_token: req.runtime_token,
166         runtime_user_uuid: runtime_user.uuid,
167         runtime_auth_scopes: runtime_auth_scopes,
168         output_storage_classes: req.output_storage_classes,
169       }
170     end
171     act_as_system_user do
172       if req.use_existing && (reusable = find_reusable(c_attrs))
173         reusable
174       else
175         Container.create!(c_attrs)
176       end
177     end
178   end
179
180   # Return a runtime_constraints hash that complies with requested but
181   # is suitable for saving in a container record, i.e., has specific
182   # values instead of ranges.
183   #
184   # Doing this as a step separate from other resolutions, like "git
185   # revision range to commit hash", makes sense only when there is no
186   # opportunity to reuse an existing container (e.g., container reuse
187   # is not implemented yet, or we have already found that no existing
188   # containers are suitable).
189   def self.resolve_runtime_constraints(runtime_constraints)
190     rc = {}
191     runtime_constraints.each do |k, v|
192       if v.is_a? Array
193         rc[k] = v[0]
194       else
195         rc[k] = v
196       end
197     end
198     if rc['keep_cache_ram'] == 0
199       rc['keep_cache_ram'] = Rails.configuration.Containers.DefaultKeepCacheRAM
200     end
201     if rc['keep_cache_disk'] == 0 and rc['keep_cache_ram'] == 0
202       rc['keep_cache_disk'] = bound_keep_cache_disk(rc['ram'])
203     end
204     rc
205   end
206
207   # Return a mounts hash suitable for a Container, i.e., with every
208   # readonly collection UUID resolved to a PDH.
209   def self.resolve_mounts(mounts)
210     c_mounts = {}
211     mounts.each do |k, mount|
212       mount = mount.dup
213       c_mounts[k] = mount
214       if mount['kind'] != 'collection'
215         next
216       end
217
218       uuid = mount.delete 'uuid'
219
220       if mount['portable_data_hash'].nil? and !uuid.nil?
221         # PDH not supplied, try by UUID
222         c = Collection.
223           readable_by(current_user).
224           where(uuid: uuid).
225           select(:portable_data_hash).
226           first
227         if !c
228           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
229         end
230         mount['portable_data_hash'] = c.portable_data_hash
231       end
232     end
233     return c_mounts
234   end
235
236   # Return a container_image PDH suitable for a Container.
237   def self.resolve_container_image(container_image)
238     coll = Collection.for_latest_docker_image(container_image)
239     if !coll
240       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
241     end
242     coll.portable_data_hash
243   end
244
245   def self.find_reusable(attrs)
246     log_reuse_info { "starting with #{Container.all.count} container records in database" }
247     candidates = Container.where_serialized(:command, attrs[:command], md5: true)
248     log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
249
250     candidates = candidates.where('cwd = ?', attrs[:cwd])
251     log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
252
253     candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
254     log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
255
256     candidates = candidates.where('output_path = ?', attrs[:output_path])
257     log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
258
259     image = resolve_container_image(attrs[:container_image])
260     candidates = candidates.where('container_image = ?', image)
261     log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
262
263     candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
264     log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
265
266     secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
267     candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
268     log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
269
270     resolved_runtime_constraints = resolve_runtime_constraints(attrs[:runtime_constraints])
271     # Ideally we would completely ignore Keep cache constraints when making
272     # reuse considerations, but our database structure makes that impractical.
273     # The best we can do is generate a search that matches on all likely values.
274     runtime_constraint_variations = {
275       keep_cache_disk: [
276         # Check for constraints without keep_cache_disk
277         # (containers that predate the constraint)
278         nil,
279         # Containers that use keep_cache_ram instead
280         0,
281         # The default value
282         bound_keep_cache_disk(resolved_runtime_constraints['ram']),
283         # The minimum default bound
284         bound_keep_cache_disk(0),
285         # The maximum default bound (presumably)
286         bound_keep_cache_disk(1 << 60),
287         # The requested value
288         resolved_runtime_constraints.delete('keep_cache_disk'),
289       ].uniq,
290       keep_cache_ram: [
291         # Containers that use keep_cache_disk instead
292         0,
293         # The default value
294         Rails.configuration.Containers.DefaultKeepCacheRAM,
295         # The requested value
296         resolved_runtime_constraints.delete('keep_cache_ram'),
297       ].uniq,
298     }
299     resolved_cuda = resolved_runtime_constraints['cuda']
300     if resolved_cuda.nil? or resolved_cuda['device_count'] == 0
301       runtime_constraint_variations[:cuda] = [
302         # Check for constraints without cuda
303         # (containers that predate the constraint)
304         nil,
305         # The default "don't need CUDA" value
306         {
307           'device_count' => 0,
308           'driver_version' => '',
309           'hardware_capability' => '',
310         },
311         # The requested value
312         resolved_runtime_constraints.delete('cuda')
313       ].uniq
314     end
315     reusable_runtime_constraints = hash_product(runtime_constraint_variations)
316                                      .map { |v| resolved_runtime_constraints.merge(v) }
317
318     candidates = candidates.where_serialized(:runtime_constraints, reusable_runtime_constraints, md5: true, multivalue: true)
319     log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
320
321     log_reuse_info { "checking for state=Complete with readable output and log..." }
322
323     select_readable_pdh = Collection.
324       readable_by(current_user).
325       select(:portable_data_hash).
326       to_sql
327
328     usable = candidates.where(state: Complete, exit_code: 0)
329     log_reuse_info(usable) { "with state=Complete, exit_code=0" }
330
331     usable = usable.where("log IN (#{select_readable_pdh})")
332     log_reuse_info(usable) { "with readable log" }
333
334     usable = usable.where("output IN (#{select_readable_pdh})")
335     log_reuse_info(usable) { "with readable output" }
336
337     usable = usable.order('finished_at ASC').limit(1).first
338     if usable
339       log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
340       return usable
341     end
342
343     # Check for non-failing Running candidates and return the most likely to finish sooner.
344     log_reuse_info { "checking for state=Running..." }
345     running = candidates.where(state: Running).
346               where("(runtime_status->'error') is null").
347               order('progress desc, started_at asc').
348               limit(1).first
349     if running
350       log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
351       return running
352     else
353       log_reuse_info { "have no containers in Running state" }
354     end
355
356     # Check for Locked or Queued ones and return the most likely to start first.
357     locked_or_queued = candidates.
358                        where("state IN (?)", [Locked, Queued]).
359                        order('state asc, priority desc, created_at asc').
360                        limit(1).first
361     if locked_or_queued
362       log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
363       return locked_or_queued
364     else
365       log_reuse_info { "have no containers in Locked or Queued state" }
366     end
367
368     log_reuse_info { "done, no reusable container found" }
369     nil
370   end
371
372   def lock
373     self.with_lock do
374       if self.state != Queued
375         raise LockFailedError.new("cannot lock when #{self.state}")
376       end
377       self.update_attributes!(state: Locked)
378     end
379   end
380
381   def check_lock
382     if state_was == Queued and state == Locked
383       if self.priority <= 0
384         raise LockFailedError.new("cannot lock when priority<=0")
385       end
386       self.lock_count = self.lock_count+1
387     end
388   end
389
390   def unlock
391     self.with_lock do
392       if self.state != Locked
393         raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
394       end
395       self.update_attributes!(state: Queued)
396     end
397   end
398
399   def check_unlock
400     if state_was == Locked and state == Queued
401       if self.locked_by_uuid != current_api_client_authorization.uuid
402         raise ArvadosModel::PermissionDeniedError.new("locked by a different token")
403       end
404       if self.lock_count >= Rails.configuration.Containers.MaxDispatchAttempts
405         self.state = Cancelled
406         self.runtime_status = {error: "Failed to start container.  Cancelled after exceeding 'Containers.MaxDispatchAttempts' (lock_count=#{self.lock_count})"}
407       end
408     end
409   end
410
411   def self.readable_by(*users_list)
412     # Load optional keyword arguments, if they exist.
413     if users_list.last.is_a? Hash
414       kwargs = users_list.pop
415     else
416       kwargs = {}
417     end
418     if users_list.select { |u| u.is_admin }.any?
419       return super
420     end
421     Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").arel.exists)
422   end
423
424   def final?
425     [Complete, Cancelled].include?(self.state)
426   end
427
428   def self.for_current_token
429     return if !current_api_client_authorization
430     _, _, _, container_uuid = Thread.current[:token].split('/')
431     if container_uuid.nil?
432       Container.where(auth_uuid: current_api_client_authorization.uuid).first
433     else
434       Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
435                       current_api_client_authorization.uuid,
436                       container_uuid,
437                       current_api_client_authorization.token).first
438     end
439   end
440
441   protected
442
443   def self.bound_keep_cache_disk(value)
444     value ||= 0
445     min_value = 2 << 30
446     max_value = 32 << 30
447     if value < min_value
448       min_value
449     elsif value > max_value
450       max_value
451     else
452       value
453     end
454   end
455
456   def self.hash_product(**kwargs)
457     # kwargs is a hash that maps parameters to an array of values.
458     # This function enumerates every possible hash where each key has one of
459     # the values from its array.
460     # The output keys are strings since that's what container hash attributes
461     # want.
462     # A nil value yields a hash without that key.
463     [[:_, nil]].product(
464       *kwargs.map { |(key, values)| [key.to_s].product(values) },
465     ).map { |param_pairs| Hash[param_pairs].compact }
466   end
467
468   def fill_field_defaults
469     self.state ||= Queued
470     self.environment ||= {}
471     self.runtime_constraints ||= {}
472     self.mounts ||= {}
473     self.cwd ||= "."
474     self.priority ||= 0
475     self.scheduling_parameters ||= {}
476   end
477
478   def permission_to_create
479     current_user.andand.is_admin
480   end
481
482   def permission_to_destroy
483     current_user.andand.is_admin
484   end
485
486   def ensure_owner_uuid_is_permitted
487     # validate_change ensures owner_uuid can't be changed at all --
488     # except during create, which requires admin privileges. Checking
489     # permission here would be superfluous.
490     true
491   end
492
493   def set_timestamps
494     if self.state_changed? and self.state == Running
495       self.started_at ||= db_current_time
496     end
497
498     if self.state_changed? and [Complete, Cancelled].include? self.state
499       self.finished_at ||= db_current_time
500     end
501   end
502
503   # Check that well-known runtime status keys have desired data types
504   def validate_runtime_status
505     [
506       'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
507     ].each do |k|
508       if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
509         errors.add(:runtime_status, "'#{k}' value must be a string")
510       end
511     end
512   end
513
514   def validate_change
515     permitted = [:state]
516     final_attrs = [:finished_at]
517     progress_attrs = [:progress, :runtime_status, :subrequests_cost, :cost,
518                       :log, :output, :output_properties, :exit_code]
519
520     if self.new_record?
521       permitted.push(:owner_uuid, :command, :container_image, :cwd,
522                      :environment, :mounts, :output_path, :priority,
523                      :runtime_constraints, :scheduling_parameters,
524                      :secret_mounts, :runtime_token,
525                      :runtime_user_uuid, :runtime_auth_scopes,
526                      :output_storage_classes)
527     end
528
529     case self.state
530     when Locked
531       permitted.push :priority, :runtime_status, :log, :lock_count
532
533     when Queued
534       permitted.push :priority
535
536     when Running
537       permitted.push :priority, :output_properties, :gateway_address, *progress_attrs
538       if self.state_changed?
539         permitted.push :started_at
540       end
541       if !self.interactive_session_started_was
542         permitted.push :interactive_session_started
543       end
544
545     when Complete
546       if self.state_was == Running
547         permitted.push *final_attrs, *progress_attrs
548       end
549
550     when Cancelled
551       case self.state_was
552       when Running
553         permitted.push :finished_at, *progress_attrs
554       when Queued, Locked
555         permitted.push :finished_at, :log, :runtime_status, :cost
556       end
557
558     else
559       # The state_transitions check will add an error message for this
560       return false
561     end
562
563     if self.state_was == Running &&
564        !current_api_client_authorization.nil? &&
565        (current_api_client_authorization.uuid == self.auth_uuid ||
566         current_api_client_authorization.token == self.runtime_token)
567       # The contained process itself can write final attrs but can't
568       # change priority or log.
569       permitted.push *final_attrs
570       permitted = permitted - [:log, :priority]
571     elsif !current_user.andand.is_admin
572       raise PermissionDeniedError
573     elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
574       # When locked, progress fields cannot be updated by the wrong
575       # dispatcher, even though it has admin privileges.
576       permitted = permitted - progress_attrs
577     end
578     check_update_whitelist permitted
579   end
580
581   def validate_lock
582     if [Locked, Running].include? self.state
583       # If the Container was already locked, locked_by_uuid must not
584       # changes. Otherwise, the current auth gets the lock.
585       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
586     else
587       need_lock = nil
588     end
589
590     # The caller can provide a new value for locked_by_uuid, but only
591     # if it's exactly what we expect. This allows a caller to perform
592     # an update like {"state":"Unlocked","locked_by_uuid":null}.
593     if self.locked_by_uuid_changed?
594       if self.locked_by_uuid != need_lock
595         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
596       end
597     end
598     self.locked_by_uuid = need_lock
599   end
600
601   def validate_output
602     # Output must exist and be readable by the current user.  This is so
603     # that a container cannot "claim" a collection that it doesn't otherwise
604     # have access to just by setting the output field to the collection PDH.
605     if output_changed?
606       c = Collection.
607             readable_by(current_user, {include_trash: true}).
608             where(portable_data_hash: self.output).
609             first
610       if !c
611         errors.add :output, "collection must exist and be readable by current user."
612       end
613     end
614   end
615
616   def update_cr_logs
617     # If self.final?, this update is superfluous: the final log/output
618     # update will be done when handle_completed calls finalize! on
619     # each requesting CR.
620     return if self.final? || !saved_change_to_log?
621     leave_modified_by_user_alone do
622       ContainerRequest.where(container_uuid: self.uuid, state: ContainerRequest::Committed).each do |cr|
623         cr.update_collections(container: self, collections: ['log'])
624         cr.save!
625       end
626     end
627   end
628
629   def assign_auth
630     if self.auth_uuid_changed?
631          return errors.add :auth_uuid, 'is readonly'
632     end
633     if not [Locked, Running].include? self.state
634       # Don't need one. If auth already exists, expire it.
635       #
636       # We use db_transaction_time here (not db_current_time) to
637       # ensure the token doesn't validate later in the same
638       # transaction (e.g., in a test case) by satisfying expires_at >
639       # transaction timestamp.
640       self.auth.andand.update_attributes(expires_at: db_transaction_time)
641       self.auth = nil
642       return
643     elsif self.auth
644       # already have one
645       return
646     end
647     if self.runtime_token.nil?
648       if self.runtime_user_uuid.nil?
649         # legacy behavior, we don't have a runtime_user_uuid so get
650         # the user from the highest priority container request, needed
651         # when performing an upgrade and there are queued containers,
652         # and some tests.
653         cr = ContainerRequest.
654                where('container_uuid=? and priority>0', self.uuid).
655                order('priority desc').
656                first
657         if !cr
658           return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
659         end
660         self.runtime_user_uuid = cr.modified_by_user_uuid
661         self.runtime_auth_scopes = ["all"]
662       end
663
664       # Generate a new token. This runs with admin credentials as it's done by a
665       # dispatcher user, so expires_at isn't enforced by API.MaxTokenLifetime.
666       self.auth = ApiClientAuthorization.
667                     create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
668                             api_client_id: 0,
669                             scopes: self.runtime_auth_scopes)
670     end
671   end
672
673   def sort_serialized_attrs
674     if self.environment_changed?
675       self.environment = self.class.deep_sort_hash(self.environment)
676     end
677     if self.mounts_changed?
678       self.mounts = self.class.deep_sort_hash(self.mounts)
679     end
680     if self.runtime_constraints_changed?
681       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
682     end
683     if self.scheduling_parameters_changed?
684       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
685     end
686     if self.runtime_auth_scopes_changed?
687       self.runtime_auth_scopes = self.runtime_auth_scopes.sort
688     end
689   end
690
691   def update_secret_mounts_md5
692     if self.secret_mounts_changed?
693       self.secret_mounts_md5 = Digest::MD5.hexdigest(
694         SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
695     end
696   end
697
698   def scrub_secrets
699     # this runs after update_secret_mounts_md5, so the
700     # secret_mounts_md5 will still reflect the secrets that are being
701     # scrubbed here.
702     if self.state_changed? && self.final?
703       self.secret_mounts = {}
704       self.runtime_token = nil
705     end
706   end
707
708   def clear_runtime_status_when_queued
709     # Avoid leaking status messages between different dispatch attempts
710     if self.state_was == Locked && self.state == Queued
711       self.runtime_status = {}
712     end
713   end
714
715   def handle_completed
716     # This container is finished so finalize any associated container requests
717     # that are associated with this container.
718     if saved_change_to_state? and self.final?
719       # These get wiped out by with_lock (which reloads the record),
720       # so record them now in case we need to schedule a retry.
721       prev_secret_mounts = secret_mounts_before_last_save
722       prev_runtime_token = runtime_token_before_last_save
723
724       # Need to take a lock on the container to ensure that any
725       # concurrent container requests that might try to reuse this
726       # container will block until the container completion
727       # transaction finishes.  This ensure that concurrent container
728       # requests that try to reuse this container are finalized (on
729       # Complete) or don't reuse it (on Cancelled).
730       self.with_lock do
731         act_as_system_user do
732           if self.state == Cancelled
733             retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
734           else
735             retryable_requests = []
736           end
737
738           if retryable_requests.any?
739             scheduling_parameters = {
740               # partitions: empty if any are empty, else the union of all parameters
741               "partitions": retryable_requests
742                               .map { |req| req.scheduling_parameters["partitions"] || [] }
743                               .reduce { |cur, new| (cur.empty? or new.empty?) ? [] : (cur | new) },
744
745               # preemptible: true if all are true, else false
746               "preemptible": retryable_requests
747                                .map { |req| req.scheduling_parameters["preemptible"] }
748                                .all?,
749
750               # supervisor: true if all any true, else false
751               "supervisor": retryable_requests
752                                .map { |req| req.scheduling_parameters["supervisor"] }
753                                .any?,
754
755               # max_run_time: 0 if any are 0 (unlimited), else the maximum
756               "max_run_time": retryable_requests
757                                 .map { |req| req.scheduling_parameters["max_run_time"] || 0 }
758                                 .reduce do |cur, new|
759                 if cur == 0 or new == 0
760                   0
761                 elsif new > cur
762                   new
763                 else
764                   cur
765                 end
766               end,
767             }
768
769             c_attrs = {
770               command: self.command,
771               cwd: self.cwd,
772               environment: self.environment,
773               output_path: self.output_path,
774               container_image: self.container_image,
775               mounts: self.mounts,
776               runtime_constraints: self.runtime_constraints,
777               scheduling_parameters: scheduling_parameters,
778               secret_mounts: prev_secret_mounts,
779               runtime_token: prev_runtime_token,
780               runtime_user_uuid: self.runtime_user_uuid,
781               runtime_auth_scopes: self.runtime_auth_scopes
782             }
783             c = Container.create! c_attrs
784             retryable_requests.each do |cr|
785               cr.with_lock do
786                 leave_modified_by_user_alone do
787                   # Use row locking because this increments container_count
788                   cr.cumulative_cost += self.cost + self.subrequests_cost
789                   cr.container_uuid = c.uuid
790                   cr.save!
791                 end
792               end
793             end
794           end
795
796           # Notify container requests associated with this container
797           ContainerRequest.where(container_uuid: uuid,
798                                  state: ContainerRequest::Committed).each do |cr|
799             leave_modified_by_user_alone do
800               cr.finalize!
801             end
802           end
803
804           # Cancel outstanding container requests made by this container.
805           ContainerRequest.
806             where(requesting_container_uuid: uuid,
807                   state: ContainerRequest::Committed).
808             in_batches(of: 15).each_record do |cr|
809             leave_modified_by_user_alone do
810               cr.set_priority_zero
811               container_state = Container.where(uuid: cr.container_uuid).pluck(:state).first
812               if container_state == Container::Queued || container_state == Container::Locked
813                 # If the child container hasn't started yet, finalize the
814                 # child CR now instead of leaving it "on hold", i.e.,
815                 # Queued with priority 0.  (OTOH, if the child is already
816                 # running, leave it alone so it can get cancelled the
817                 # usual way, get a copy of the log collection, etc.)
818                 cr.update_attributes!(state: ContainerRequest::Final)
819               end
820             end
821           end
822         end
823       end
824     end
825   end
826 end