1 class ApplicationController < ActionController::Base
2 include ArvadosApiClientHelper
4 respond_to :html, :json, :js
7 ERROR_ACTIONS = [:render_error, :render_not_found]
9 around_filter :thread_clear
10 around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
11 around_filter :thread_with_optional_api_token
12 before_filter :check_user_agreements, except: ERROR_ACTIONS
13 before_filter :check_user_notifications, except: ERROR_ACTIONS
14 before_filter :find_object_by_uuid, except: [:index] + ERROR_ACTIONS
18 rescue_from Exception,
19 :with => :render_exception
20 rescue_from ActiveRecord::RecordNotFound,
21 :with => :render_not_found
22 rescue_from ActionController::RoutingError,
23 :with => :render_not_found
24 rescue_from ActionController::UnknownController,
25 :with => :render_not_found
26 rescue_from ::AbstractController::ActionNotFound,
27 :with => :render_not_found
30 def unprocessable(message=nil)
33 @errors << message if message
34 render_error status: 422
37 def render_error(opts)
38 opts = {status: 500}.merge opts
40 # json must come before html here, so it gets used as the
41 # default format when js is requested by the client. This lets
42 # ajax:error callback parse the response correctly, even though
44 f.json { render opts.merge(json: {success: false, errors: @errors}) }
45 f.html { render opts.merge(controller: 'application', action: 'error') }
49 def render_exception(e)
50 logger.error e.inspect
51 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
52 if @object.andand.errors.andand.full_messages.andand.any?
53 @errors = @object.errors.full_messages
57 self.render_error status: 422
60 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
61 logger.error e.inspect
62 @errors = ["Path not found"]
63 self.render_error status: 404
69 @limit = params[:limit].to_i
74 @offset = params[:offset].to_i
79 filters = params[:filters]
80 if filters.is_a? String
81 filters = Oj.load filters
86 @objects ||= model_class
87 @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
89 f.json { render json: @objects }
97 return render_not_found("object not found")
100 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
102 if request.method == 'GET'
105 redirect_to params[:return_to] || @object
114 return render_not_found("object not found")
119 @object = model_class.new
123 @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
124 @updates.keys.each do |attr|
125 if @object.send(attr).is_a? Hash
126 if @updates[attr].is_a? String
127 @updates[attr] = Oj.load @updates[attr]
129 if params[:merge] || params["merge_#{attr}".to_sym]
130 # Merge provided Hash with current Hash, instead of
132 @updates[attr] = @object.send(attr).with_indifferent_access.
133 deep_merge(@updates[attr].with_indifferent_access)
137 if @object.update_attributes @updates
140 self.render_error status: 422
145 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
146 @new_resource_attrs ||= {}
147 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
148 @object ||= model_class.new @new_resource_attrs, params["options"]
151 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
158 self.render_error status: 422
165 f.json { render json: @object }
167 redirect_to(params[:return_to] || :back)
172 self.render_error status: 422
177 if Thread.current[:arvados_api_token]
178 Thread.current[:user] ||= User.current
180 logger.error "No API token in Thread"
186 controller_name.classify.constantize
189 def breadcrumb_page_name
190 (@breadcrumb_page_name ||
191 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
200 %w(Attributes Metadata JSON API)
205 def redirect_to_login
208 if request.method == 'GET'
209 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
211 flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
216 @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
217 self.render_error status: 422
220 false # For convenience to return from callbacks
223 def using_specific_api_token(api_token)
225 [:arvados_api_token, :user].each do |key|
226 start_values[key] = Thread.current[key]
228 Thread.current[:arvados_api_token] = api_token
229 Thread.current[:user] = nil
233 start_values.each_key { |key| Thread.current[key] = start_values[key] }
237 def find_object_by_uuid
238 if params[:id] and params[:id].match /\D/
239 params[:uuid] = params.delete :id
243 elsif params[:uuid].is_a? String
244 if params[:uuid].empty?
247 @object = model_class.find(params[:uuid])
250 @object = model_class.where(uuid: params[:uuid]).first
255 Thread.current[:arvados_api_token] = nil
256 Thread.current[:user] = nil
257 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
259 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
262 def thread_with_api_token(login_optional = false)
264 try_redirect_to_login = true
265 if params[:api_token]
266 try_redirect_to_login = false
267 Thread.current[:arvados_api_token] = params[:api_token]
268 # Before copying the token into session[], do a simple API
269 # call to verify its authenticity.
271 session[:arvados_api_token] = params[:api_token]
272 if !request.format.json? and request.method == 'GET'
273 # Repeat this request with api_token in the (new) session
274 # cookie instead of the query string. This prevents API
275 # tokens from appearing in (and being inadvisedly copied
276 # and pasted from) browser Location bars.
277 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
282 @errors = ['Invalid API token']
283 self.render_error status: 401
285 elsif session[:arvados_api_token]
286 # In this case, the token must have already verified at some
287 # point, but it might have been revoked since. We'll try
288 # using it, and catch the exception if it doesn't work.
289 try_redirect_to_login = false
290 Thread.current[:arvados_api_token] = session[:arvados_api_token]
293 rescue ArvadosApiClient::NotLoggedInException
294 try_redirect_to_login = true
297 logger.debug "No token received, session is #{session.inspect}"
299 if try_redirect_to_login
300 unless login_optional
303 # login is optional for this route so go on to the regular controller
304 Thread.current[:arvados_api_token] = nil
309 # Remove token in case this Thread is used for anything else.
310 Thread.current[:arvados_api_token] = nil
314 def thread_with_mandatory_api_token
315 thread_with_api_token do
320 # This runs after thread_with_mandatory_api_token in the filter chain.
321 def thread_with_optional_api_token
322 if Thread.current[:arvados_api_token]
323 # We are already inside thread_with_mandatory_api_token.
326 # We skipped thread_with_mandatory_api_token. Use the optional version.
327 thread_with_api_token(true) do
335 Link.where(uuid: 'just-verifying-my-api-token')
337 rescue ArvadosApiClient::NotLoggedInException
342 def ensure_current_user_is_admin
343 unless current_user and current_user.is_admin
344 @errors = ['Permission denied']
345 self.render_error status: 401
349 def check_user_agreements
350 if current_user && !current_user.is_active && current_user.is_invited
351 signatures = UserAgreement.signatures
352 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
353 @required_user_agreements = UserAgreement.all.map do |ua|
354 if not @signed_ua_uuids.index ua.uuid
355 Collection.find(ua.uuid)
358 if @required_user_agreements.empty?
359 # No agreements to sign. Perhaps we just need to ask?
360 current_user.activate
361 if !current_user.is_active
362 logger.warn "#{current_user.uuid.inspect}: " +
363 "No user agreements to sign, but activate failed!"
366 if !current_user.is_active
367 render 'user_agreements/index'
374 return Rails.configuration.arvados_theme
377 @@notification_tests = []
379 @@notification_tests.push lambda { |controller, current_user|
380 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
383 return lambda { |view|
384 view.render partial: 'notifications/ssh_key_notification'
388 #@@notification_tests.push lambda { |controller, current_user|
389 # Job.limit(1).where(created_by: current_user.uuid).each do
392 # return lambda { |view|
393 # view.render partial: 'notifications/jobs_notification'
397 @@notification_tests.push lambda { |controller, current_user|
398 Collection.limit(1).where(created_by: current_user.uuid).each do
401 return lambda { |view|
402 view.render partial: 'notifications/collections_notification'
406 @@notification_tests.push lambda { |controller, current_user|
407 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
410 return lambda { |view|
411 view.render partial: 'notifications/pipelines_notification'
415 def check_user_notifications
416 @notification_count = 0
420 @showallalerts = false
421 @@notification_tests.each do |t|
422 a = t.call(self, current_user)
424 @notification_count += 1
425 @notifications.push a
430 if @notification_count == 0
431 @notification_count = ''
435 helper_method :my_folders
437 return @my_folders if @my_folders
440 Group.filter([['group_class','=','folder']]).each do |g|
441 root_of[g.uuid] = g.owner_uuid
447 root_of = root_of.each_with_object({}) do |(child, parent), h|
449 h[child] = root_of[parent]
456 @my_folders = @my_folders.select do |g|
457 root_of[g.uuid] == current_user.uuid
461 # helper method to get links for given object or uuid
462 helper_method :links_for_object
463 def links_for_object object_or_uuid
464 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
465 preload_links_for_objects([object_or_uuid])
467 @all_links_for[uuid] ||= []
470 # helper method to preload links for given objects and uuids
471 helper_method :preload_links_for_objects
472 def preload_links_for_objects objects_and_uuids
473 @all_links_for ||= {}
475 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
476 return @all_links_for if objects_and_uuids.empty?
478 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
480 # if already preloaded for all of these uuids, return
481 if not uuids.select { |x| @all_links_for[x].nil? }.any?
486 @all_links_for[x] = []
489 # TODO: make sure we get every page of results from API server
490 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
491 @all_links_for[link.head_uuid] << link
496 # helper method to get a certain number of objects of a specific type
497 # this can be used to replace any uses of: "dataclass.limit(n)"
498 helper_method :get_n_objects_of_class
499 def get_n_objects_of_class dataclass, size
500 @objects_map_for ||= {}
502 # if the objects_map_for has a value for this dataclass, and the
503 # size used to retrieve those objects is equal, return it
504 size_key = "#{dataclass}_size"
505 if @objects_map_for[dataclass] && @objects_map_for[size_key] &&
506 (@objects_map_for[size_key] == size)
507 return @objects_map_for[dataclass]
510 @objects_map_for[size_key] = size
511 @objects_map_for[dataclass] = dataclass.limit(size)
514 # helper method to get collections for the given uuid
515 helper_method :collections_for_object
516 def collections_for_object uuid
517 preload_collections_for_objects([uuid])
518 @all_collections_for[uuid] ||= []
521 # helper method to preload collections for the given uuids
522 helper_method :preload_collections_for_objects
523 def preload_collections_for_objects uuids
524 @all_collections_for ||= {}
526 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
527 return @all_collections_for if uuids.empty?
529 # if already preloaded for all of these uuids, return
530 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
535 @all_collections_for[x] = []
538 # TODO: make sure we get every page of results from API server
539 Collection.where(uuid: uuids).each do |collection|
540 @all_collections_for[collection.uuid] << collection
545 # helper method to get log collections for the given log
546 helper_method :log_collections_for_object
547 def log_collections_for_object log
548 preload_log_collections_for_objects([log])
551 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
552 if fixup && fixup.size>1
556 @all_log_collections_for[uuid] ||= []
559 # helper method to preload collections for the given uuids
560 helper_method :preload_log_collections_for_objects
561 def preload_log_collections_for_objects logs
562 @all_log_collections_for ||= {}
564 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
565 return @all_log_collections_for if logs.empty?
569 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
570 if fixup && fixup.size>1
577 # if already preloaded for all of these uuids, return
578 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
583 @all_log_collections_for[x] = []
586 # TODO: make sure we get every page of results from API server
587 Collection.where(uuid: uuids).each do |collection|
588 @all_log_collections_for[collection.uuid] << collection
590 @all_log_collections_for
593 # helper method to get object of a given dataclass and uuid
594 helper_method :object_for_dataclass
595 def object_for_dataclass dataclass, uuid
596 preload_objects_for_dataclass(dataclass, [uuid])
600 # helper method to preload objects for given dataclass and uuids
601 helper_method :preload_objects_for_dataclass
602 def preload_objects_for_dataclass dataclass, uuids
605 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
606 return @all_collections_for if uuids.empty?
608 # if already preloaded for all of these uuids, return
609 if not uuids.select { |x| @objects_for[x].nil? }.any?
613 dataclass.where(uuid: uuids).each do |obj|
614 @objects_for[obj.uuid] = obj