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