3021: Replace more "render json:..." with faster Oj.
[arvados.git] / services / api / app / controllers / application_controller.rb
1 module ApiTemplateOverride
2   def allowed_to_render?(fieldset, field, model, options)
3     return false if !super
4     if options[:select]
5       options[:select].include? field.to_s
6     else
7       true
8     end
9   end
10 end
11
12 class ActsAsApi::ApiTemplate
13   prepend ApiTemplateOverride
14 end
15
16 require 'load_param'
17 require 'record_filters'
18
19 class ApplicationController < ActionController::Base
20   include CurrentApiClient
21   include ThemesForRails::ActionController
22   include LoadParam
23   include RecordFilters
24
25   respond_to :json
26   protect_from_forgery
27
28   ERROR_ACTIONS = [:render_error, :render_not_found]
29
30   before_filter :set_cors_headers
31   before_filter :respond_with_json_by_default
32   before_filter :remote_ip
33   before_filter :load_read_auths
34   before_filter :require_auth_scope, except: ERROR_ACTIONS
35
36   before_filter :catch_redirect_hint
37   before_filter(:find_object_by_uuid,
38                 except: [:index, :create] + ERROR_ACTIONS)
39   before_filter :load_required_parameters
40   before_filter :load_limit_offset_order_params, only: [:index, :contents]
41   before_filter :load_where_param, only: [:index, :contents]
42   before_filter :load_filters_param, only: [:index, :contents]
43   before_filter :find_objects_for_index, :only => :index
44   before_filter :reload_object_before_update, :only => :update
45   before_filter(:render_404_if_no_object,
46                 except: [:index, :create] + ERROR_ACTIONS)
47
48   theme :select_theme
49
50   attr_accessor :resource_attrs
51
52   begin
53     rescue_from(Exception,
54                 ArvadosModel::PermissionDeniedError,
55                 :with => :render_error)
56     rescue_from(ActiveRecord::RecordNotFound,
57                 ActionController::RoutingError,
58                 ActionController::UnknownController,
59                 AbstractController::ActionNotFound,
60                 :with => :render_not_found)
61   end
62
63   def default_url_options
64     if Rails.configuration.host
65       {:host => Rails.configuration.host}
66     else
67       {}
68     end
69   end
70
71   def index
72     @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
73     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
74       @objects.each(&:eager_load_associations)
75     end
76     render_list
77   end
78
79   def show
80     send_json @object.as_api_response(nil, select: @select)
81   end
82
83   def create
84     @object = model_class.new resource_attrs
85
86     if @object.respond_to? :name and params[:ensure_unique_name]
87       # Record the original name.  See below.
88       name_stem = @object.name
89       counter = 1
90     end
91
92     begin
93       @object.save!
94     rescue ActiveRecord::RecordNotUnique => rn
95       raise unless params[:ensure_unique_name]
96
97       # Dig into the error to determine if it is specifically calling out a
98       # (owner_uuid, name) uniqueness violation.  In this specific case, and
99       # the client requested a unique name with ensure_unique_name==true,
100       # update the name field and try to save again.  Loop as necessary to
101       # discover a unique name.  It is necessary to handle name choosing at
102       # this level (as opposed to the client) to ensure that record creation
103       # never fails due to a race condition.
104       raise unless rn.original_exception.is_a? PG::UniqueViolation
105
106       # Unfortunately ActiveRecord doesn't abstract out any of the
107       # necessary information to figure out if this the error is actually
108       # the specific case where we want to apply the ensure_unique_name
109       # behavior, so the following code is specialized to Postgres.
110       err = rn.original_exception
111       detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
112       raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
113
114       # OK, this exception really is just a unique name constraint
115       # violation, and we've been asked to ensure_unique_name.
116       counter += 1
117       @object.uuid = nil
118       @object.name = "#{name_stem} (#{counter})"
119       redo
120     end while false
121     show
122   end
123
124   def update
125     attrs_to_update = resource_attrs.reject { |k,v|
126       [:kind, :etag, :href].index k
127     }
128     @object.update_attributes! attrs_to_update
129     show
130   end
131
132   def destroy
133     @object.destroy
134     show
135   end
136
137   def catch_redirect_hint
138     if !current_user
139       if params.has_key?('redirect_to') then
140         session[:redirect_to] = params[:redirect_to]
141       end
142     end
143   end
144
145   def render_404_if_no_object
146     render_not_found "Object not found" if !@object
147   end
148
149   def render_error(e)
150     logger.error e.inspect
151     if e.respond_to? :backtrace and e.backtrace
152       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
153     end
154     if (@object.respond_to? :errors and
155         @object.errors.andand.full_messages.andand.any?)
156       errors = @object.errors.full_messages
157       logger.error errors.inspect
158     else
159       errors = [e.inspect]
160     end
161     status = e.respond_to?(:http_status) ? e.http_status : 422
162     send_error(*errors, status: status)
163   end
164
165   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
166     logger.error e.inspect
167     send_error("Path not found", status: 404)
168   end
169
170   protected
171
172   def send_error(*args)
173     if args.last.is_a? Hash
174       err = args.pop
175     else
176       err = {}
177     end
178     err[:errors] ||= args
179     err[:error_token] = [Time.now.utc.to_i, "%08x" % rand(16 ** 8)].join("+")
180     status = err.delete(:status) || 422
181     logger.error "Error #{err[:error_token]}: #{status}"
182     send_json err, status: status
183   end
184
185   def send_json response, opts={}
186     # The obvious render(json: ...) forces a slow JSON encoder. See
187     # #3021 and commit logs. Might be fixed in Rails 4.1.
188     render({
189              text: Oj.dump(response, mode: :compat).html_safe,
190              content_type: 'application/json'
191            }.merge opts)
192   end
193
194   def find_objects_for_index
195     @objects ||= model_class.readable_by(*@read_users)
196     apply_where_limit_order_params
197   end
198
199   def apply_filters model_class=nil
200     model_class ||= self.model_class
201     ft = record_filters @filters, model_class
202     if ft[:cond_out].any?
203       @objects = @objects.where('(' + ft[:cond_out].join(') AND (') + ')',
204                                 *ft[:param_out])
205     end
206   end
207
208   def apply_where_limit_order_params *args
209     apply_filters *args
210
211     ar_table_name = @objects.table_name
212     if @where.is_a? Hash and @where.any?
213       conditions = ['1=1']
214       @where.each do |attr,value|
215         if attr.to_s == 'any'
216           if value.is_a?(Array) and
217               value.length == 2 and
218               value[0] == 'contains' then
219             ilikes = []
220             model_class.searchable_columns('ilike').each do |column|
221               # Including owner_uuid in an "any column" search will
222               # probably just return a lot of false positives.
223               next if column == 'owner_uuid'
224               ilikes << "#{ar_table_name}.#{column} ilike ?"
225               conditions << "%#{value[1]}%"
226             end
227             if ilikes.any?
228               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
229             end
230           end
231         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
232             model_class.columns.collect(&:name).index(attr.to_s)
233           if value.nil?
234             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
235             conditions << nil
236           elsif value.is_a? Array
237             if value[0] == 'contains' and value.length == 2
238               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
239               conditions << "%#{value[1]}%"
240             else
241               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
242               conditions << value
243             end
244           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
245             conditions[0] << " and #{ar_table_name}.#{attr}=?"
246             conditions << value
247           elsif value.is_a? Hash
248             # Not quite the same thing as "equal?" but better than nothing?
249             value.each do |k,v|
250               if v.is_a? String
251                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
252                 conditions << "%#{k}%#{v}%"
253               end
254             end
255           end
256         end
257       end
258       if conditions.length > 1
259         conditions[0].sub!(/^1=1 and /, '')
260         @objects = @objects.
261           where(*conditions)
262       end
263     end
264
265     if @select
266       unless action_name.in? %w(create update destroy)
267         # Map attribute names in @select to real column names, resolve
268         # those to fully-qualified SQL column names, and pass the
269         # resulting string to the select method.
270         api_column_map = model_class.attributes_required_columns
271         columns_list = @select.
272           flat_map { |attr| api_column_map[attr] }.
273           uniq.
274           map { |s| "#{table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
275         @objects = @objects.select(columns_list.join(", "))
276       end
277
278       # This information helps clients understand what they're seeing
279       # (Workbench always expects it), but they can't select it explicitly
280       # because it's not an SQL column.  Always add it.
281       # (This is harmless, given that clients can deduce what they're
282       # looking at by the returned UUID anyway.)
283       @select |= ["kind"]
284     end
285     @objects = @objects.order(@orders.join ", ") if @orders.any?
286     @objects = @objects.limit(@limit)
287     @objects = @objects.offset(@offset)
288     @objects = @objects.uniq(@distinct) if not @distinct.nil?
289   end
290
291   def resource_attrs
292     return @attrs if @attrs
293     @attrs = params[resource_name]
294     if @attrs.is_a? String
295       @attrs = Oj.load @attrs, symbol_keys: true
296     end
297     unless @attrs.is_a? Hash
298       message = "No #{resource_name}"
299       if resource_name.index('_')
300         message << " (or #{resource_name.camelcase(:lower)})"
301       end
302       message << " hash provided with request"
303       raise ArgumentError.new(message)
304     end
305     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
306       @attrs.delete x.to_sym
307     end
308     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
309     @attrs
310   end
311
312   # Authentication
313   def load_read_auths
314     @read_auths = []
315     if current_api_client_authorization
316       @read_auths << current_api_client_authorization
317     end
318     # Load reader tokens if this is a read request.
319     # If there are too many reader tokens, assume the request is malicious
320     # and ignore it.
321     if request.get? and params[:reader_tokens] and
322         params[:reader_tokens].size < 100
323       @read_auths += ApiClientAuthorization
324         .includes(:user)
325         .where('api_token IN (?) AND
326                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
327                params[:reader_tokens])
328         .all
329     end
330     @read_auths.select! { |auth| auth.scopes_allow_request? request }
331     @read_users = @read_auths.map { |auth| auth.user }.uniq
332   end
333
334   def require_login
335     if not current_user
336       respond_to do |format|
337         format.json { send_error("Not logged in", status: 401) }
338         format.html { redirect_to '/auth/joshid' }
339       end
340       false
341     end
342   end
343
344   def admin_required
345     unless current_user and current_user.is_admin
346       send_error("Forbidden", status: 403)
347     end
348   end
349
350   def require_auth_scope
351     if @read_auths.empty?
352       if require_login != false
353         send_error("Forbidden", status: 403)
354       end
355       false
356     end
357   end
358
359   def set_cors_headers
360     response.headers['Access-Control-Allow-Origin'] = '*'
361     response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
362     response.headers['Access-Control-Allow-Headers'] = 'Authorization'
363     response.headers['Access-Control-Max-Age'] = '86486400'
364   end
365
366   def respond_with_json_by_default
367     html_index = request.accepts.index(Mime::HTML)
368     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
369       request.format = :json
370     end
371   end
372
373   def model_class
374     controller_name.classify.constantize
375   end
376
377   def resource_name             # params[] key used by client
378     controller_name.singularize
379   end
380
381   def table_name
382     controller_name
383   end
384
385   def find_object_by_uuid
386     if params[:id] and params[:id].match /\D/
387       params[:uuid] = params.delete :id
388     end
389     @where = { uuid: params[:uuid] }
390     @offset = 0
391     @limit = 1
392     @orders = []
393     @filters = []
394     @objects = nil
395     find_objects_for_index
396     @object = @objects.first
397   end
398
399   def reload_object_before_update
400     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
401     # error when updating an object which was retrieved using a join.
402     if @object.andand.readonly?
403       @object = model_class.find_by_uuid(@objects.first.uuid)
404     end
405   end
406
407   def load_json_value(hash, key, must_be_class=nil)
408     if hash[key].is_a? String
409       hash[key] = Oj.load(hash[key], symbol_keys: false)
410       if must_be_class and !hash[key].is_a? must_be_class
411         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
412       end
413     end
414   end
415
416   def self.accept_attribute_as_json(attr, must_be_class=nil)
417     before_filter lambda { accept_attribute_as_json attr, must_be_class }
418   end
419   accept_attribute_as_json :properties, Hash
420   accept_attribute_as_json :info, Hash
421   def accept_attribute_as_json(attr, must_be_class)
422     if params[resource_name] and resource_attrs.is_a? Hash
423       if resource_attrs[attr].is_a? Hash
424         # Convert symbol keys to strings (in hashes provided by
425         # resource_attrs)
426         resource_attrs[attr] = resource_attrs[attr].
427           with_indifferent_access.to_hash
428       else
429         load_json_value(resource_attrs, attr, must_be_class)
430       end
431     end
432   end
433
434   def self.accept_param_as_json(key, must_be_class=nil)
435     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
436   end
437   accept_param_as_json :reader_tokens, Array
438
439   def render_list
440     @object_list = {
441       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
442       :etag => "",
443       :self_link => "",
444       :offset => @offset,
445       :limit => @limit,
446       :items => @objects.as_api_response(nil, {select: @select})
447     }
448     if @objects.respond_to? :except
449       @object_list[:items_available] = @objects.
450         except(:limit).except(:offset).
451         count(:id, distinct: true)
452     end
453     send_json @object_list
454   end
455
456   def remote_ip
457     # Caveat: this is highly dependent on the proxy setup. YMMV.
458     if request.headers.has_key?('HTTP_X_REAL_IP') then
459       # We're behind a reverse proxy
460       @remote_ip = request.headers['HTTP_X_REAL_IP']
461     else
462       # Hopefully, we are not!
463       @remote_ip = request.env['REMOTE_ADDR']
464     end
465   end
466
467   def load_required_parameters
468     (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
469       each do |key, info|
470       if info[:required] and not params.include?(key)
471         raise ArgumentError.new("#{key} parameter is required")
472       elsif info[:type] == 'boolean'
473         # Make sure params[key] is either true or false -- not a
474         # string, not nil, etc.
475         if not params.include?(key)
476           params[key] = info[:default]
477         elsif [false, 'false', '0', 0].include? params[key]
478           params[key] = false
479         elsif [true, 'true', '1', 1].include? params[key]
480           params[key] = true
481         else
482           raise TypeError.new("#{key} parameter must be a boolean, true or false")
483         end
484       end
485     end
486     true
487   end
488
489   def self._create_requires_parameters
490     {
491       ensure_unique_name: {
492         type: "boolean",
493         description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
494         location: "query",
495         required: false,
496         default: false
497       }
498     }
499   end
500
501   def self._index_requires_parameters
502     {
503       filters: { type: 'array', required: false },
504       where: { type: 'object', required: false },
505       order: { type: 'array', required: false },
506       select: { type: 'array', required: false },
507       distinct: { type: 'boolean', required: false },
508       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
509       offset: { type: 'integer', required: false, default: 0 },
510     }
511   end
512
513   def client_accepts_plain_text_stream
514     (request.headers['Accept'].split(' ') &
515      ['text/plain', '*/*']).count > 0
516   end
517
518   def render *opts
519     if opts.first
520       response = opts.first[:json]
521       if response.is_a?(Hash) &&
522           params[:_profile] &&
523           Thread.current[:request_starttime]
524         response[:_profile] = {
525           request_time: Time.now - Thread.current[:request_starttime]
526         }
527       end
528     end
529     super *opts
530   end
531
532   def select_theme
533     return Rails.configuration.arvados_theme
534   end
535 end