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"]]
131 # After this, params[:filters] can be trusted to be an array of arrays:
132 params[:filters] = filters
137 def find_objects_for_index
138 @objects ||= model_class
139 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
144 f.json { render json: @objects }
147 render_pane params[:tab_pane]
156 helper_method :render_pane
157 def render_pane tab_pane, opts={}
159 partial: 'show_' + tab_pane.downcase,
161 comparable: self.respond_to?(:compare),
164 }.merge(opts[:locals] || {})
167 render_to_string render_opts
174 find_objects_for_index if !@objects
178 helper_method :next_page_offset
179 def next_page_offset objects=nil
183 if objects.respond_to?(:result_offset) and
184 objects.respond_to?(:result_limit) and
185 objects.respond_to?(:items_available)
186 next_offset = objects.result_offset + objects.result_limit
187 if next_offset < objects.items_available
195 helper_method :next_page_href
196 def next_page_href with_params={}
198 url_for with_params.merge(offset: next_page_offset)
204 return render_not_found("object not found")
208 extra_attrs = { href: url_for(action: :show, id: @object) }
209 @object.textile_attributes.each do |textile_attr|
210 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
212 render json: @object.attributes.merge(extra_attrs)
215 if params['tab_pane']
216 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
217 elsif request.method.in? ['GET', 'HEAD']
220 redirect_to params[:return_to] || @object
228 params[:limit] ||= 40
232 find_objects_for_index if !@objects
234 content: render_to_string(partial: "choose_rows.html",
236 next_page_href: next_page_href(partial: params[:partial])
241 find_objects_for_index if !@objects
242 render partial: 'choose', locals: {multiple: params[:multiple]}
249 return render_not_found("object not found")
254 @object = model_class.new
258 @updates ||= params[@object.resource_param_name.to_sym]
259 @updates.keys.each do |attr|
260 if @object.send(attr).is_a? Hash
261 if @updates[attr].is_a? String
262 @updates[attr] = Oj.load @updates[attr]
264 if params[:merge] || params["merge_#{attr}".to_sym]
265 # Merge provided Hash with current Hash, instead of
267 @updates[attr] = @object.send(attr).with_indifferent_access.
268 deep_merge(@updates[attr].with_indifferent_access)
272 if @object.update_attributes @updates
275 self.render_error status: 422
280 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
281 @new_resource_attrs ||= {}
282 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
283 @object ||= model_class.new @new_resource_attrs, params["options"]
286 f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
293 self.render_error status: 422
297 # Clone the given object, merging any attribute values supplied as
298 # with a create action.
300 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
301 @new_resource_attrs ||= {}
302 @object = @object.dup
303 @object.update_attributes @new_resource_attrs
304 if not @new_resource_attrs[:name] and @object.respond_to? :name
305 if @object.name and @object.name != ''
306 @object.name = "Copy of #{@object.name}"
318 f.json { render json: @object }
320 redirect_to(params[:return_to] || :back)
325 self.render_error status: 422
330 Thread.current[:user]
334 controller_name.classify.constantize
337 def breadcrumb_page_name
338 (@breadcrumb_page_name ||
339 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
348 %w(Attributes Advanced)
353 def strip_token_from_path(path)
354 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
357 def redirect_to_login
360 if request.method.in? ['GET', 'HEAD']
361 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
363 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."
368 @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.']
369 self.render_error status: 422
372 false # For convenience to return from callbacks
375 def using_specific_api_token(api_token)
377 [:arvados_api_token, :user].each do |key|
378 start_values[key] = Thread.current[key]
380 load_api_token(api_token)
384 start_values.each_key { |key| Thread.current[key] = start_values[key] }
389 def accept_uuid_as_id_param
390 if params[:id] and params[:id].match /\D/
391 params[:uuid] = params.delete :id
395 def find_object_by_uuid
399 elsif not params[:uuid].is_a?(String)
400 @object = model_class.where(uuid: params[:uuid]).first
401 elsif params[:uuid].empty?
403 elsif (model_class != Link and
404 resource_class_for_uuid(params[:uuid]) == Link)
405 @name_link = Link.find(params[:uuid])
406 @object = model_class.find(@name_link.head_uuid)
408 @object = model_class.find(params[:uuid])
410 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
411 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
414 render_not_found(error)
421 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
423 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
426 # Set up the thread with the given API token and associated user object.
427 def load_api_token(new_token)
428 Thread.current[:arvados_api_token] = new_token
430 Thread.current[:user] = nil
432 Thread.current[:user] = User.current
436 # If there's a valid api_token parameter, set up the session with that
437 # user's information. Return true if the method redirects the request
438 # (usually a post-login redirect); false otherwise.
439 def setup_user_session
440 return false unless params[:api_token]
441 Thread.current[:arvados_api_token] = params[:api_token]
444 rescue ArvadosApiClient::NotLoggedInException
445 false # We may redirect to login, or not, based on the current action.
447 session[:arvados_api_token] = params[:api_token]
448 # If we later have trouble contacting the API server, we still want
449 # to be able to render basic user information in the UI--see
450 # render_exception above. We store that in the session here. This is
451 # not intended to be used as a general-purpose cache. See #2891.
455 first_name: user.first_name,
456 last_name: user.last_name,
457 is_active: user.is_active,
458 is_admin: user.is_admin,
462 if !request.format.json? and request.method.in? ['GET', 'HEAD']
463 # Repeat this request with api_token in the (new) session
464 # cookie instead of the query string. This prevents API
465 # tokens from appearing in (and being inadvisedly copied
466 # and pasted from) browser Location bars.
467 redirect_to strip_token_from_path(request.fullpath)
473 Thread.current[:arvados_api_token] = nil
477 # Save the session API token in thread-local storage, and yield.
478 # This method also takes care of session setup if the request
479 # provides a valid api_token parameter.
480 # If a token is unavailable or expired, the block is still run, with
482 def set_thread_api_token
483 if Thread.current[:arvados_api_token]
484 yield # An API token has already been found - pass it through.
486 elsif setup_user_session
487 return # A new session was set up and received a response.
491 load_api_token(session[:arvados_api_token])
493 rescue ArvadosApiClient::NotLoggedInException
494 # If we got this error with a token, it must've expired.
495 # Retry the request without a token.
496 unless Thread.current[:arvados_api_token].nil?
501 # Remove token in case this Thread is used for anything else.
506 # Redirect to login/welcome if client provided expired API token (or none at all)
507 def require_thread_api_token
508 if Thread.current[:arvados_api_token]
510 elsif session[:arvados_api_token]
511 # Expired session. Clear it before refreshing login so that,
512 # if this login procedure fails, we end up showing the "please
513 # log in" page instead of getting stuck in a redirect loop.
514 session.delete :arvados_api_token
517 redirect_to welcome_users_path(return_to: request.fullpath)
521 def ensure_current_user_is_admin
522 unless current_user and current_user.is_admin
523 @errors = ['Permission denied']
524 self.render_error status: 401
528 helper_method :unsigned_user_agreements
529 def unsigned_user_agreements
530 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
531 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
532 if not @signed_ua_uuids.index ua.uuid
533 Collection.find(ua.uuid)
538 def check_user_agreements
539 if current_user && !current_user.is_active
540 if not current_user.is_invited
541 return redirect_to inactive_users_path(return_to: request.fullpath)
543 if unsigned_user_agreements.empty?
544 # No agreements to sign. Perhaps we just need to ask?
545 current_user.activate
546 if !current_user.is_active
547 logger.warn "#{current_user.uuid.inspect}: " +
548 "No user agreements to sign, but activate failed!"
551 if !current_user.is_active
552 redirect_to user_agreements_path(return_to: request.fullpath)
558 def check_user_profile
559 if request.method.downcase != 'get' || params[:partial] ||
560 params[:tab_pane] || params[:action_method] ||
561 params[:action] == 'setup_popup'
565 if missing_required_profile?
566 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
571 helper_method :missing_required_profile?
572 def missing_required_profile?
573 missing_required = false
575 profile_config = Rails.configuration.user_profile_form_fields
576 if current_user && profile_config
577 current_user_profile = current_user.prefs[:profile]
578 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
580 if !current_user_profile ||
581 !current_user_profile[entry['key'].to_sym] ||
582 current_user_profile[entry['key'].to_sym].empty?
583 missing_required = true
594 return Rails.configuration.arvados_theme
597 @@notification_tests = []
599 @@notification_tests.push lambda { |controller, current_user|
600 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
603 return lambda { |view|
604 view.render partial: 'notifications/ssh_key_notification'
608 @@notification_tests.push lambda { |controller, current_user|
609 Collection.limit(1).where(created_by: current_user.uuid).each do
612 return lambda { |view|
613 view.render partial: 'notifications/collections_notification'
617 @@notification_tests.push lambda { |controller, current_user|
618 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
621 return lambda { |view|
622 view.render partial: 'notifications/pipelines_notification'
626 def check_user_notifications
627 return if params['tab_pane']
629 @notification_count = 0
632 if current_user.andand.is_active
633 @showallalerts = false
634 @@notification_tests.each do |t|
635 a = t.call(self, current_user)
637 @notification_count += 1
638 @notifications.push a
643 if @notification_count == 0
644 @notification_count = ''
648 helper_method :all_projects
650 @all_projects ||= Group.
651 filter([['group_class','=','project']]).order('name')
654 helper_method :my_projects
656 return @my_projects if @my_projects
659 all_projects.each do |g|
660 root_of[g.uuid] = g.owner_uuid
666 root_of = root_of.each_with_object({}) do |(child, parent), h|
668 h[child] = root_of[parent]
675 @my_projects = @my_projects.select do |g|
676 root_of[g.uuid] == current_user.uuid
680 helper_method :projects_shared_with_me
681 def projects_shared_with_me
682 my_project_uuids = my_projects.collect &:uuid
683 all_projects.reject { |x| x.uuid.in? my_project_uuids }
686 helper_method :recent_jobs_and_pipelines
687 def recent_jobs_and_pipelines
689 PipelineInstance.limit(10)).
691 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
695 helper_method :running_pipelines
696 def running_pipelines
697 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
700 pl.components.each do |k,v|
701 if v.is_a? Hash and v[:job]
702 jobs[v[:job][:uuid]] = {}
707 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
712 pl.components.each do |k,v|
713 if v.is_a? Hash and v[:job]
714 v[:job] = jobs[v[:job][:uuid]]
722 helper_method :finished_pipelines
723 def finished_pipelines lim
724 PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]])
727 helper_method :recent_collections
728 def recent_collections lim
729 c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
731 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
734 {collections: c, owners: own}
737 helper_method :my_project_tree
743 helper_method :shared_project_tree
744 def shared_project_tree
749 def build_project_trees
750 return if @my_project_tree and @shared_project_tree
751 parent_of = {current_user.uuid => 'me'}
752 all_projects.each do |ob|
753 parent_of[ob.uuid] = ob.owner_uuid
755 children_of = {false => [], 'me' => [current_user]}
756 all_projects.each do |ob|
757 if ob.owner_uuid != current_user.uuid and
758 not parent_of.has_key? ob.owner_uuid
759 parent_of[ob.uuid] = false
761 children_of[parent_of[ob.uuid]] ||= []
762 children_of[parent_of[ob.uuid]] << ob
764 buildtree = lambda do |children_of, root_uuid=false|
766 children_of[root_uuid].andand.each do |ob|
767 tree[ob] = buildtree.call(children_of, ob.uuid)
771 sorted_paths = lambda do |tree, depth=0|
773 tree.keys.sort_by { |ob|
774 ob.is_a?(String) ? ob : ob.friendly_link_name
776 paths << {object: ob, depth: depth}
777 paths += sorted_paths.call tree[ob], depth+1
782 sorted_paths.call buildtree.call(children_of, 'me')
783 @shared_project_tree =
784 sorted_paths.call({'Projects shared with me' =>
785 buildtree.call(children_of, false)})
788 helper_method :get_object
790 if @get_object.nil? and @objects
791 @get_object = @objects.each_with_object({}) do |object, h|
792 h[object.uuid] = object
799 helper_method :project_breadcrumbs
800 def project_breadcrumbs
802 current = @name_link || @object
804 if current.is_a?(Group) and current.group_class == 'project'
805 crumbs.prepend current
807 if current.is_a? Link
808 current = Group.find?(current.tail_uuid)
810 current = Group.find?(current.owner_uuid)
816 helper_method :current_project_uuid
817 def current_project_uuid
818 if @object.is_a? Group and @object.group_class == 'project'
820 elsif @name_link.andand.tail_uuid
822 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
829 # helper method to get links for given object or uuid
830 helper_method :links_for_object
831 def links_for_object object_or_uuid
832 raise ArgumentError, 'No input argument' unless object_or_uuid
833 preload_links_for_objects([object_or_uuid])
834 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
835 @all_links_for[uuid] ||= []
838 # helper method to preload links for given objects and uuids
839 helper_method :preload_links_for_objects
840 def preload_links_for_objects objects_and_uuids
841 @all_links_for ||= {}
843 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
844 return @all_links_for if objects_and_uuids.empty?
846 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
848 # if already preloaded for all of these uuids, return
849 if not uuids.select { |x| @all_links_for[x].nil? }.any?
850 return @all_links_for
854 @all_links_for[x] = []
857 # TODO: make sure we get every page of results from API server
858 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
859 @all_links_for[link.head_uuid] << link
864 # helper method to get a certain number of objects of a specific type
865 # this can be used to replace any uses of: "dataclass.limit(n)"
866 helper_method :get_n_objects_of_class
867 def get_n_objects_of_class dataclass, size
868 @objects_map_for ||= {}
870 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
871 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
873 # if the objects_map_for has a value for this dataclass, and the
874 # size used to retrieve those objects is equal, return it
875 size_key = "#{dataclass.name}_size"
876 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
877 (@objects_map_for[size_key] == size)
878 return @objects_map_for[dataclass.name]
881 @objects_map_for[size_key] = size
882 @objects_map_for[dataclass.name] = dataclass.limit(size)
885 # helper method to get collections for the given uuid
886 helper_method :collections_for_object
887 def collections_for_object uuid
888 raise ArgumentError, 'No input argument' unless uuid
889 preload_collections_for_objects([uuid])
890 @all_collections_for[uuid] ||= []
893 # helper method to preload collections for the given uuids
894 helper_method :preload_collections_for_objects
895 def preload_collections_for_objects uuids
896 @all_collections_for ||= {}
898 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
899 return @all_collections_for if uuids.empty?
901 # if already preloaded for all of these uuids, return
902 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
903 return @all_collections_for
907 @all_collections_for[x] = []
910 # TODO: make sure we get every page of results from API server
911 Collection.where(uuid: uuids).each do |collection|
912 @all_collections_for[collection.uuid] << collection
917 # helper method to get log collections for the given log
918 helper_method :log_collections_for_object
919 def log_collections_for_object log
920 raise ArgumentError, 'No input argument' unless log
922 preload_log_collections_for_objects([log])
925 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
926 if fixup && fixup.size>1
930 @all_log_collections_for[uuid] ||= []
933 # helper method to preload collections for the given uuids
934 helper_method :preload_log_collections_for_objects
935 def preload_log_collections_for_objects logs
936 @all_log_collections_for ||= {}
938 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
939 return @all_log_collections_for if logs.empty?
943 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
944 if fixup && fixup.size>1
951 # if already preloaded for all of these uuids, return
952 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
953 return @all_log_collections_for
957 @all_log_collections_for[x] = []
960 # TODO: make sure we get every page of results from API server
961 Collection.where(uuid: uuids).each do |collection|
962 @all_log_collections_for[collection.uuid] << collection
964 @all_log_collections_for
967 # helper method to get object of a given dataclass and uuid
968 helper_method :object_for_dataclass
969 def object_for_dataclass dataclass, uuid
970 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
971 preload_objects_for_dataclass(dataclass, [uuid])
975 # helper method to preload objects for given dataclass and uuids
976 helper_method :preload_objects_for_dataclass
977 def preload_objects_for_dataclass dataclass, uuids
980 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
981 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
983 return @objects_for if uuids.empty?
985 # if already preloaded for all of these uuids, return
986 if not uuids.select { |x| @objects_for[x].nil? }.any?
990 dataclass.where(uuid: uuids).each do |obj|
991 @objects_for[obj.uuid] = obj