11546: Avoid loading/saving non-essential fields in /arvados/v1/containers/lock.
[arvados.git] / services / api / app / models / container.rb
1 require 'whitelist_update'
2 require 'safe_json'
3
4 class Container < ArvadosModel
5   include HasUuid
6   include KindAndEtag
7   include CommonApiTemplate
8   include WhitelistUpdate
9   extend CurrentApiClient
10   extend DbCurrentTime
11
12   serialize :environment, Hash
13   serialize :mounts, Hash
14   serialize :runtime_constraints, Hash
15   serialize :command, Array
16   serialize :scheduling_parameters, Hash
17
18   before_validation :fill_field_defaults, :if => :new_record?
19   before_validation :set_timestamps
20   validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
21   validate :validate_state_change
22   validate :validate_change
23   validate :validate_lock
24   validate :validate_output
25   after_validation :assign_auth
26   before_save :sort_serialized_attrs
27   after_save :handle_completed
28
29   has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
30   belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
31
32   api_accessible :user, extend: :common do |t|
33     t.add :command
34     t.add :container_image
35     t.add :cwd
36     t.add :environment
37     t.add :exit_code
38     t.add :finished_at
39     t.add :locked_by_uuid
40     t.add :log
41     t.add :mounts
42     t.add :output
43     t.add :output_path
44     t.add :priority
45     t.add :progress
46     t.add :runtime_constraints
47     t.add :started_at
48     t.add :state
49     t.add :auth_uuid
50     t.add :scheduling_parameters
51   end
52
53   # Supported states for a container
54   States =
55     [
56      (Queued = 'Queued'),
57      (Locked = 'Locked'),
58      (Running = 'Running'),
59      (Complete = 'Complete'),
60      (Cancelled = 'Cancelled')
61     ]
62
63   State_transitions = {
64     nil => [Queued],
65     Queued => [Locked, Cancelled],
66     Locked => [Queued, Running, Cancelled],
67     Running => [Complete, Cancelled]
68   }
69
70   def self.limit_index_columns_read
71     ["mounts"]
72   end
73
74   def state_transitions
75     State_transitions
76   end
77
78   def update_priority!
79     if [Queued, Locked, Running].include? self.state
80       # Update the priority of this container to the maximum priority of any of
81       # its committed container requests and save the record.
82       self.priority = ContainerRequest.
83         where(container_uuid: uuid,
84               state: ContainerRequest::Committed).
85         maximum('priority')
86       self.save!
87     end
88   end
89
90   # Create a new container (or find an existing one) to satisfy the
91   # given container request.
92   def self.resolve(req)
93     c_attrs = {
94       command: req.command,
95       cwd: req.cwd,
96       environment: req.environment,
97       output_path: req.output_path,
98       container_image: resolve_container_image(req.container_image),
99       mounts: resolve_mounts(req.mounts),
100       runtime_constraints: resolve_runtime_constraints(req.runtime_constraints),
101       scheduling_parameters: req.scheduling_parameters,
102     }
103     act_as_system_user do
104       if req.use_existing && (reusable = find_reusable(c_attrs))
105         reusable
106       else
107         Container.create!(c_attrs)
108       end
109     end
110   end
111
112   # Return a runtime_constraints hash that complies with requested but
113   # is suitable for saving in a container record, i.e., has specific
114   # values instead of ranges.
115   #
116   # Doing this as a step separate from other resolutions, like "git
117   # revision range to commit hash", makes sense only when there is no
118   # opportunity to reuse an existing container (e.g., container reuse
119   # is not implemented yet, or we have already found that no existing
120   # containers are suitable).
121   def self.resolve_runtime_constraints(runtime_constraints)
122     rc = {}
123     defaults = {
124       'keep_cache_ram' =>
125       Rails.configuration.container_default_keep_cache_ram,
126     }
127     defaults.merge(runtime_constraints).each do |k, v|
128       if v.is_a? Array
129         rc[k] = v[0]
130       else
131         rc[k] = v
132       end
133     end
134     rc
135   end
136
137   # Return a mounts hash suitable for a Container, i.e., with every
138   # readonly collection UUID resolved to a PDH.
139   def self.resolve_mounts(mounts)
140     c_mounts = {}
141     mounts.each do |k, mount|
142       mount = mount.dup
143       c_mounts[k] = mount
144       if mount['kind'] != 'collection'
145         next
146       end
147       if (uuid = mount.delete 'uuid')
148         c = Collection.
149           readable_by(current_user).
150           where(uuid: uuid).
151           select(:portable_data_hash).
152           first
153         if !c
154           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
155         end
156         if mount['portable_data_hash'].nil?
157           # PDH not supplied by client
158           mount['portable_data_hash'] = c.portable_data_hash
159         elsif mount['portable_data_hash'] != c.portable_data_hash
160           # UUID and PDH supplied by client, but they don't agree
161           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"
162         end
163       end
164     end
165     return c_mounts
166   end
167
168   # Return a container_image PDH suitable for a Container.
169   def self.resolve_container_image(container_image)
170     coll = Collection.for_latest_docker_image(container_image)
171     if !coll
172       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
173     end
174     coll.portable_data_hash
175   end
176
177   def self.find_reusable(attrs)
178     candidates = Container.
179       where_serialized(:command, attrs[:command]).
180       where('cwd = ?', attrs[:cwd]).
181       where_serialized(:environment, attrs[:environment]).
182       where('output_path = ?', attrs[:output_path]).
183       where('container_image = ?', resolve_container_image(attrs[:container_image])).
184       where_serialized(:mounts, resolve_mounts(attrs[:mounts])).
185       where_serialized(:runtime_constraints, resolve_runtime_constraints(attrs[:runtime_constraints]))
186
187     # Check for Completed candidates whose output and log are both readable.
188     select_readable_pdh = Collection.
189       readable_by(current_user).
190       select(:portable_data_hash).
191       to_sql
192     usable = candidates.
193       where(state: Complete).
194       where(exit_code: 0).
195       where("log IN (#{select_readable_pdh})").
196       where("output IN (#{select_readable_pdh})").
197       order('finished_at ASC').
198       limit(1).
199       first
200     return usable if usable
201
202     # Check for Running candidates and return the most likely to finish sooner.
203     running = candidates.where(state: Running).
204       order('progress desc, started_at asc').limit(1).first
205     return running if not running.nil?
206
207     # Check for Locked or Queued ones and return the most likely to start first.
208     locked_or_queued = candidates.where("state IN (?)", [Locked, Queued]).
209       order('state asc, priority desc, created_at asc').limit(1).first
210     return locked_or_queued if not locked_or_queued.nil?
211
212     # No suitable candidate found.
213     nil
214   end
215
216   def check_lock_fail
217     if self.state != Queued
218       raise LockFailedError.new("cannot lock when #{self.state}")
219     elsif self.priority <= 0
220       raise LockFailedError.new("cannot lock when priority<=0")
221     end
222   end
223
224   def lock
225     # Check invalid state transitions once before getting the lock
226     # (because it's cheaper that way) and once after getting the lock
227     # (because state might have changed while acquiring the lock).
228     check_lock_fail
229     begin
230       reload(lock: 'FOR UPDATE NOWAIT')
231     rescue
232       raise LockFailedError.new("cannot lock: other transaction in progress")
233     end
234     check_lock_fail
235     update_attributes!(state: Locked)
236   end
237
238   def check_unlock_fail
239     if self.state != Locked
240       raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
241     elsif self.locked_by_uuid != current_api_client_authorization.uuid
242       raise InvalidStateTransitionError.new("locked by a different token")
243     end
244   end
245
246   def unlock
247     # Check invalid state transitions twice (see lock)
248     check_unlock_fail
249     reload(lock: 'FOR UPDATE')
250     check_unlock_fail
251     update_attributes!(state: Queued)
252   end
253
254   def self.readable_by(*users_list)
255     if users_list.select { |u| u.is_admin }.any?
256       return self
257     end
258     user_uuids = users_list.map { |u| u.uuid }
259     uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
260     uuid_list.uniq!
261     permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
262     joins(:container_requests).
263       where("container_requests.uuid IN #{permitted} OR "+
264             "container_requests.owner_uuid IN (:uuids)",
265             uuids: uuid_list)
266   end
267
268   def final?
269     [Complete, Cancelled].include?(self.state)
270   end
271
272   protected
273
274   def fill_field_defaults
275     self.state ||= Queued
276     self.environment ||= {}
277     self.runtime_constraints ||= {}
278     self.mounts ||= {}
279     self.cwd ||= "."
280     self.priority ||= 1
281     self.scheduling_parameters ||= {}
282   end
283
284   def permission_to_create
285     current_user.andand.is_admin
286   end
287
288   def permission_to_update
289     # Override base permission check to allow auth_uuid to set progress and
290     # output (only).  Whether it is legal to set progress and output in the current
291     # state has already been checked in validate_change.
292     current_user.andand.is_admin ||
293       (!current_api_client_authorization.nil? and
294        [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
295   end
296
297   def ensure_owner_uuid_is_permitted
298     # Override base permission check to allow auth_uuid to set progress and
299     # output (only).  Whether it is legal to set progress and output in the current
300     # state has already been checked in validate_change.
301     if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
302       check_update_whitelist [:progress, :output]
303     else
304       super
305     end
306   end
307
308   def set_timestamps
309     if self.state_changed? and self.state == Running
310       self.started_at ||= db_current_time
311     end
312
313     if self.state_changed? and [Complete, Cancelled].include? self.state
314       self.finished_at ||= db_current_time
315     end
316   end
317
318   def validate_change
319     permitted = [:state]
320
321     if self.new_record?
322       permitted.push(:owner_uuid, :command, :container_image, :cwd,
323                      :environment, :mounts, :output_path, :priority,
324                      :runtime_constraints, :scheduling_parameters)
325     end
326
327     case self.state
328     when Queued, Locked
329       permitted.push :priority
330
331     when Running
332       permitted.push :priority, :progress, :output
333       if self.state_changed?
334         permitted.push :started_at
335       end
336
337     when Complete
338       if self.state_was == Running
339         permitted.push :finished_at, :output, :log, :exit_code
340       end
341
342     when Cancelled
343       case self.state_was
344       when Running
345         permitted.push :finished_at, :output, :log
346       when Queued, Locked
347         permitted.push :finished_at
348       end
349
350     else
351       # The state_transitions check will add an error message for this
352       return false
353     end
354
355     check_update_whitelist permitted
356   end
357
358   def validate_lock
359     if [Locked, Running].include? self.state
360       # If the Container was already locked, locked_by_uuid must not
361       # changes. Otherwise, the current auth gets the lock.
362       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
363     else
364       need_lock = nil
365     end
366
367     # The caller can provide a new value for locked_by_uuid, but only
368     # if it's exactly what we expect. This allows a caller to perform
369     # an update like {"state":"Unlocked","locked_by_uuid":null}.
370     if self.locked_by_uuid_changed?
371       if self.locked_by_uuid != need_lock
372         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
373       end
374     end
375     self.locked_by_uuid = need_lock
376   end
377
378   def validate_output
379     # Output must exist and be readable by the current user.  This is so
380     # that a container cannot "claim" a collection that it doesn't otherwise
381     # have access to just by setting the output field to the collection PDH.
382     if output_changed?
383       c = Collection.unscoped do
384         Collection.
385             readable_by(current_user).
386             where(portable_data_hash: self.output).
387             first
388       end
389       if !c
390         errors.add :output, "collection must exist and be readable by current user."
391       end
392     end
393   end
394
395   def assign_auth
396     if self.auth_uuid_changed?
397       return errors.add :auth_uuid, 'is readonly'
398     end
399     if not [Locked, Running].include? self.state
400       # don't need one
401       self.auth.andand.update_attributes(expires_at: db_current_time)
402       self.auth = nil
403       return
404     elsif self.auth
405       # already have one
406       return
407     end
408     cr = ContainerRequest.
409       where('container_uuid=? and priority>0', self.uuid).
410       order('priority desc').
411       first
412     if !cr
413       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
414     end
415     self.auth = ApiClientAuthorization.
416       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
417               api_client_id: 0)
418   end
419
420   def sort_serialized_attrs
421     if self.environment_changed?
422       self.environment = self.class.deep_sort_hash(self.environment)
423     end
424     if self.mounts_changed?
425       self.mounts = self.class.deep_sort_hash(self.mounts)
426     end
427     if self.runtime_constraints_changed?
428       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
429     end
430     if self.scheduling_parameters_changed?
431       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
432     end
433   end
434
435   def handle_completed
436     # This container is finished so finalize any associated container requests
437     # that are associated with this container.
438     if self.state_changed? and self.final?
439       act_as_system_user do
440
441         if self.state == Cancelled
442           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
443         else
444           retryable_requests = []
445         end
446
447         if retryable_requests.any?
448           c_attrs = {
449             command: self.command,
450             cwd: self.cwd,
451             environment: self.environment,
452             output_path: self.output_path,
453             container_image: self.container_image,
454             mounts: self.mounts,
455             runtime_constraints: self.runtime_constraints,
456             scheduling_parameters: self.scheduling_parameters
457           }
458           c = Container.create! c_attrs
459           retryable_requests.each do |cr|
460             cr.with_lock do
461               # Use row locking because this increments container_count
462               cr.container_uuid = c.uuid
463               cr.save
464             end
465           end
466         end
467
468         # Notify container requests associated with this container
469         ContainerRequest.where(container_uuid: uuid,
470                                state: ContainerRequest::Committed).each do |cr|
471           cr.finalize!
472         end
473
474         # Try to cancel any outstanding container requests made by this container.
475         ContainerRequest.where(requesting_container_uuid: uuid,
476                                state: ContainerRequest::Committed).each do |cr|
477           cr.priority = 0
478           cr.save
479         end
480       end
481     end
482   end
483
484 end