10293: add output_uuid to container_request and set it during finalize.
[arvados.git] / services / api / app / models / container_request.rb
1 require 'whitelist_update'
2
3 class ContainerRequest < ArvadosModel
4   include HasUuid
5   include KindAndEtag
6   include CommonApiTemplate
7   include WhitelistUpdate
8
9   serialize :properties, Hash
10   serialize :environment, Hash
11   serialize :mounts, Hash
12   serialize :runtime_constraints, Hash
13   serialize :command, Array
14
15   before_validation :fill_field_defaults, :if => :new_record?
16   before_validation :validate_runtime_constraints
17   before_validation :set_container
18   validates :command, :container_image, :output_path, :cwd, :presence => true
19   validate :validate_state_change
20   validate :validate_change
21   after_save :update_priority
22   after_save :finalize_if_needed
23   before_create :set_requesting_container_uuid
24
25   api_accessible :user, extend: :common do |t|
26     t.add :command
27     t.add :container_count
28     t.add :container_count_max
29     t.add :container_image
30     t.add :container_uuid
31     t.add :cwd
32     t.add :description
33     t.add :environment
34     t.add :expires_at
35     t.add :filters
36     t.add :mounts
37     t.add :name
38     t.add :output_path
39     t.add :priority
40     t.add :properties
41     t.add :requesting_container_uuid
42     t.add :runtime_constraints
43     t.add :state
44     t.add :use_existing
45     t.add :output_uuid
46   end
47
48   # Supported states for a container request
49   States =
50     [
51      (Uncommitted = 'Uncommitted'),
52      (Committed = 'Committed'),
53      (Final = 'Final'),
54     ]
55
56   State_transitions = {
57     nil => [Uncommitted, Committed],
58     Uncommitted => [Committed],
59     Committed => [Final]
60   }
61
62   def state_transitions
63     State_transitions
64   end
65
66   def skip_uuid_read_permission_check
67     # XXX temporary until permissions are sorted out.
68     %w(modified_by_client_uuid container_uuid requesting_container_uuid)
69   end
70
71   def finalize_if_needed
72     if state == Committed && Container.find_by_uuid(container_uuid).final?
73       reload
74       act_as_system_user do
75         finalize!
76       end
77     end
78   end
79
80   # Finalize the container request after the container has
81   # finished/cancelled.
82   def finalize!
83     out_uuid = nil
84     c = Container.find_by_uuid(container_uuid)
85     ['output', 'log'].each do |out_type|
86       pdh = c.send(out_type)
87       next if pdh.nil?
88       manifest = Collection.where(portable_data_hash: pdh).first.manifest_text
89       coll = Collection.create!(owner_uuid: owner_uuid,
90                          manifest_text: manifest,
91                          portable_data_hash: pdh,
92                          name: "Container #{out_type} for request #{uuid}",
93                          properties: {
94                            'type' => out_type,
95                            'container_request' => uuid,
96                          })
97       out_uuid = coll.uuid if out_type == 'output'
98     end
99     update_attributes!(state: Final, output_uuid: out_uuid)
100   end
101
102   protected
103
104   def fill_field_defaults
105     self.state ||= Uncommitted
106     self.environment ||= {}
107     self.runtime_constraints ||= {}
108     self.mounts ||= {}
109     self.cwd ||= "."
110     self.container_count_max ||= Rails.configuration.container_count_max
111   end
112
113   # Create a new container (or find an existing one) to satisfy this
114   # request.
115   def resolve
116     c_mounts = mounts_for_container
117     c_runtime_constraints = runtime_constraints_for_container
118     c_container_image = container_image_for_container
119     c = act_as_system_user do
120       c_attrs = {command: self.command,
121                  cwd: self.cwd,
122                  environment: self.environment,
123                  output_path: self.output_path,
124                  container_image: c_container_image,
125                  mounts: c_mounts,
126                  runtime_constraints: c_runtime_constraints}
127
128       reusable = self.use_existing ? Container.find_reusable(c_attrs) : nil
129       if not reusable.nil?
130         reusable
131       else
132         Container.create!(c_attrs)
133       end
134     end
135     self.container_uuid = c.uuid
136   end
137
138   # Return a runtime_constraints hash that complies with
139   # self.runtime_constraints but is suitable for saving in a container
140   # record, i.e., has specific values instead of ranges.
141   #
142   # Doing this as a step separate from other resolutions, like "git
143   # revision range to commit hash", makes sense only when there is no
144   # opportunity to reuse an existing container (e.g., container reuse
145   # is not implemented yet, or we have already found that no existing
146   # containers are suitable).
147   def runtime_constraints_for_container
148     rc = {}
149     runtime_constraints.each do |k, v|
150       if v.is_a? Array
151         rc[k] = v[0]
152       else
153         rc[k] = v
154       end
155     end
156     rc
157   end
158
159   # Return a mounts hash suitable for a Container, i.e., with every
160   # readonly collection UUID resolved to a PDH.
161   def mounts_for_container
162     c_mounts = {}
163     mounts.each do |k, mount|
164       mount = mount.dup
165       c_mounts[k] = mount
166       if mount['kind'] != 'collection'
167         next
168       end
169       if (uuid = mount.delete 'uuid')
170         c = Collection.
171           readable_by(current_user).
172           where(uuid: uuid).
173           select(:portable_data_hash).
174           first
175         if !c
176           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
177         end
178         if mount['portable_data_hash'].nil?
179           # PDH not supplied by client
180           mount['portable_data_hash'] = c.portable_data_hash
181         elsif mount['portable_data_hash'] != c.portable_data_hash
182           # UUID and PDH supplied by client, but they don't agree
183           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"
184         end
185       end
186     end
187     return c_mounts
188   end
189
190   # Return a container_image PDH suitable for a Container.
191   def container_image_for_container
192     coll = Collection.for_latest_docker_image(container_image)
193     if !coll
194       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
195     end
196     return coll.portable_data_hash
197   end
198
199   def set_container
200     if (container_uuid_changed? and
201         not current_user.andand.is_admin and
202         not container_uuid.nil?)
203       errors.add :container_uuid, "can only be updated to nil."
204       return false
205     end
206     if state_changed? and state == Committed and container_uuid.nil?
207       resolve
208     end
209     if self.container_uuid != self.container_uuid_was
210       if self.container_count_changed?
211         errors.add :container_count, "cannot be updated directly."
212         return false
213       else
214         self.container_count += 1
215       end
216     end
217   end
218
219   def validate_runtime_constraints
220     case self.state
221     when Committed
222       ['vcpus', 'ram'].each do |k|
223         if not (runtime_constraints.include? k and
224                 runtime_constraints[k].is_a? Integer and
225                 runtime_constraints[k] > 0)
226           errors.add :runtime_constraints, "#{k} must be a positive integer"
227         end
228       end
229
230       if runtime_constraints.include? 'keep_cache_ram' and
231          (!runtime_constraints['keep_cache_ram'].is_a?(Integer) or
232           runtime_constraints['keep_cache_ram'] <= 0)
233             errors.add :runtime_constraints, "keep_cache_ram must be a positive integer"
234       elsif !runtime_constraints.include? 'keep_cache_ram'
235         runtime_constraints['keep_cache_ram'] = Rails.configuration.container_default_keep_cache_ram
236       end
237     end
238   end
239
240   def validate_change
241     permitted = [:owner_uuid]
242
243     case self.state
244     when Uncommitted
245       # Permit updating most fields
246       permitted.push :command, :container_count_max,
247                      :container_image, :cwd, :description, :environment,
248                      :filters, :mounts, :name, :output_path, :priority,
249                      :properties, :requesting_container_uuid, :runtime_constraints,
250                      :state, :container_uuid, :use_existing
251
252     when Committed
253       if container_uuid.nil?
254         errors.add :container_uuid, "has not been resolved to a container."
255       end
256
257       if priority.nil?
258         errors.add :priority, "cannot be nil"
259       end
260
261       # Can update priority, container count, name and description
262       permitted.push :priority, :container_count, :container_count_max, :container_uuid, :name, :description
263
264       if self.state_changed?
265         # Allow create-and-commit in a single operation.
266         permitted.push :command, :container_image, :cwd, :description, :environment,
267                        :filters, :mounts, :name, :output_path, :properties,
268                        :requesting_container_uuid, :runtime_constraints,
269                        :state, :container_uuid
270       end
271
272     when Final
273       if not current_user.andand.is_admin and not (self.name_changed? || self.description_changed?)
274         errors.add :state, "of container request can only be set to Final by system."
275       end
276
277       if self.state_changed? || self.name_changed? || self.description_changed? || self.output_uuid_changed?
278           permitted.push :state, :name, :description, :output_uuid
279       else
280         errors.add :state, "does not allow updates"
281       end
282
283     else
284       errors.add :state, "invalid value"
285     end
286
287     check_update_whitelist permitted
288   end
289
290   def update_priority
291     if self.state_changed? or
292         self.priority_changed? or
293         self.container_uuid_changed?
294       act_as_system_user do
295         Container.
296           where('uuid in (?)',
297                 [self.container_uuid_was, self.container_uuid].compact).
298           map(&:update_priority!)
299       end
300     end
301   end
302
303   def set_requesting_container_uuid
304     return !new_record? if self.requesting_container_uuid   # already set
305
306     token_uuid = current_api_client_authorization.andand.uuid
307     container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
308     self.requesting_container_uuid = container.uuid if container
309     true
310   end
311 end