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