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