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