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