Merge branch '11305-migrate-docker19-doc'
[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   serialize :scheduling_parameters, Hash
15
16   before_validation :fill_field_defaults, :if => :new_record?
17   before_validation :validate_runtime_constraints
18   before_validation :validate_scheduling_parameters
19   before_validation :set_container
20   validates :command, :container_image, :output_path, :cwd, :presence => true
21   validates :output_ttl, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
22   validate :validate_state_change
23   validate :check_update_whitelist
24   after_save :update_priority
25   after_save :finalize_if_needed
26   before_create :set_requesting_container_uuid
27
28   api_accessible :user, extend: :common do |t|
29     t.add :command
30     t.add :container_count
31     t.add :container_count_max
32     t.add :container_image
33     t.add :container_uuid
34     t.add :cwd
35     t.add :description
36     t.add :environment
37     t.add :expires_at
38     t.add :filters
39     t.add :log_uuid
40     t.add :mounts
41     t.add :name
42     t.add :output_name
43     t.add :output_path
44     t.add :output_uuid
45     t.add :output_ttl
46     t.add :priority
47     t.add :properties
48     t.add :requesting_container_uuid
49     t.add :runtime_constraints
50     t.add :scheduling_parameters
51     t.add :state
52     t.add :use_existing
53   end
54
55   # Supported states for a container request
56   States =
57     [
58      (Uncommitted = 'Uncommitted'),
59      (Committed = 'Committed'),
60      (Final = 'Final'),
61     ]
62
63   State_transitions = {
64     nil => [Uncommitted, Committed],
65     Uncommitted => [Committed],
66     Committed => [Final]
67   }
68
69   AttrsPermittedAlways = [:owner_uuid, :state, :name, :description]
70   AttrsPermittedBeforeCommit = [:command, :container_count_max,
71   :container_image, :cwd, :environment, :filters, :mounts,
72   :output_path, :priority, :properties, :requesting_container_uuid,
73   :runtime_constraints, :state, :container_uuid, :use_existing,
74   :scheduling_parameters, :output_name, :output_ttl]
75
76   def state_transitions
77     State_transitions
78   end
79
80   def skip_uuid_read_permission_check
81     # XXX temporary until permissions are sorted out.
82     %w(modified_by_client_uuid container_uuid requesting_container_uuid)
83   end
84
85   def finalize_if_needed
86     if state == Committed && Container.find_by_uuid(container_uuid).final?
87       reload
88       act_as_system_user do
89         finalize!
90       end
91     end
92   end
93
94   # Finalize the container request after the container has
95   # finished/cancelled.
96   def finalize!
97     out_coll = nil
98     log_coll = nil
99     c = Container.find_by_uuid(container_uuid)
100     ['output', 'log'].each do |out_type|
101       pdh = c.send(out_type)
102       next if pdh.nil?
103       coll_name = "Container #{out_type} for request #{uuid}"
104       trash_at = nil
105       if out_type == 'output'
106         if self.output_name
107           coll_name = self.output_name
108         end
109         if self.output_ttl > 0
110           trash_at = db_current_time + self.output_ttl
111         end
112       end
113       manifest = Collection.unscoped do
114         Collection.where(portable_data_hash: pdh).first.manifest_text
115       end
116
117       coll = Collection.new(owner_uuid: owner_uuid,
118                             manifest_text: manifest,
119                             portable_data_hash: pdh,
120                             name: coll_name,
121                             trash_at: trash_at,
122                             delete_at: trash_at,
123                             properties: {
124                               'type' => out_type,
125                               'container_request' => uuid,
126                             })
127       coll.save_with_unique_name!
128       if out_type == 'output'
129         out_coll = coll.uuid
130       else
131         log_coll = coll.uuid
132       end
133     end
134     update_attributes!(state: Final, output_uuid: out_coll, log_uuid: log_coll)
135   end
136
137   def self.full_text_searchable_columns
138     super - ["mounts"]
139   end
140
141   protected
142
143   def fill_field_defaults
144     self.state ||= Uncommitted
145     self.environment ||= {}
146     self.runtime_constraints ||= {}
147     self.mounts ||= {}
148     self.cwd ||= "."
149     self.container_count_max ||= Rails.configuration.container_count_max
150     self.scheduling_parameters ||= {}
151     self.output_ttl ||= 0
152   end
153
154   def set_container
155     if (container_uuid_changed? and
156         not current_user.andand.is_admin and
157         not container_uuid.nil?)
158       errors.add :container_uuid, "can only be updated to nil."
159       return false
160     end
161     if state_changed? and state == Committed and container_uuid.nil?
162       self.container_uuid = Container.resolve(self).uuid
163     end
164     if self.container_uuid != self.container_uuid_was
165       if self.container_count_changed?
166         errors.add :container_count, "cannot be updated directly."
167         return false
168       else
169         self.container_count += 1
170       end
171     end
172   end
173
174   def validate_runtime_constraints
175     case self.state
176     when Committed
177       [['vcpus', true],
178        ['ram', true],
179        ['keep_cache_ram', false]].each do |k, required|
180         if !required && !runtime_constraints.include?(k)
181           next
182         end
183         v = runtime_constraints[k]
184         unless (v.is_a?(Integer) && v > 0)
185           errors.add(:runtime_constraints,
186                      "[#{k}]=#{v.inspect} must be a positive integer")
187         end
188       end
189     end
190   end
191
192   def validate_scheduling_parameters
193     if self.state == Committed
194       if scheduling_parameters.include? 'partitions' and
195          (!scheduling_parameters['partitions'].is_a?(Array) ||
196           scheduling_parameters['partitions'].reject{|x| !x.is_a?(String)}.size !=
197             scheduling_parameters['partitions'].size)
198             errors.add :scheduling_parameters, "partitions must be an array of strings"
199       end
200     end
201   end
202
203   def check_update_whitelist
204     permitted = AttrsPermittedAlways.dup
205
206     if self.new_record? || self.state_was == Uncommitted
207       # Allow create-and-commit in a single operation.
208       permitted.push *AttrsPermittedBeforeCommit
209     end
210
211     case self.state
212     when Committed
213       permitted.push :priority, :container_count_max, :container_uuid
214
215       if self.container_uuid.nil?
216         self.errors.add :container_uuid, "has not been resolved to a container."
217       end
218
219       if self.priority.nil?
220         self.errors.add :priority, "cannot be nil"
221       end
222
223       # Allow container count to increment by 1
224       if (self.container_uuid &&
225           self.container_uuid != self.container_uuid_was &&
226           self.container_count == 1 + (self.container_count_was || 0))
227         permitted.push :container_count
228       end
229
230     when Final
231       if self.state_changed? and not current_user.andand.is_admin
232         self.errors.add :state, "of container request can only be set to Final by system."
233       end
234
235       if self.state_was == Committed
236         permitted.push :output_uuid, :log_uuid
237       end
238
239     end
240
241     super(permitted)
242   end
243
244   def update_priority
245     if self.state_changed? or
246         self.priority_changed? or
247         self.container_uuid_changed?
248       act_as_system_user do
249         Container.
250           where('uuid in (?)',
251                 [self.container_uuid_was, self.container_uuid].compact).
252           map(&:update_priority!)
253       end
254     end
255   end
256
257   def set_requesting_container_uuid
258     return !new_record? if self.requesting_container_uuid   # already set
259
260     token_uuid = current_api_client_authorization.andand.uuid
261     container = Container.where('auth_uuid=?', token_uuid).order('created_at desc').first
262     self.requesting_container_uuid = container.uuid if container
263     true
264   end
265 end