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