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