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