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