9898: add lock and unlock endpoints to containers_controller.
[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   def lock
80     with_lock do
81       if self.state == Queued
82         self.state = Locked
83         self.save!
84       end
85     end
86   end
87
88   protected
89
90   def fill_field_defaults
91     self.state ||= Queued
92     self.environment ||= {}
93     self.runtime_constraints ||= {}
94     self.mounts ||= {}
95     self.cwd ||= "."
96     self.priority ||= 1
97   end
98
99   def permission_to_create
100     current_user.andand.is_admin
101   end
102
103   def permission_to_update
104     current_user.andand.is_admin
105   end
106
107   def set_timestamps
108     if self.state_changed? and self.state == Running
109       self.started_at ||= db_current_time
110     end
111
112     if self.state_changed? and [Complete, Cancelled].include? self.state
113       self.finished_at ||= db_current_time
114     end
115   end
116
117   def validate_change
118     permitted = [:state]
119
120     if self.new_record?
121       permitted.push(:owner_uuid, :command, :container_image, :cwd,
122                      :environment, :mounts, :output_path, :priority,
123                      :runtime_constraints)
124     end
125
126     case self.state
127     when Queued, Locked
128       permitted.push :priority
129
130     when Running
131       permitted.push :priority, :progress
132       if self.state_changed?
133         permitted.push :started_at
134       end
135
136     when Complete
137       if self.state_was == Running
138         permitted.push :finished_at, :output, :log, :exit_code
139       end
140
141     when Cancelled
142       case self.state_was
143       when Running
144         permitted.push :finished_at, :output, :log
145       when Queued, Locked
146         permitted.push :finished_at
147       end
148
149     else
150       # The state_transitions check will add an error message for this
151       return false
152     end
153
154     check_update_whitelist permitted
155   end
156
157   def validate_lock
158     # If the Container is already locked by someone other than the
159     # current api_client_auth, disallow all changes -- except
160     # priority, which needs to change to reflect max(priority) of
161     # relevant ContainerRequests.
162     if locked_by_uuid_was
163       if locked_by_uuid_was != Thread.current[:api_client_authorization].uuid
164         check_update_whitelist [:priority]
165       end
166     end
167
168     if [Locked, Running].include? self.state
169       # If the Container was already locked, locked_by_uuid must not
170       # changes. Otherwise, the current auth gets the lock.
171       need_lock = locked_by_uuid_was || Thread.current[:api_client_authorization].uuid
172     else
173       need_lock = nil
174     end
175
176     # The caller can provide a new value for locked_by_uuid, but only
177     # if it's exactly what we expect. This allows a caller to perform
178     # an update like {"state":"Unlocked","locked_by_uuid":null}.
179     if self.locked_by_uuid_changed?
180       if self.locked_by_uuid != need_lock
181         return errors.add :locked_by_uuid, "can only change to #{need_lock}"
182       end
183     end
184     self.locked_by_uuid = need_lock
185   end
186
187   def assign_auth
188     if self.auth_uuid_changed?
189       return errors.add :auth_uuid, 'is readonly'
190     end
191     if not [Locked, Running].include? self.state
192       # don't need one
193       self.auth.andand.update_attributes(expires_at: db_current_time)
194       self.auth = nil
195       return
196     elsif self.auth
197       # already have one
198       return
199     end
200     cr = ContainerRequest.
201       where('container_uuid=? and priority>0', self.uuid).
202       order('priority desc').
203       first
204     if !cr
205       return errors.add :auth_uuid, "cannot be assigned because priority <= 0"
206     end
207     self.auth = ApiClientAuthorization.
208       create!(user_id: User.find_by_uuid(cr.modified_by_user_uuid).id,
209               api_client_id: 0)
210   end
211
212   def handle_completed
213     # This container is finished so finalize any associated container requests
214     # that are associated with this container.
215     if self.state_changed? and [Complete, Cancelled].include? self.state
216       act_as_system_user do
217         # Notify container requests associated with this container
218         ContainerRequest.where(container_uuid: uuid,
219                                :state => ContainerRequest::Committed).each do |cr|
220           cr.container_completed!
221         end
222
223         # Try to cancel any outstanding container requests made by this container.
224         ContainerRequest.where(requesting_container_uuid: uuid,
225                                :state => ContainerRequest::Committed).each do |cr|
226           cr.priority = 0
227           cr.save
228         end
229       end
230     end
231   end
232
233 end