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