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