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