8018: Fix state transition checks. Add test of retry and fix other tests to
[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   def container_completed!
69     # may implement retry logic here in the future.
70     self.state = ContainerRequest::Final
71     self.save!
72   end
73
74   protected
75
76   def fill_field_defaults
77     self.state ||= Uncommitted
78     self.environment ||= {}
79     self.runtime_constraints ||= {}
80     self.mounts ||= {}
81     self.cwd ||= "."
82     self.container_count_max ||= Rails.configuration.container_count_max
83   end
84
85   # Create a new container (or find an existing one) to satisfy this
86   # request.
87   def resolve
88     c_mounts = mounts_for_container
89     c_runtime_constraints = runtime_constraints_for_container
90     c_container_image = container_image_for_container
91     c = act_as_system_user do
92       c_attrs = {command: self.command,
93                  cwd: self.cwd,
94                  environment: self.environment,
95                  output_path: self.output_path,
96                  container_image: c_container_image,
97                  mounts: c_mounts,
98                  runtime_constraints: c_runtime_constraints}
99       reusable = Container.find_reusable(c_attrs)
100       if not reusable.nil?
101         reusable
102       else
103         Container.create!(c_attrs)
104       end
105     end
106     self.container_uuid = c.uuid
107   end
108
109   # Return a runtime_constraints hash that complies with
110   # self.runtime_constraints but is suitable for saving in a container
111   # record, i.e., has specific values instead of ranges.
112   #
113   # Doing this as a step separate from other resolutions, like "git
114   # revision range to commit hash", makes sense only when there is no
115   # opportunity to reuse an existing container (e.g., container reuse
116   # is not implemented yet, or we have already found that no existing
117   # containers are suitable).
118   def runtime_constraints_for_container
119     rc = {}
120     runtime_constraints.each do |k, v|
121       if v.is_a? Array
122         rc[k] = v[0]
123       else
124         rc[k] = v
125       end
126     end
127     rc
128   end
129
130   # Return a mounts hash suitable for a Container, i.e., with every
131   # readonly collection UUID resolved to a PDH.
132   def mounts_for_container
133     c_mounts = {}
134     mounts.each do |k, mount|
135       mount = mount.dup
136       c_mounts[k] = mount
137       if mount['kind'] != 'collection'
138         next
139       end
140       if (uuid = mount.delete 'uuid')
141         c = Collection.
142           readable_by(current_user).
143           where(uuid: uuid).
144           select(:portable_data_hash).
145           first
146         if !c
147           raise ArvadosModel::UnresolvableContainerError.new "cannot mount collection #{uuid.inspect}: not found"
148         end
149         if mount['portable_data_hash'].nil?
150           # PDH not supplied by client
151           mount['portable_data_hash'] = c.portable_data_hash
152         elsif mount['portable_data_hash'] != c.portable_data_hash
153           # UUID and PDH supplied by client, but they don't agree
154           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"
155         end
156       end
157     end
158     return c_mounts
159   end
160
161   # Return a container_image PDH suitable for a Container.
162   def container_image_for_container
163     coll = Collection.for_latest_docker_image(container_image)
164     if !coll
165       raise ArvadosModel::UnresolvableContainerError.new "docker image #{container_image.inspect} not found"
166     end
167     return coll.portable_data_hash
168   end
169
170   def set_container
171     if (container_uuid_changed? and
172         not current_user.andand.is_admin and
173         not container_uuid.nil?)
174       errors.add :container_uuid, "can only be updated to nil."
175       return false
176     end
177     if state_changed? and state == Committed and container_uuid.nil?
178       resolve
179     end
180     if self.container_uuid != self.container_uuid_was
181       if self.container_count_changed?
182         errors.add :container_count, "cannot be updated directly."
183         return false
184       else
185         self.container_count += 1
186       end
187     end
188   end
189
190   def validate_runtime_constraints
191     case self.state
192     when Committed
193       ['vcpus', 'ram'].each do |k|
194         if not (runtime_constraints.include? k and
195                 runtime_constraints[k].is_a? Integer and
196                 runtime_constraints[k] > 0)
197           errors.add :runtime_constraints, "#{k} must be a positive integer"
198         end
199       end
200     end
201   end
202
203   def validate_change
204     permitted = [:owner_uuid]
205
206     case self.state
207     when Uncommitted
208       # Permit updating most fields
209       permitted.push :command, :container_count_max,
210                      :container_image, :cwd, :description, :environment,
211                      :filters, :mounts, :name, :output_path, :priority,
212                      :properties, :requesting_container_uuid, :runtime_constraints,
213                      :state, :container_uuid
214
215     when Committed
216       if container_uuid.nil?
217         errors.add :container_uuid, "has not been resolved to a container."
218       end
219
220       if priority.nil?
221         errors.add :priority, "cannot be nil"
222       end
223
224       # Can update priority, container count, name and description
225       permitted.push :priority, :container_count, :container_count_max, :container_uuid, :name, :description
226
227       if self.state_changed?
228         # Allow create-and-commit in a single operation.
229         permitted.push :command, :container_image, :cwd, :description, :environment,
230                        :filters, :mounts, :name, :output_path, :properties,
231                        :requesting_container_uuid, :runtime_constraints,
232                        :state, :container_uuid
233       end
234
235     when Final
236       if not current_user.andand.is_admin and not (self.name_changed? || self.description_changed?)
237         errors.add :state, "of container request can only be set to Final by system."
238       end
239
240       if self.state_changed? || self.name_changed? || self.description_changed?
241           permitted.push :state, :name, :description
242       else
243         errors.add :state, "does not allow updates"
244       end
245
246     else
247       errors.add :state, "invalid value"
248     end
249
250     check_update_whitelist permitted
251   end
252
253   def update_priority
254     if self.state_changed? or
255         self.priority_changed? or
256         self.container_uuid_changed?
257       act_as_system_user do
258         Container.
259           where('uuid in (?)',
260                 [self.container_uuid_was, self.container_uuid].compact).
261           map(&:update_priority!)
262       end
263     end
264   end
265
266   def set_requesting_container_uuid
267     return !new_record? if self.requesting_container_uuid   # already set
268
269     token_uuid = current_api_client_authorization.andand.uuid
270     container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
271     self.requesting_container_uuid = container.uuid if container
272     true
273   end
274 end