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