11720: Merge branch 'master' into 11720-govendor
[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     transaction do
230       begin
231         reload(lock: 'FOR UPDATE NOWAIT')
232       rescue
233         raise LockFailedError.new("cannot lock: other transaction in progress")
234       end
235       check_lock_fail
236       update_attributes!(state: Locked)
237     end
238   end
239
240   def check_unlock_fail
241     if self.state != Locked
242       raise InvalidStateTransitionError.new("cannot unlock when #{self.state}")
243     elsif self.locked_by_uuid != current_api_client_authorization.uuid
244       raise InvalidStateTransitionError.new("locked by a different token")
245     end
246   end
247
248   def unlock
249     # Check invalid state transitions twice (see lock)
250     check_unlock_fail
251     transaction do
252       reload(lock: 'FOR UPDATE')
253       check_unlock_fail
254       update_attributes!(state: Queued)
255     end
256   end
257
258   def self.readable_by(*users_list)
259     if users_list.select { |u| u.is_admin }.any?
260       return self
261     end
262     user_uuids = users_list.map { |u| u.uuid }
263     uuid_list = user_uuids + users_list.flat_map { |u| u.groups_i_can(:read) }
264     uuid_list.uniq!
265     permitted = "(SELECT head_uuid FROM links WHERE link_class='permission' AND tail_uuid IN (:uuids))"
266     joins(:container_requests).
267       where("container_requests.uuid IN #{permitted} OR "+
268             "container_requests.owner_uuid IN (:uuids)",
269             uuids: uuid_list)
270   end
271
272   def final?
273     [Complete, Cancelled].include?(self.state)
274   end
275
276   protected
277
278   def fill_field_defaults
279     self.state ||= Queued
280     self.environment ||= {}
281     self.runtime_constraints ||= {}
282     self.mounts ||= {}
283     self.cwd ||= "."
284     self.priority ||= 1
285     self.scheduling_parameters ||= {}
286   end
287
288   def permission_to_create
289     current_user.andand.is_admin
290   end
291
292   def permission_to_update
293     # Override base permission check to allow auth_uuid to set progress and
294     # output (only).  Whether it is legal to set progress and output in the current
295     # state has already been checked in validate_change.
296     current_user.andand.is_admin ||
297       (!current_api_client_authorization.nil? and
298        [self.auth_uuid, self.locked_by_uuid].include? current_api_client_authorization.uuid)
299   end
300
301   def ensure_owner_uuid_is_permitted
302     # Override base permission check to allow auth_uuid to set progress and
303     # output (only).  Whether it is legal to set progress and output in the current
304     # state has already been checked in validate_change.
305     if !current_api_client_authorization.nil? and self.auth_uuid == current_api_client_authorization.uuid
306       check_update_whitelist [:progress, :output]
307     else
308       super
309     end
310   end
311
312   def set_timestamps
313     if self.state_changed? and self.state == Running
314       self.started_at ||= db_current_time
315     end
316
317     if self.state_changed? and [Complete, Cancelled].include? self.state
318       self.finished_at ||= db_current_time
319     end
320   end
321
322   def validate_change
323     permitted = [:state]
324
325     if self.new_record?
326       permitted.push(:owner_uuid, :command, :container_image, :cwd,
327                      :environment, :mounts, :output_path, :priority,
328                      :runtime_constraints, :scheduling_parameters)
329     end
330
331     case self.state
332     when Queued, Locked
333       permitted.push :priority
334
335     when Running
336       permitted.push :priority, :progress, :output
337       if self.state_changed?
338         permitted.push :started_at
339       end
340
341     when Complete
342       if self.state_was == Running
343         permitted.push :finished_at, :output, :log, :exit_code
344       end
345
346     when Cancelled
347       case self.state_was
348       when Running
349         permitted.push :finished_at, :output, :log
350       when Queued, Locked
351         permitted.push :finished_at
352       end
353
354     else
355       # The state_transitions check will add an error message for this
356       return false
357     end
358
359     check_update_whitelist permitted
360   end
361
362   def validate_lock
363     if [Locked, Running].include? self.state
364       # If the Container was already locked, locked_by_uuid must not
365       # changes. Otherwise, the current auth gets the lock.
366       need_lock = locked_by_uuid_was || current_api_client_authorization.andand.uuid
367     else
368       need_lock = nil
369     end
370
371     # The caller can provide a new value for locked_by_uuid, but only
372     # if it's exactly what we expect. This allows a caller to perform
373     # an update like {"state":"Unlocked","locked_by_uuid":null}.
374     if self.locked_by_uuid_changed?
375       if self.locked_by_uuid != need_lock
376         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
377       end
378     end
379     self.locked_by_uuid = need_lock
380   end
381
382   def validate_output
383     # Output must exist and be readable by the current user.  This is so
384     # that a container cannot "claim" a collection that it doesn't otherwise
385     # have access to just by setting the output field to the collection PDH.
386     if output_changed?
387       c = Collection.unscoped do
388         Collection.
389             readable_by(current_user).
390             where(portable_data_hash: self.output).
391             first
392       end
393       if !c
394         errors.add :output, "collection must exist and be readable by current user."
395       end
396     end
397   end
398
399   def assign_auth
400     if self.auth_uuid_changed?
401       return errors.add :auth_uuid, 'is readonly'
402     end
403     if not [Locked, Running].include? self.state
404       # don't need one
405       self.auth.andand.update_attributes(expires_at: db_current_time)
406       self.auth = nil
407       return
408     elsif self.auth
409       # already have one
410       return
411     end
412     cr = ContainerRequest.
413       where('container_uuid=? and priority>0', self.uuid).
414       order('priority desc').
415       first
416     if !cr
417       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
418     end
419     self.auth = ApiClientAuthorization.
420       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
421               api_client_id: 0)
422   end
423
424   def sort_serialized_attrs
425     if self.environment_changed?
426       self.environment = self.class.deep_sort_hash(self.environment)
427     end
428     if self.mounts_changed?
429       self.mounts = self.class.deep_sort_hash(self.mounts)
430     end
431     if self.runtime_constraints_changed?
432       self.runtime_constraints = self.class.deep_sort_hash(self.runtime_constraints)
433     end
434     if self.scheduling_parameters_changed?
435       self.scheduling_parameters = self.class.deep_sort_hash(self.scheduling_parameters)
436     end
437   end
438
439   def handle_completed
440     # This container is finished so finalize any associated container requests
441     # that are associated with this container.
442     if self.state_changed? and self.final?
443       act_as_system_user do
444
445         if self.state == Cancelled
446           retryable_requests = ContainerRequest.where("container_uuid = ? and priority > 0 and state = 'Committed' and container_count < container_count_max", uuid)
447         else
448           retryable_requests = []
449         end
450
451         if retryable_requests.any?
452           c_attrs = {
453             command: self.command,
454             cwd: self.cwd,
455             environment: self.environment,
456             output_path: self.output_path,
457             container_image: self.container_image,
458             mounts: self.mounts,
459             runtime_constraints: self.runtime_constraints,
460             scheduling_parameters: self.scheduling_parameters
461           }
462           c = Container.create! c_attrs
463           retryable_requests.each do |cr|
464             cr.with_lock do
465               # Use row locking because this increments container_count
466               cr.container_uuid = c.uuid
467               cr.save
468             end
469           end
470         end
471
472         # Notify container requests associated with this container
473         ContainerRequest.where(container_uuid: uuid,
474                                state: ContainerRequest::Committed).each do |cr|
475           cr.finalize!
476         end
477
478         # Try to cancel any outstanding container requests made by this container.
479         ContainerRequest.where(requesting_container_uuid: uuid,
480                                state: ContainerRequest::Committed).each do |cr|
481           cr.priority = 0
482           cr.save
483         end
484       end
485     end
486   end
487
488 end