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