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