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