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