Merge branch '8128-crunch2-auth-api'
[arvados.git] / services / api / app / models / container.rb
1 require 'whitelist_update'
2
3 class Container < ArvadosModel
4   include HasUuid
5   include KindAndEtag
6   include CommonApiTemplate
7   include WhitelistUpdate
8
9   serialize :environment, Hash
10   serialize :mounts, Hash
11   serialize :runtime_constraints, Hash
12   serialize :command, Array
13
14   before_validation :fill_field_defaults, :if => :new_record?
15   before_validation :set_timestamps
16   validates :command, :container_image, :output_path, :cwd, :priority, :presence => true
17   validate :validate_state_change
18   validate :validate_change
19   validate :validate_lock
20   after_validation :assign_auth
21   after_save :handle_completed
22
23   has_many :container_requests, :foreign_key => :container_uuid, :class_name => 'ContainerRequest', :primary_key => :uuid
24   belongs_to :auth, :class_name => 'ApiClientAuthorization', :foreign_key => :auth_uuid, :primary_key => :uuid
25
26   api_accessible :user, extend: :common do |t|
27     t.add :command
28     t.add :container_image
29     t.add :cwd
30     t.add :environment
31     t.add :exit_code
32     t.add :finished_at
33     t.add :locked_by_uuid
34     t.add :log
35     t.add :mounts
36     t.add :output
37     t.add :output_path
38     t.add :priority
39     t.add :progress
40     t.add :runtime_constraints
41     t.add :started_at
42     t.add :state
43     t.add :auth_uuid
44   end
45
46   # Supported states for a container
47   States =
48     [
49      (Queued = 'Queued'),
50      (Locked = 'Locked'),
51      (Running = 'Running'),
52      (Complete = 'Complete'),
53      (Cancelled = 'Cancelled')
54     ]
55
56   State_transitions = {
57     nil => [Queued],
58     Queued => [Locked, Cancelled],
59     Locked => [Queued, Running, Cancelled],
60     Running => [Complete, Cancelled]
61   }
62
63   def state_transitions
64     State_transitions
65   end
66
67   def update_priority!
68     if [Queued, Locked, Running].include? self.state
69       # Update the priority of this container to the maximum priority of any of
70       # its committed container requests and save the record.
71       self.priority = ContainerRequest.
72         where(container_uuid: uuid,
73               state: ContainerRequest::Committed).
74         maximum('priority')
75       self.save!
76     end
77   end
78
79   protected
80
81   def fill_field_defaults
82     self.state ||= Queued
83     self.environment ||= {}
84     self.runtime_constraints ||= {}
85     self.mounts ||= {}
86     self.cwd ||= "."
87     self.priority ||= 1
88   end
89
90   def permission_to_create
91     current_user.andand.is_admin
92   end
93
94   def permission_to_update
95     current_user.andand.is_admin
96   end
97
98   def set_timestamps
99     if self.state_changed? and self.state == Running
100       self.started_at ||= db_current_time
101     end
102
103     if self.state_changed? and [Complete, Cancelled].include? self.state
104       self.finished_at ||= db_current_time
105     end
106   end
107
108   def validate_change
109     permitted = [:state]
110
111     if self.new_record?
112       permitted.push(:owner_uuid, :command, :container_image, :cwd,
113                      :environment, :mounts, :output_path, :priority,
114                      :runtime_constraints)
115     end
116
117     case self.state
118     when Queued, Locked
119       permitted.push :priority
120
121     when Running
122       permitted.push :priority, :progress
123       if self.state_changed?
124         permitted.push :started_at
125       end
126
127     when Complete
128       if self.state_was == Running
129         permitted.push :finished_at, :output, :log, :exit_code
130       end
131
132     when Cancelled
133       case self.state_was
134       when Running
135         permitted.push :finished_at, :output, :log
136       when Queued, Locked
137         permitted.push :finished_at
138       end
139
140     else
141       # The state_transitions check will add an error message for this
142       return false
143     end
144
145     check_update_whitelist permitted
146   end
147
148   def validate_lock
149     # If the Container is already locked by someone other than the
150     # current api_client_auth, disallow all changes -- except
151     # priority, which needs to change to reflect max(priority) of
152     # relevant ContainerRequests.
153     if locked_by_uuid_was
154       if locked_by_uuid_was != Thread.current[:api_client_authorization].uuid
155         check_update_whitelist [:priority]
156       end
157     end
158
159     if [Locked, Running].include? self.state
160       # If the Container was already locked, locked_by_uuid must not
161       # changes. Otherwise, the current auth gets the lock.
162       need_lock = locked_by_uuid_was || Thread.current[:api_client_authorization].uuid
163     else
164       need_lock = nil
165     end
166
167     # The caller can provide a new value for locked_by_uuid, but only
168     # if it's exactly what we expect. This allows a caller to perform
169     # an update like {"state":"Unlocked","locked_by_uuid":null}.
170     if self.locked_by_uuid_changed?
171       if self.locked_by_uuid != need_lock
172         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
173       end
174     end
175     self.locked_by_uuid = need_lock
176   end
177
178   def assign_auth
179     if self.auth_uuid_changed?
180       return errors.add :auth_uuid, 'is readonly'
181     end
182     if not [Locked, Running].include? self.state
183       # don't need one
184       self.auth.andand.update_attributes(expires_at: db_current_time)
185       self.auth = nil
186       return
187     elsif self.auth
188       # already have one
189       return
190     end
191     cr = ContainerRequest.
192       where('container_uuid=? and priority>0', self.uuid).
193       order('priority desc').
194       first
195     if !cr
196       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
197     end
198     self.auth = ApiClientAuthorization.
199       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
200               api_client_id: 0)
201   end
202
203   def handle_completed
204     # This container is finished so finalize any associated container requests
205     # that are associated with this container.
206     if self.state_changed? and [Complete, Cancelled].include? self.state
207       act_as_system_user do
208         # Notify container requests associated with this container
209         ContainerRequest.where(container_uuid: uuid,
210                                :state => ContainerRequest::Committed).each do |cr|
211           cr.container_completed!
212         end
213
214         # Try to cancel any outstanding container requests made by this container.
215         ContainerRequest.where(requesting_container_uuid: uuid,
216                                :state => ContainerRequest::Committed).each do |cr|
217           cr.priority = 0
218           cr.save
219         end
220       end
221     end
222   end
223
224 end