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