0d8453174e205e85ab3f79e01a32cc530478a4a1
[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       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
252     end
253     coll.portable_data_hash
254   end
255
256   def self.find_reusable(attrs)
257     log_reuse_info { "starting with #{Container.all.count} container records in database" }
258     candidates = Container.where_serialized(:command, attrs[:command], md5: true)
259     log_reuse_info(candidates) { "after filtering on command #{attrs[:command].inspect}" }
260
261     candidates = candidates.where('cwd = ?', attrs[:cwd])
262     log_reuse_info(candidates) { "after filtering on cwd #{attrs[:cwd].inspect}" }
263
264     candidates = candidates.where_serialized(:environment, attrs[:environment], md5: true)
265     log_reuse_info(candidates) { "after filtering on environment #{attrs[:environment].inspect}" }
266
267     candidates = candidates.where('output_path = ?', attrs[:output_path])
268     log_reuse_info(candidates) { "after filtering on output_path #{attrs[:output_path].inspect}" }
269
270     image = resolve_container_image(attrs[:container_image])
271     candidates = candidates.where('container_image = ?', image)
272     log_reuse_info(candidates) { "after filtering on container_image #{image.inspect} (resolved from #{attrs[:container_image].inspect})" }
273
274     candidates = candidates.where_serialized(:mounts, resolve_mounts(attrs[:mounts]), md5: true)
275     log_reuse_info(candidates) { "after filtering on mounts #{attrs[:mounts].inspect}" }
276
277     secret_mounts_md5 = Digest::MD5.hexdigest(SafeJSON.dump(self.deep_sort_hash(attrs[:secret_mounts])))
278     candidates = candidates.where('secret_mounts_md5 = ?', secret_mounts_md5)
279     log_reuse_info(candidates) { "after filtering on secret_mounts_md5 #{secret_mounts_md5.inspect}" }
280
281     candidates = candidates.where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]), md5: true)
282     log_reuse_info(candidates) { "after filtering on runtime_constraints #{attrs[:runtime_constraints].inspect}" }
283
284     candidates = candidates.where('runtime_user_uuid = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
285                                   attrs[:runtime_user_uuid])
286     log_reuse_info(candidates) { "after filtering on runtime_user_uuid #{attrs[:runtime_user_uuid].inspect}" }
287
288     candidates = candidates.where('runtime_auth_scopes = ? or (runtime_user_uuid is NULL and runtime_auth_scopes is NULL)',
289                                   SafeJSON.dump(attrs[:runtime_auth_scopes].sort))
290     log_reuse_info(candidates) { "after filtering on runtime_auth_scopes #{attrs[:runtime_auth_scopes].inspect}" }
291
292     log_reuse_info { "checking for state=Complete with readable output and log..." }
293
294     select_readable_pdh = Collection.
295       readable_by(current_user).
296       select(:portable_data_hash).
297       to_sql
298
299     usable = candidates.where(state: Complete, exit_code: 0)
300     log_reuse_info(usable) { "with state=Complete, exit_code=0" }
301
302     usable = usable.where("log IN (#{select_readable_pdh})")
303     log_reuse_info(usable) { "with readable log" }
304
305     usable = usable.where("output IN (#{select_readable_pdh})")
306     log_reuse_info(usable) { "with readable output" }
307
308     usable = usable.order('finished_at ASC').limit(1).first
309     if usable
310       log_reuse_info { "done, reusing container #{usable.uuid} with state=Complete" }
311       return usable
312     end
313
314     # Check for non-failing Running candidates and return the most likely to finish sooner.
315     log_reuse_info { "checking for state=Running..." }
316     running = candidates.where(state: Running).
317               where("(runtime_status->'error') is null").
318               order('progress desc, started_at asc').
319               limit(1).first
320     if running
321       log_reuse_info { "done, reusing container #{running.uuid} with state=Running" }
322       return running
323     else
324       log_reuse_info { "have no containers in Running state" }
325     end
326
327     # Check for Locked or Queued ones and return the most likely to start first.
328     locked_or_queued = candidates.
329                        where("state IN (?)", [Locked, Queued]).
330                        order('state asc, priority desc, created_at asc').
331                        limit(1).first
332     if locked_or_queued
333       log_reuse_info { "done, reusing container #{locked_or_queued.uuid} with state=#{locked_or_queued.state}" }
334       return locked_or_queued
335     else
336       log_reuse_info { "have no containers in Locked or Queued state" }
337     end
338
339     log_reuse_info { "done, no reusable container found" }
340     nil
341   end
342
343   def check_lock_fail
344     if self.state != Queued
345       raise LockFailedError.new("cannot lock when #{self.state}")
346     elsif self.priority <= 0
347       raise LockFailedError.new("cannot lock when priority<=0")
348     end
349   end
350
351   def lock
352     # Check invalid state transitions once before getting the lock
353     # (because it's cheaper that way) and once after getting the lock
354     # (because state might have changed while acquiring the lock).
355     check_lock_fail
356     transaction do
357       reload
358       check_lock_fail
359       update_attributes!(state: Locked)
360     end
361   end
362
363   def check_unlock_fail
364     if self.state != Locked
365       raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
366     elsif self.locked_by_uuid != current_api_client_authorization.uuid
367       raise InvalidStateTransitionError.new("locked by a different token")
368     end
369   end
370
371   def unlock
372     # Check invalid state transitions twice (see lock)
373     check_unlock_fail
374     transaction do
375       reload(lock: 'FOR UPDATE')
376       check_unlock_fail
377       update_attributes!(state: Queued)
378     end
379   end
380
381   def self.readable_by(*users_list)
382     # Load optional keyword arguments, if they exist.
383     if users_list.last.is_a? Hash
384       kwargs = users_list.pop
385     else
386       kwargs = {}
387     end
388     Container.where(ContainerRequest.readable_by(*users_list).where("containers.uuid = container_requests.container_uuid").exists)
389   end
390
391   def final?
392     [Complete, Cancelled].include?(self.state)
393   end
394
395   def self.for_current_token
396     return if !current_api_client_authorization
397     _, _, _, container_uuid = Thread.current[:token].split('/')
398     if container_uuid.nil?
399       Container.where(auth_uuid: current_api_client_authorization.uuid).first
400     else
401       Container.where('auth_uuid=? or (uuid=? and runtime_token=?)',
402                       current_api_client_authorization.uuid,
403                       container_uuid,
404                       current_api_client_authorization.token).first
405     end
406   end
407
408   protected
409
410   def fill_field_defaults
411     self.state ||= Queued
412     self.environment ||= {}
413     self.runtime_constraints ||= {}
414     self.mounts ||= {}
415     self.cwd ||= "."
416     self.priority ||= 0
417     self.scheduling_parameters ||= {}
418   end
419
420   def permission_to_create
421     current_user.andand.is_admin
422   end
423
424   def ensure_owner_uuid_is_permitted
425     # validate_change ensures owner_uuid can't be changed at all --
426     # except during create, which requires admin privileges. Checking
427     # permission here would be superfluous.
428     true
429   end
430
431   def set_timestamps
432     if self.state_changed? and self.state == Running
433       self.started_at ||= db_current_time
434     end
435
436     if self.state_changed? and [Complete, Cancelled].include? self.state
437       self.finished_at ||= db_current_time
438     end
439   end
440
441   # Check that well-known runtime status keys have desired data types
442   def validate_runtime_status
443     [
444       'error', 'errorDetail', 'warning', 'warningDetail', 'activity'
445     ].each do |k|
446       if self.runtime_status.andand.include?(k) && !self.runtime_status[k].is_a?(String)
447         errors.add(:runtime_status, "'#{k}' value must be a string")
448       end
449     end
450   end
451
452   def validate_change
453     permitted = [:state]
454     progress_attrs = [:progress, :runtime_status, :log, :output]
455     final_attrs = [:exit_code, :finished_at]
456
457     if self.new_record?
458       permitted.push(:owner_uuid, :command, :container_image, :cwd,
459                      :environment, :mounts, :output_path, :priority,
460                      :runtime_constraints, :scheduling_parameters,
461                      :secret_mounts, :runtime_token,
462                      :runtime_user_uuid, :runtime_auth_scopes)
463     end
464
465     case self.state
466     when Locked
467       permitted.push :priority, :runtime_status, :log
468
469     when Queued
470       permitted.push :priority
471
472     when Running
473       permitted.push :priority, *progress_attrs
474       if self.state_changed?
475         permitted.push :started_at
476       end
477
478     when Complete
479       if self.state_was == Running
480         permitted.push *final_attrs, *progress_attrs
481       end
482
483     when Cancelled
484       case self.state_was
485       when Running
486         permitted.push :finished_at, *progress_attrs
487       when Queued, Locked
488         permitted.push :finished_at, :log
489       end
490
491     else
492       # The state_transitions check will add an error message for this
493       return false
494     end
495
496     if current_api_client_authorization.andand.uuid.andand == self.auth_uuid
497       # The contained process itself can update progress indicators,
498       # but can't change priority etc.
499       permitted = permitted & (progress_attrs + final_attrs + [:state] - [:log])
500     elsif self.locked_by_uuid && self.locked_by_uuid != current_api_client_authorization.andand.uuid
501       # When locked, progress fields cannot be updated by the wrong
502       # dispatcher, even though it has admin privileges.
503       permitted = permitted - progress_attrs
504     end
505     check_update_whitelist permitted
506   end
507
508   def validate_lock
509     if [Locked, Running].include? self.state
510       # If the Container was already locked, locked_by_uuid must not
511       # changes. Otherwise, the current auth gets the lock.
512       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
513     else
514       need_lock = nil
515     end
516
517     # The caller can provide a new value for locked_by_uuid, but only
518     # if it's exactly what we expect. This allows a caller to perform
519     # an update like {"state":"Unlocked","locked_by_uuid":null}.
520     if self.locked_by_uuid_changed?
521       if self.locked_by_uuid != need_lock
522         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
523       end
524     end
525     self.locked_by_uuid = need_lock
526   end
527
528   def validate_output
529     # Output must exist and be readable by the current user.  This is so
530     # that a container cannot "claim" a collection that it doesn't otherwise
531     # have access to just by setting the output field to the collection PDH.
532     if output_changed?
533       c = Collection.
534             readable_by(current_user, {include_trash: true}).
535             where(portable_data_hash: self.output).
536             first
537       if !c
538         errors.add :output, "collection must exist and be readable by current user."
539       end
540     end
541   end
542
543   def update_cr_logs
544     # If self.final?, this update is superfluous: the final log/output
545     # update will be done when handle_completed calls finalize! on
546     # each requesting CR.
547     return if self.final? || !self.log_changed?
548     leave_modified_by_user_alone do
549       ContainerRequest.where(container_uuid: self.uuid).each do |cr|
550         cr.update_collections(container: self, collections: ['log'])
551         cr.save!
552       end
553     end
554   end
555
556   def assign_auth
557     if self.auth_uuid_changed?
558          return errors.add :auth_uuid, 'is readonly'
559     end
560     if not [Locked, Running].include? self.state
561       # don't need one
562       self.auth.andand.update_attributes(expires_at: db_current_time)
563       self.auth = nil
564       return
565     elsif self.auth
566       # already have one
567       return
568     end
569     if self.runtime_token.nil?
570       if self.runtime_user_uuid.nil?
571         # legacy behavior, we don't have a runtime_user_uuid so get
572         # the user from the highest priority container request, needed
573         # when performing an upgrade and there are queued containers,
574         # and some tests.
575         cr = ContainerRequest.
576                where('container_uuid=? and priority>0', self.uuid).
577                order('priority desc').
578                first
579         if !cr
580           return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
581         end
582         self.runtime_user_uuid = cr.modified_by_user_uuid
583         self.runtime_auth_scopes = ["all"]
584       end
585
586       # generate a new token
587       self.auth = ApiClientAuthorization.
588                     create!(user_id: User.find_by_uuid(self.runtime_user_uuid).id,
589                             api_client_id: 0,
590                             scopes: self.runtime_auth_scopes)
591     end
592   end
593
594   def sort_serialized_attrs
595     if self.environment_changed?
596       self.environment = self.class.deep_sort_hash(self.environment)
597     end
598     if self.mounts_changed?
599       self.mounts = self.class.deep_sort_hash(self.mounts)
600     end
601     if self.runtime_constraints_changed?
602       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
603     end
604     if self.scheduling_parameters_changed?
605       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
606     end
607     if self.runtime_auth_scopes_changed?
608       self.runtime_auth_scopes = self.runtime_auth_scopes.sort
609     end
610   end
611
612   def update_secret_mounts_md5
613     if self.secret_mounts_changed?
614       self.secret_mounts_md5 = Digest::MD5.hexdigest(
615         SafeJSON.dump(self.class.deep_sort_hash(self.secret_mounts)))
616     end
617   end
618
619   def scrub_secrets
620     # this runs after update_secret_mounts_md5, so the
621     # secret_mounts_md5 will still reflect the secrets that are being
622     # scrubbed here.
623     if self.state_changed? && self.final?
624       self.secret_mounts = {}
625       self.runtime_token = nil
626     end
627   end
628
629   def clear_runtime_status_when_queued
630     # Avoid leaking status messages between different dispatch attempts
631     if self.state_was == Locked && self.state == Queued
632       self.runtime_status = {}
633     end
634   end
635
636   def handle_completed
637     # This container is finished so finalize any associated container requests
638     # that are associated with this container.
639     if self.state_changed? and self.final?
640       act_as_system_user do
641
642         if self.state == Cancelled
643           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
644         else
645           retryable_requests = []
646         end
647
648         if retryable_requests.any?
649           c_attrs = {
650             command: self.command,
651             cwd: self.cwd,
652             environment: self.environment,
653             output_path: self.output_path,
654             container_image: self.container_image,
655             mounts: self.mounts,
656             runtime_constraints: self.runtime_constraints,
657             scheduling_parameters: self.scheduling_parameters,
658             secret_mounts: self.secret_mounts_was,
659             runtime_token: self.runtime_token_was,
660             runtime_user_uuid: self.runtime_user_uuid,
661             runtime_auth_scopes: self.runtime_auth_scopes
662           }
663           c = Container.create! c_attrs
664           retryable_requests.each do |cr|
665             cr.with_lock do
666               leave_modified_by_user_alone do
667                 # Use row locking because this increments container_count
668                 cr.container_uuid = c.uuid
669                 cr.save!
670               end
671             end
672           end
673         end
674
675         # Notify container requests associated with this container
676         ContainerRequest.where(container_uuid: uuid,
677                                state: ContainerRequest::Committed).each do |cr|
678           leave_modified_by_user_alone do
679             cr.finalize!
680           end
681         end
682
683         # Cancel outstanding container requests made by this container.
684         ContainerRequest.
685           includes(:container).
686           where(requesting_container_uuid: uuid,
687                 state: ContainerRequest::Committed).each do |cr|
688           leave_modified_by_user_alone do
689             cr.update_attributes!(priority: 0)
690             cr.container.reload
691             if cr.container.state == Container::Queued || cr.container.state == Container::Locked
692               # If the child container hasn't started yet, finalize the
693               # child CR now instead of leaving it "on hold", i.e.,
694               # Queued with priority 0.  (OTOH, if the child is already
695               # running, leave it alone so it can get cancelled the
696               # usual way, get a copy of the log collection, etc.)
697               cr.update_attributes!(state: ContainerRequest::Final)
698             end
699           end
700         end
701       end
702     end
703   end
704 end