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