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