1 class ApplicationController < ActionController::Base
2 include ArvadosApiClientHelper
3 include ApplicationHelper
5 respond_to :html, :json, :js
8 ERROR_ACTIONS = [:render_error, :render_not_found]
10 around_filter :thread_clear
11 around_filter :set_thread_api_token
12 # Methods that don't require login should
13 # skip_around_filter :require_thread_api_token
14 around_filter :require_thread_api_token, except: ERROR_ACTIONS
15 before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
16 before_filter :check_user_agreements, except: ERROR_ACTIONS
17 before_filter :check_user_profile, except: ERROR_ACTIONS
18 before_filter :check_user_notifications, except: ERROR_ACTIONS
19 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
20 before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS
24 rescue_from(ActiveRecord::RecordNotFound,
25 ActionController::RoutingError,
26 ActionController::UnknownController,
27 AbstractController::ActionNotFound,
28 with: :render_not_found)
29 rescue_from(Exception,
30 ActionController::UrlGenerationError,
31 with: :render_exception)
34 def unprocessable(message=nil)
37 @errors << message if message
38 render_error status: 422
41 def render_error(opts={})
44 # json must come before html here, so it gets used as the
45 # default format when js is requested by the client. This lets
46 # ajax:error callback parse the response correctly, even though
48 f.json { render opts.merge(json: {success: false, errors: @errors}) }
49 f.html { render({action: 'error'}.merge(opts)) }
53 def render_exception(e)
54 logger.error e.inspect
55 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
56 err_opts = {status: 422}
57 if e.is_a?(ArvadosApiClient::ApiError)
58 err_opts.merge!(action: 'api_error', locals: {api_error: e})
59 @errors = e.api_response[:errors]
60 elsif @object.andand.errors.andand.full_messages.andand.any?
61 @errors = @object.errors.full_messages
65 # Make user information available on the error page, falling back to the
66 # session cache if the API server is unavailable.
68 load_api_token(session[:arvados_api_token])
69 rescue ArvadosApiClient::ApiError
70 unless session[:user].nil?
72 Thread.current[:user] = User.new(session[:user])
73 rescue ArvadosApiClient::ApiError
74 # This can happen if User's columns are unavailable. Nothing to do.
78 # Preload projects trees for the template. If that's not doable, set empty
79 # trees so error page rendering can proceed. (It's easier to rescue the
80 # exception here than in a template.)
81 unless current_user.nil?
84 rescue ArvadosApiClient::ApiError
85 # Fall back to the default-setting code later.
88 @my_project_tree ||= []
89 @shared_project_tree ||= []
90 render_error(err_opts)
93 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
94 logger.error e.inspect
95 @errors = ["Path not found"]
96 set_thread_api_token do
97 self.render_error(action: '404', status: 404)
101 def load_filters_and_paging_params
102 @order = params[:order] || 'created_at desc'
103 @order = [@order] unless @order.is_a? Array
107 @limit = params[:limit].to_i
112 @offset = params[:offset].to_i
117 filters = params[:filters]
118 if filters.is_a? String
119 filters = Oj.load filters
120 elsif filters.is_a? Array
121 filters = filters.collect do |filter|
122 if filter.is_a? String
123 # Accept filters[]=["foo","=","bar"]
126 # Accept filters=[["foo","=","bar"]]
135 def find_objects_for_index
136 @objects ||= model_class
137 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
142 f.json { render json: @objects }
145 render_pane params[:tab_pane]
154 helper_method :render_pane
155 def render_pane tab_pane, opts={}
157 partial: 'show_' + tab_pane.downcase,
159 comparable: self.respond_to?(:compare),
162 }.merge(opts[:locals] || {})
165 render_to_string render_opts
172 find_objects_for_index if !@objects
176 helper_method :next_page_offset
177 def next_page_offset objects=nil
181 if objects.respond_to?(:result_offset) and
182 objects.respond_to?(:result_limit) and
183 objects.respond_to?(:items_available)
184 next_offset = objects.result_offset + objects.result_limit
185 if next_offset < objects.items_available
193 helper_method :next_page_href
194 def next_page_href with_params={}
196 url_for with_params.merge(offset: next_page_offset)
202 return render_not_found("object not found")
206 extra_attrs = { href: url_for(action: :show, id: @object) }
207 @object.textile_attributes.each do |textile_attr|
208 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
210 render json: @object.attributes.merge(extra_attrs)
213 if params['tab_pane']
214 render_pane params['tab_pane']
215 elsif request.method.in? ['GET', 'HEAD']
218 redirect_to params[:return_to] || @object
226 params[:limit] ||= 40
230 find_objects_for_index if !@objects
232 content: render_to_string(partial: "choose_rows.html",
234 next_page_href: next_page_href(partial: params[:partial])
239 find_objects_for_index if !@objects
240 render partial: 'choose', locals: {multiple: params[:multiple]}
247 return render_not_found("object not found")
252 @object = model_class.new
256 @updates ||= params[@object.resource_param_name.to_sym]
257 @updates.keys.each do |attr|
258 if @object.send(attr).is_a? Hash
259 if @updates[attr].is_a? String
260 @updates[attr] = Oj.load @updates[attr]
262 if params[:merge] || params["merge_#{attr}".to_sym]
263 # Merge provided Hash with current Hash, instead of
265 @updates[attr] = @object.send(attr).with_indifferent_access.
266 deep_merge(@updates[attr].with_indifferent_access)
270 if @object.update_attributes @updates
273 self.render_error status: 422
278 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
279 @new_resource_attrs ||= {}
280 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
281 @object ||= model_class.new @new_resource_attrs, params["options"]
284 f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
291 self.render_error status: 422
295 # Clone the given object, merging any attribute values supplied as
296 # with a create action.
298 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
299 @new_resource_attrs ||= {}
300 @object = @object.dup
301 @object.update_attributes @new_resource_attrs
302 if not @new_resource_attrs[:name] and @object.respond_to? :name
303 if @object.name and @object.name != ''
304 @object.name = "Copy of #{@object.name}"
316 f.json { render json: @object }
318 redirect_to(params[:return_to] || :back)
323 self.render_error status: 422
328 Thread.current[:user]
332 controller_name.classify.constantize
335 def breadcrumb_page_name
336 (@breadcrumb_page_name ||
337 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
346 %w(Attributes Advanced)
351 def strip_token_from_path(path)
352 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
355 def redirect_to_login
358 if request.method.in? ['GET', 'HEAD']
359 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
361 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."
366 @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.']
367 self.render_error status: 422
370 false # For convenience to return from callbacks
373 def using_specific_api_token(api_token)
375 [:arvados_api_token, :user].each do |key|
376 start_values[key] = Thread.current[key]
378 load_api_token(api_token)
382 start_values.each_key { |key| Thread.current[key] = start_values[key] }
387 def accept_uuid_as_id_param
388 if params[:id] and params[:id].match /\D/
389 params[:uuid] = params.delete :id
393 def find_object_by_uuid
397 elsif not params[:uuid].is_a?(String)
398 @object = model_class.where(uuid: params[:uuid]).first
399 elsif params[:uuid].empty?
401 elsif (model_class != Link and
402 resource_class_for_uuid(params[:uuid]) == Link)
403 @name_link = Link.find(params[:uuid])
404 @object = model_class.find(@name_link.head_uuid)
406 @object = model_class.find(params[:uuid])
408 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
409 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
412 render_not_found(error)
419 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
421 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
424 # Set up the thread with the given API token and associated user object.
425 def load_api_token(new_token)
426 Thread.current[:arvados_api_token] = new_token
428 Thread.current[:user] = nil
430 Thread.current[:user] = User.current
434 # If there's a valid api_token parameter, set up the session with that
435 # user's information. Return true if the method redirects the request
436 # (usually a post-login redirect); false otherwise.
437 def setup_user_session
438 return false unless params[:api_token]
439 Thread.current[:arvados_api_token] = params[:api_token]
442 rescue ArvadosApiClient::NotLoggedInException
443 false # We may redirect to login, or not, based on the current action.
445 session[:arvados_api_token] = params[:api_token]
446 # If we later have trouble contacting the API server, we still want
447 # to be able to render basic user information in the UI--see
448 # render_exception above. We store that in the session here. This is
449 # not intended to be used as a general-purpose cache. See #2891.
453 first_name: user.first_name,
454 last_name: user.last_name,
455 is_active: user.is_active,
456 is_admin: user.is_admin,
460 if !request.format.json? and request.method.in? ['GET', 'HEAD']
461 # Repeat this request with api_token in the (new) session
462 # cookie instead of the query string. This prevents API
463 # tokens from appearing in (and being inadvisedly copied
464 # and pasted from) browser Location bars.
465 redirect_to strip_token_from_path(request.fullpath)
471 Thread.current[:arvados_api_token] = nil
475 # Save the session API token in thread-local storage, and yield.
476 # This method also takes care of session setup if the request
477 # provides a valid api_token parameter.
478 # If a token is unavailable or expired, the block is still run, with
480 def set_thread_api_token
481 if Thread.current[:arvados_api_token]
482 yield # An API token has already been found - pass it through.
484 elsif setup_user_session
485 return # A new session was set up and received a response.
489 load_api_token(session[:arvados_api_token])
491 rescue ArvadosApiClient::NotLoggedInException
492 # If we got this error with a token, it must've expired.
493 # Retry the request without a token.
494 unless Thread.current[:arvados_api_token].nil?
499 # Remove token in case this Thread is used for anything else.
504 # Redirect to login/welcome if client provided expired API token (or none at all)
505 def require_thread_api_token
506 if Thread.current[:arvados_api_token]
508 elsif session[:arvados_api_token]
509 # Expired session. Clear it before refreshing login so that,
510 # if this login procedure fails, we end up showing the "please
511 # log in" page instead of getting stuck in a redirect loop.
512 session.delete :arvados_api_token
515 redirect_to welcome_users_path(return_to: request.fullpath)
519 def ensure_current_user_is_admin
520 unless current_user and current_user.is_admin
521 @errors = ['Permission denied']
522 self.render_error status: 401
526 helper_method :unsigned_user_agreements
527 def unsigned_user_agreements
528 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
529 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
530 if not @signed_ua_uuids.index ua.uuid
531 Collection.find(ua.uuid)
536 def check_user_agreements
537 if current_user && !current_user.is_active
538 if not current_user.is_invited
539 return redirect_to inactive_users_path(return_to: request.fullpath)
541 if unsigned_user_agreements.empty?
542 # No agreements to sign. Perhaps we just need to ask?
543 current_user.activate
544 if !current_user.is_active
545 logger.warn "#{current_user.uuid.inspect}: " +
546 "No user agreements to sign, but activate failed!"
549 if !current_user.is_active
550 redirect_to user_agreements_path(return_to: request.fullpath)
556 def check_user_profile
557 if request.method.downcase != 'get' || params[:partial] ||
558 params[:tab_pane] || params[:action_method] ||
559 params[:action] == 'setup_popup'
563 if missing_required_profile?
564 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
569 helper_method :missing_required_profile?
570 def missing_required_profile?
571 missing_required = false
573 profile_config = Rails.configuration.user_profile_form_fields
574 if current_user && profile_config
575 current_user_profile = current_user.prefs[:profile]
576 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
578 if !current_user_profile ||
579 !current_user_profile[entry['key'].to_sym] ||
580 current_user_profile[entry['key'].to_sym].empty?
581 missing_required = true
592 return Rails.configuration.arvados_theme
595 @@notification_tests = []
597 @@notification_tests.push lambda { |controller, current_user|
598 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
601 return lambda { |view|
602 view.render partial: 'notifications/ssh_key_notification'
606 @@notification_tests.push lambda { |controller, current_user|
607 Collection.limit(1).where(created_by: current_user.uuid).each do
610 return lambda { |view|
611 view.render partial: 'notifications/collections_notification'
615 @@notification_tests.push lambda { |controller, current_user|
616 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
619 return lambda { |view|
620 view.render partial: 'notifications/pipelines_notification'
624 def check_user_notifications
625 return if params['tab_pane']
627 @notification_count = 0
630 if current_user.andand.is_active
631 @showallalerts = false
632 @@notification_tests.each do |t|
633 a = t.call(self, current_user)
635 @notification_count += 1
636 @notifications.push a
641 if @notification_count == 0
642 @notification_count = ''
646 helper_method :all_projects
648 @all_projects ||= Group.
649 filter([['group_class','=','project']]).order('name')
652 helper_method :my_projects
654 return @my_projects if @my_projects
657 all_projects.each do |g|
658 root_of[g.uuid] = g.owner_uuid
664 root_of = root_of.each_with_object({}) do |(child, parent), h|
666 h[child] = root_of[parent]
673 @my_projects = @my_projects.select do |g|
674 root_of[g.uuid] == current_user.uuid
678 helper_method :projects_shared_with_me
679 def projects_shared_with_me
680 my_project_uuids = my_projects.collect &:uuid
681 all_projects.reject { |x| x.uuid.in? my_project_uuids }
684 helper_method :recent_jobs_and_pipelines
685 def recent_jobs_and_pipelines
687 PipelineInstance.limit(10)).
689 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
693 helper_method :my_project_tree
699 helper_method :shared_project_tree
700 def shared_project_tree
705 def build_project_trees
706 return if @my_project_tree and @shared_project_tree
707 parent_of = {current_user.uuid => 'me'}
708 all_projects.each do |ob|
709 parent_of[ob.uuid] = ob.owner_uuid
711 children_of = {false => [], 'me' => [current_user]}
712 all_projects.each do |ob|
713 if ob.owner_uuid != current_user.uuid and
714 not parent_of.has_key? ob.owner_uuid
715 parent_of[ob.uuid] = false
717 children_of[parent_of[ob.uuid]] ||= []
718 children_of[parent_of[ob.uuid]] << ob
720 buildtree = lambda do |children_of, root_uuid=false|
722 children_of[root_uuid].andand.each do |ob|
723 tree[ob] = buildtree.call(children_of, ob.uuid)
727 sorted_paths = lambda do |tree, depth=0|
729 tree.keys.sort_by { |ob|
730 ob.is_a?(String) ? ob : ob.friendly_link_name
732 paths << {object: ob, depth: depth}
733 paths += sorted_paths.call tree[ob], depth+1
738 sorted_paths.call buildtree.call(children_of, 'me')
739 @shared_project_tree =
740 sorted_paths.call({'Projects shared with me' =>
741 buildtree.call(children_of, false)})
744 helper_method :get_object
746 if @get_object.nil? and @objects
747 @get_object = @objects.each_with_object({}) do |object, h|
748 h[object.uuid] = object
755 helper_method :project_breadcrumbs
756 def project_breadcrumbs
758 current = @name_link || @object
760 if current.is_a?(Group) and current.group_class == 'project'
761 crumbs.prepend current
763 if current.is_a? Link
764 current = Group.find?(current.tail_uuid)
766 current = Group.find?(current.owner_uuid)
772 helper_method :current_project_uuid
773 def current_project_uuid
774 if @object.is_a? Group and @object.group_class == 'project'
776 elsif @name_link.andand.tail_uuid
778 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
785 # helper method to get links for given object or uuid
786 helper_method :links_for_object
787 def links_for_object object_or_uuid
788 raise ArgumentError, 'No input argument' unless object_or_uuid
789 preload_links_for_objects([object_or_uuid])
790 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
791 @all_links_for[uuid] ||= []
794 # helper method to preload links for given objects and uuids
795 helper_method :preload_links_for_objects
796 def preload_links_for_objects objects_and_uuids
797 @all_links_for ||= {}
799 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
800 return @all_links_for if objects_and_uuids.empty?
802 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
804 # if already preloaded for all of these uuids, return
805 if not uuids.select { |x| @all_links_for[x].nil? }.any?
806 return @all_links_for
810 @all_links_for[x] = []
813 # TODO: make sure we get every page of results from API server
814 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
815 @all_links_for[link.head_uuid] << link
820 # helper method to get a certain number of objects of a specific type
821 # this can be used to replace any uses of: "dataclass.limit(n)"
822 helper_method :get_n_objects_of_class
823 def get_n_objects_of_class dataclass, size
824 @objects_map_for ||= {}
826 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
827 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
829 # if the objects_map_for has a value for this dataclass, and the
830 # size used to retrieve those objects is equal, return it
831 size_key = "#{dataclass.name}_size"
832 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
833 (@objects_map_for[size_key] == size)
834 return @objects_map_for[dataclass.name]
837 @objects_map_for[size_key] = size
838 @objects_map_for[dataclass.name] = dataclass.limit(size)
841 # helper method to get collections for the given uuid
842 helper_method :collections_for_object
843 def collections_for_object uuid
844 raise ArgumentError, 'No input argument' unless uuid
845 preload_collections_for_objects([uuid])
846 @all_collections_for[uuid] ||= []
849 # helper method to preload collections for the given uuids
850 helper_method :preload_collections_for_objects
851 def preload_collections_for_objects uuids
852 @all_collections_for ||= {}
854 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
855 return @all_collections_for if uuids.empty?
857 # if already preloaded for all of these uuids, return
858 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
859 return @all_collections_for
863 @all_collections_for[x] = []
866 # TODO: make sure we get every page of results from API server
867 Collection.where(uuid: uuids).each do |collection|
868 @all_collections_for[collection.uuid] << collection
873 # helper method to get log collections for the given log
874 helper_method :log_collections_for_object
875 def log_collections_for_object log
876 raise ArgumentError, 'No input argument' unless log
878 preload_log_collections_for_objects([log])
881 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
882 if fixup && fixup.size>1
886 @all_log_collections_for[uuid] ||= []
889 # helper method to preload collections for the given uuids
890 helper_method :preload_log_collections_for_objects
891 def preload_log_collections_for_objects logs
892 @all_log_collections_for ||= {}
894 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
895 return @all_log_collections_for if logs.empty?
899 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
900 if fixup && fixup.size>1
907 # if already preloaded for all of these uuids, return
908 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
909 return @all_log_collections_for
913 @all_log_collections_for[x] = []
916 # TODO: make sure we get every page of results from API server
917 Collection.where(uuid: uuids).each do |collection|
918 @all_log_collections_for[collection.uuid] << collection
920 @all_log_collections_for
923 # helper method to get object of a given dataclass and uuid
924 helper_method :object_for_dataclass
925 def object_for_dataclass dataclass, uuid
926 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
927 preload_objects_for_dataclass(dataclass, [uuid])
931 # helper method to preload objects for given dataclass and uuids
932 helper_method :preload_objects_for_dataclass
933 def preload_objects_for_dataclass dataclass, uuids
936 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
937 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
939 return @objects_for if uuids.empty?
941 # if already preloaded for all of these uuids, return
942 if not uuids.select { |x| @objects_for[x].nil? }.any?
946 dataclass.where(uuid: uuids).each do |obj|
947 @objects_for[obj.uuid] = obj