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