fb900a993d464e809fd93ce0ecdacdae35995027
[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   validates :command, :container_image, :output_path, :cwd, :priority, { presence: true }
35   validates :priority, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
36   validate :validate_runtime_status
37   validate :validate_state_change
38   validate :validate_change
39   validate :validate_lock
40   validate :validate_output
41   after_validation :assign_auth
42   before_save :sort_serialized_attrs
43   before_save :update_secret_mounts_md5
44   before_save :scrub_secrets
45   before_save :clear_runtime_status_when_queued
46   after_save :update_cr_logs
47   after_save :handle_completed
48   after_save :propagate_priority
49   after_commit { UpdatePriority.run_update_thread }
50
51   has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
52   belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
53
54   api_accessible :user, extend: :common do |t|
55     t.add :command
56     t.add :container_image
57     t.add :cwd
58     t.add :environment
59     t.add :exit_code
60     t.add :finished_at
61     t.add :locked_by_uuid
62     t.add :log
63     t.add :mounts
64     t.add :output
65     t.add :output_path
66     t.add :priority
67     t.add :progress
68     t.add :runtime_constraints
69     t.add :runtime_status
70     t.add :started_at
71     t.add :state
72     t.add :auth_uuid
73     t.add :scheduling_parameters
74     t.add :runtime_user_uuid
75     t.add :runtime_auth_scopes
76   end
77
78   # Supported states for a container
79   States =
80     [
81      (Queued = 'Queued'),
82      (Locked = 'Locked'),
83      (Running = 'Running'),
84      (Complete = 'Complete'),
85      (Cancelled = 'Cancelled')
86     ]
87
88   State_transitions = {
89     nil => [Queued],
90     Queued => [Locked, Cancelled],
91     Locked => [Queued, Running, Cancelled],
92     Running => [Complete, Cancelled]
93   }
94
95   def self.limit_index_columns_read
96     ["mounts"]
97   end
98
99   def self.full_text_searchable_columns
100     super - ["secret_mounts", "secret_mounts_md5", "runtime_token"]
101   end
102
103   def self.searchable_columns *args
104     super - ["secret_mounts_md5", "runtime_token"]
105   end
106
107   def logged_attributes
108     super.except('secret_mounts', 'runtime_token')
109   end
110
111   def state_transitions
112     State_transitions
113   end
114
115   # Container priority is the highest "computed priority" of any
116   # matching request. The computed priority of a container-submitted
117   # request is the priority of the submitting container. The computed
118   # priority of a user-submitted request is a function of
119   # user-assigned priority and request creation time.
120   def update_priority!
121     return if ![Queued, Locked, Running].include?(state)
122     p = ContainerRequest.
123         where('container_uuid=? and priority>0', uuid).
124         includes(:requesting_container).
125         lock(true).
126         map do |cr|
127       if cr.requesting_container
128         cr.requesting_container.priority
129       else
130         (cr.priority << 50) - (cr.created_at.to_time.to_f * 1000).to_i
131       end
132     end.max || 0
133     update_attributes!(priority: p)
134   end
135
136   def propagate_priority
137     return true unless priority_changed?
138     act_as_system_user do
139       # Update the priority of child container requests to match new
140       # priority of the parent container (ignoring requests with no
141       # container assigned, because their priority doesn't matter).
142       ContainerRequest.
143         where(requesting_container_uuid: self.uuid,
144               state: ContainerRequest::Committed).
145         where('container_uuid is not null').
146         includes(:container).
147         map(&:container).
148         map(&:update_priority!)
149     end
150   end
151
152   # Create a new container (or find an existing one) to satisfy the
153   # given container request.
154   def self.resolve(req)
155     if req.runtime_token.nil?
156       runtime_user = if req.modified_by_user_uuid.nil?
157                        current_user
158                      else
159                        User.find_by_uuid(req.modified_by_user_uuid)
160                      end
161       runtime_auth_scopes = ["all"]
162     else
163       auth = ApiClientAuthorization.validate(token: req.runtime_token)
164       if auth.nil?
165         raise ArgumentError.new "Invalid runtime token"
166       end
167       runtime_user = User.find_by_id(auth.user_id)
168       runtime_auth_scopes = auth.scopes
169     end
170     c_attrs = act_as_user runtime_user do
171       {
172         command: req.command,
173         cwd: req.cwd,
174         environment: req.environment,
175         output_path: req.output_path,
176         container_image: resolve_container_image(req.container_image),
177         mounts: resolve_mounts(req.mounts),
178         runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
179         scheduling_parameters: req.scheduling_parameters,
180         secret_mounts: req.secret_mounts,
181         runtime_token: req.runtime_token,
182         runtime_user_uuid: runtime_user.uuid,
183         runtime_auth_scopes: runtime_auth_scopes
184       }
185     end
186     act_as_system_user do
187       if req.use_existing && (reusable = find_reusable(c_attrs))
188         reusable
189       else
190         Container.create!(c_attrs)
191       end
192     end
193   end
194
195   # Return a runtime_constraints hash that complies with requested but
196   # is suitable for saving in a container record, i.e., has specific
197   # values instead of ranges.
198   #
199   # Doing this as a step separate from other resolutions, like "git
200   # revision range to commit hash", makes sense only when there is no
201   # opportunity to reuse an existing container (e.g., container reuse
202   # is not implemented yet, or we have already found that no existing
203   # containers are suitable).
204   def self.resolve_runtime_constraints(runtime_constraints)
205     rc = {}
206     defaults = {
207       'keep_cache_ram' =>
208       Rails.configuration.container_default_keep_cache_ram,
209     }
210     defaults.merge(runtime_constraints).each do |k, v|
211       if v.is_a? Array
212         rc[k] = v[0]
213       else
214         rc[k] = v
215       end
216     end
217     rc
218   end
219
220   # Return a mounts hash suitable for a Container, i.e., with every
221   # readonly collection UUID resolved to a PDH.
222   def self.resolve_mounts(mounts)
223     c_mounts = {}
224     mounts.each do |k, mount|
225       mount = mount.dup
226       c_mounts[k] = mount
227       if mount['kind'] != 'collection'
228         next
229       end
230
231       uuid = mount.delete 'uuid'
232
233       if mount['portable_data_hash'].nil? and !uuid.nil?
234         # PDH not supplied, try by UUID
235         c = Collection.
236           readable_by(current_user).
237           where(uuid: uuid).
238           select(:portable_data_hash).
239           first
240         if !c
241           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
242         end
243         mount['portable_data_hash'] = c.portable_data_hash
244       end
245     end
246     return c_mounts
247   end
248
249   # Return a container_image PDH suitable for a Container.
250   def self.resolve_container_image(container_image)
251     coll = Collection.for_latest_docker_image(container_image)
252     if !coll
253       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
254     end
255     coll.portable_data_hash
256   end
257
258   def self.find_reusable(attrs)
259     log_reuse_info { "starting with #{Container.all.count} container records in database" }
260     candidates = Container.where_serialized(:command, attrs[:command], md5: true)
261     log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
262
263     candidates = candidates.where('cwd = ?', attrs[:cwd])
264     log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
265
266     candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
267     log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
268
269     candidates = candidates.where('output_path = ?', attrs[:output_path])
270     log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
271
272     image = resolve_container_image(attrs[:container_image])
273     candidates = candidates.where('container_image = ?', image)
274     log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
275
276     candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
277     log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
278
279     secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
280     candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
281     log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
282
283     candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
284     log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
285
286     log_reuse_info { "checking for state=Complete with readable output and log..." }
287
288     select_readable_pdh = Collection.
289       readable_by(current_user).
290       select(:portable_data_hash).
291       to_sql
292
293     usable = candidates.where(state: Complete, exit_code: 0)
294     log_reuse_info(usable) { "with state=Complete, exit_code=0" }
295
296     usable = usable.where("log IN (#{select_readable_pdh})")
297     log_reuse_info(usable) { "with readable log" }
298
299     usable = usable.where("output IN (#{select_readable_pdh})")
300     log_reuse_info(usable) { "with readable output" }
301
302     usable = usable.order('finished_at ASC').limit(1).first
303     if usable
304       log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
305       return usable
306     end
307
308     # Check for non-failing Running candidates and return the most likely to finish sooner.
309     log_reuse_info { "checking for state=Running..." }
310     running = candidates.where(state: Running).
311               where("(runtime_status->'error') is null").
312               order('progress desc, started_at asc').
313               limit(1).first
314     if running
315       log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
316       return running
317     else
318       log_reuse_info { "have no containers in Running state" }
319     end
320
321     # Check for Locked or Queued ones and return the most likely to start first.
322     locked_or_queued = candidates.
323                        where("state IN (?)", [Locked, Queued]).
324                        order('state asc, priority desc, created_at asc').
325                        limit(1).first
326     if locked_or_queued
327       log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
328       return locked_or_queued
329     else
330       log_reuse_info { "have no containers in Locked or Queued state" }
331     end
332
333     log_reuse_info { "done, no reusable container found" }
334     nil
335   end
336
337   def check_lock_fail
338     if self.state != Queued
339       raise LockFailedError.new("cannot lock when #{self.state}")
340     elsif self.priority <= 0
341       raise LockFailedError.new("cannot lock when priority<=0")
342     end
343   end
344
345   def lock
346     # Check invalid state transitions once before getting the lock
347     # (because it's cheaper that way) and once after getting the lock
348     # (because state might have changed while acquiring the lock).
349     check_lock_fail
350     transaction do
351       reload
352       check_lock_fail
353       update_attributes!(state: Locked, lock_count: self.lock_count+1)
354     end
355   end
356
357   def check_unlock_fail
358     if self.state != Locked
359       raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
360     elsif self.locked_by_uuid != current_api_client_authorization.uuid
361       raise InvalidStateTransitionError.new("locked by a different token")
362     end
363   end
364
365   def unlock
366     # Check invalid state transitions twice (see lock)
367     check_unlock_fail
368     transaction do
369       reload(lock: 'FOR UPDATE')
370       check_unlock_fail
371       if self.lock_count < Rails.configuration.max_container_dispatch_attempts
372         update_attributes!(state: Queued)
373       else
374         update_attributes!(state: Cancelled,
375                            runtime_status: {
376                              error: "Container exceeded 'max_container_dispatch_attempts' (lock_count=#{self.lock_count}."
377                            })
378       end
379     end
380   end
381
382   def self.readable_by(*users_list)
383     # Load optional keyword arguments, if they exist.
384     if users_list.last.is_a? Hash
385       kwargs = users_list.pop
386     else
387       kwargs = {}
388     end
389     if users_list.select { |u| u.is_admin }.any?
390       return super
391     end
392     Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
393   end
394
395   def final?
396     [Complete, Cancelled].include?(self.state)
397   end
398
399   def self.for_current_token
400     return if !current_api_client_authorization
401     _, _, _, container_uuid = Thread.current[:token].split('/')
402     if container_uuid.nil?
403       Container.where(auth_uuid: current_api_client_authorization.uuid).first
404     else
405       Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
406                       current_api_client_authorization.uuid,
407                       container_uuid,
408                       current_api_client_authorization.token).first
409     end
410   end
411
412   protected
413
414   def fill_field_defaults
415     self.state ||= Queued
416     self.environment ||= {}
417     self.runtime_constraints ||= {}
418     self.mounts ||= {}
419     self.cwd ||= "."
420     self.priority ||= 0
421     self.scheduling_parameters ||= {}
422   end
423
424   def permission_to_create
425     current_user.andand.is_admin
426   end
427
428   def ensure_owner_uuid_is_permitted
429     # validate_change ensures owner_uuid can't be changed at all --
430     # except during create, which requires admin privileges. Checking
431     # permission here would be superfluous.
432     true
433   end
434
435   def set_timestamps
436     if self.state_changed? and self.state == Running
437       self.started_at ||= db_current_time
438     end
439
440     if self.state_changed? and [Complete, Cancelled].include? self.state
441       self.finished_at ||= db_current_time
442     end
443   end
444
445   # Check that well-known runtime status keys have desired data types
446   def validate_runtime_status
447     [
448       'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
449     ].each do |k|
450       if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
451         errors.add(:runtime_status, "'#{k}' value must be a string")
452       end
453     end
454   end
455
456   def validate_change
457     permitted = [:state]
458     progress_attrs = [:progress, :runtime_status, :log, :output]
459     final_attrs = [:exit_code, :finished_at]
460
461     if self.new_record?
462       permitted.push(:owner_uuid, :command, :container_image, :cwd,
463                      :environment, :mounts, :output_path, :priority,
464                      :runtime_constraints, :scheduling_parameters,
465                      :secret_mounts, :runtime_token,
466                      :runtime_user_uuid, :runtime_auth_scopes)
467     end
468
469     case self.state
470     when Locked
471       permitted.push :priority, :runtime_status, :log, :lock_count
472
473     when Queued
474       permitted.push :priority
475
476     when Running
477       permitted.push :priority, *progress_attrs
478       if self.state_changed?
479         permitted.push :started_at
480       end
481
482     when Complete
483       if self.state_was == Running
484         permitted.push *final_attrs, *progress_attrs
485       end
486
487     when Cancelled
488       case self.state_was
489       when Running
490         permitted.push :finished_at, *progress_attrs
491       when Queued, Locked
492         permitted.push :finished_at, :log, :runtime_status
493       end
494
495     else
496       # The state_transitions check will add an error message for this
497       return false
498     end
499
500     if self.state == Running &&
501        !current_api_client_authorization.nil? &&
502        (current_api_client_authorization.uuid == self.auth_uuid ||
503         current_api_client_authorization.token == self.runtime_token)
504       # The contained process itself can write final attrs but can't
505       # change priority or log.
506       permitted.push *final_attrs
507       permitted = permitted - [:log, :priority]
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       act_as_system_user do
649
650         if self.state == Cancelled
651           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
652         else
653           retryable_requests = []
654         end
655
656         if retryable_requests.any?
657           c_attrs = {
658             command: self.command,
659             cwd: self.cwd,
660             environment: self.environment,
661             output_path: self.output_path,
662             container_image: self.container_image,
663             mounts: self.mounts,
664             runtime_constraints: self.runtime_constraints,
665             scheduling_parameters: self.scheduling_parameters,
666             secret_mounts: self.secret_mounts_was,
667             runtime_token: self.runtime_token_was,
668             runtime_user_uuid: self.runtime_user_uuid,
669             runtime_auth_scopes: self.runtime_auth_scopes
670           }
671           c = Container.create! c_attrs
672           retryable_requests.each do |cr|
673             cr.with_lock do
674               leave_modified_by_user_alone do
675                 # Use row locking because this increments container_count
676                 cr.container_uuid = c.uuid
677                 cr.save!
678               end
679             end
680           end
681         end
682
683         # Notify container requests associated with this container
684         ContainerRequest.where(container_uuid: uuid,
685                                state: ContainerRequest::Committed).each do |cr|
686           leave_modified_by_user_alone do
687             cr.finalize!
688           end
689         end
690
691         # Cancel outstanding container requests made by this container.
692         ContainerRequest.
693           includes(:container).
694           where(requesting_container_uuid: uuid,
695                 state: ContainerRequest::Committed).each do |cr|
696           leave_modified_by_user_alone do
697             cr.update_attributes!(priority: 0)
698             cr.container.reload
699             if cr.container.state == Container::Queued || cr.container.state == Container::Locked
700               # If the child container hasn't started yet, finalize the
701               # child CR now instead of leaving it "on hold", i.e.,
702               # Queued with priority 0.  (OTOH, if the child is already
703               # running, leave it alone so it can get cancelled the
704               # usual way, get a copy of the log collection, etc.)
705               cr.update_attributes!(state: ContainerRequest::Final)
706             end
707           end
708         end
709       end
710     end
711   end
712 end