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: [: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_content_from_database(@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
227 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 render partial: 'choose', locals: {multiple: params[:multiple]}
246 return render_not_found("object not found")
251 @object = model_class.new
255 @updates ||= params[@object.resource_param_name.to_sym]
256 @updates.keys.each do |attr|
257 if @object.send(attr).is_a? Hash
258 if @updates[attr].is_a? String
259 @updates[attr] = Oj.load @updates[attr]
261 if params[:merge] || params["merge_#{attr}".to_sym]
262 # Merge provided Hash with current Hash, instead of
264 @updates[attr] = @object.send(attr).with_indifferent_access.
265 deep_merge(@updates[attr].with_indifferent_access)
269 if @object.update_attributes @updates
272 self.render_error status: 422
277 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
278 @new_resource_attrs ||= {}
279 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
280 @object ||= model_class.new @new_resource_attrs, params["options"]
283 f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
290 self.render_error status: 422
294 # Clone the given object, merging any attribute values supplied as
295 # with a create action.
297 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
298 @new_resource_attrs ||= {}
299 @object = @object.dup
300 @object.update_attributes @new_resource_attrs
301 if not @new_resource_attrs[:name] and @object.respond_to? :name
302 if @object.name and @object.name != ''
303 @object.name = "Copy of #{@object.name}"
315 f.json { render json: @object }
317 redirect_to(params[:return_to] || :back)
322 self.render_error status: 422
327 Thread.current[:user]
331 controller_name.classify.constantize
334 def breadcrumb_page_name
335 (@breadcrumb_page_name ||
336 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
345 %w(Attributes Advanced)
350 def strip_token_from_path(path)
351 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
354 def redirect_to_login
357 if request.method.in? ['GET', 'HEAD']
358 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
360 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."
365 @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.']
366 self.render_error status: 422
369 false # For convenience to return from callbacks
372 def using_specific_api_token(api_token)
374 [:arvados_api_token, :user].each do |key|
375 start_values[key] = Thread.current[key]
377 load_api_token(api_token)
381 start_values.each_key { |key| Thread.current[key] = start_values[key] }
386 def accept_uuid_as_id_param
387 if params[:id] and params[:id].match /\D/
388 params[:uuid] = params.delete :id
392 def find_object_by_uuid
396 elsif not params[:uuid].is_a?(String)
397 @object = model_class.where(uuid: params[:uuid]).first
398 elsif params[:uuid].empty?
400 elsif (model_class != Link and
401 resource_class_for_uuid(params[:uuid]) == Link)
402 @name_link = Link.find(params[:uuid])
403 @object = model_class.find(@name_link.head_uuid)
405 @object = model_class.find(params[:uuid])
407 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
408 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
411 render_not_found(error)
418 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
420 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
423 # Set up the thread with the given API token and associated user object.
424 def load_api_token(new_token)
425 Thread.current[:arvados_api_token] = new_token
427 Thread.current[:user] = nil
429 Thread.current[:user] = User.current
433 # If there's a valid api_token parameter, set up the session with that
434 # user's information. Return true if the method redirects the request
435 # (usually a post-login redirect); false otherwise.
436 def setup_user_session
437 return false unless params[:api_token]
438 Thread.current[:arvados_api_token] = params[:api_token]
441 rescue ArvadosApiClient::NotLoggedInException
442 false # We may redirect to login, or not, based on the current action.
444 session[:arvados_api_token] = params[:api_token]
445 # If we later have trouble contacting the API server, we still want
446 # to be able to render basic user information in the UI--see
447 # render_exception above. We store that in the session here. This is
448 # not intended to be used as a general-purpose cache. See #2891.
452 first_name: user.first_name,
453 last_name: user.last_name,
454 is_active: user.is_active,
455 is_admin: user.is_admin,
459 if !request.format.json? and request.method.in? ['GET', 'HEAD']
460 # Repeat this request with api_token in the (new) session
461 # cookie instead of the query string. This prevents API
462 # tokens from appearing in (and being inadvisedly copied
463 # and pasted from) browser Location bars.
464 redirect_to strip_token_from_path(request.fullpath)
470 Thread.current[:arvados_api_token] = nil
474 # Save the session API token in thread-local storage, and yield.
475 # This method also takes care of session setup if the request
476 # provides a valid api_token parameter.
477 # If a token is unavailable or expired, the block is still run, with
479 def set_thread_api_token
480 if Thread.current[:arvados_api_token]
481 yield # An API token has already been found - pass it through.
483 elsif setup_user_session
484 return # A new session was set up and received a response.
488 load_api_token(session[:arvados_api_token])
490 rescue ArvadosApiClient::NotLoggedInException
491 # If we got this error with a token, it must've expired.
492 # Retry the request without a token.
493 unless Thread.current[:arvados_api_token].nil?
498 # Remove token in case this Thread is used for anything else.
503 # Redirect to login/welcome if client provided expired API token (or none at all)
504 def require_thread_api_token
505 if Thread.current[:arvados_api_token]
507 elsif session[:arvados_api_token]
508 # Expired session. Clear it before refreshing login so that,
509 # if this login procedure fails, we end up showing the "please
510 # log in" page instead of getting stuck in a redirect loop.
511 session.delete :arvados_api_token
514 redirect_to welcome_users_path(return_to: request.fullpath)
518 def ensure_current_user_is_admin
519 unless current_user and current_user.is_admin
520 @errors = ['Permission denied']
521 self.render_error status: 401
525 helper_method :unsigned_user_agreements
526 def unsigned_user_agreements
527 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
528 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
529 if not @signed_ua_uuids.index ua.uuid
530 Collection.find(ua.uuid)
535 def check_user_agreements
536 if current_user && !current_user.is_active
537 if not current_user.is_invited
538 return redirect_to inactive_users_path(return_to: request.fullpath)
540 if unsigned_user_agreements.empty?
541 # No agreements to sign. Perhaps we just need to ask?
542 current_user.activate
543 if !current_user.is_active
544 logger.warn "#{current_user.uuid.inspect}: " +
545 "No user agreements to sign, but activate failed!"
548 if !current_user.is_active
549 redirect_to user_agreements_path(return_to: request.fullpath)
555 def check_user_profile
556 if request.method.downcase != 'get' || params[:partial] ||
557 params[:tab_pane] || params[:action_method] ||
558 params[:action] == 'setup_popup'
562 if missing_required_profile?
563 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
568 helper_method :missing_required_profile?
569 def missing_required_profile?
570 missing_required = false
572 profile_config = Rails.configuration.user_profile_form_fields
573 if current_user && profile_config
574 current_user_profile = current_user.prefs[:profile]
575 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
577 if !current_user_profile ||
578 !current_user_profile[entry['key'].to_sym] ||
579 current_user_profile[entry['key'].to_sym].empty?
580 missing_required = true
591 return Rails.configuration.arvados_theme
594 @@notification_tests = []
596 @@notification_tests.push lambda { |controller, current_user|
597 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
600 return lambda { |view|
601 view.render partial: 'notifications/ssh_key_notification'
605 @@notification_tests.push lambda { |controller, current_user|
606 Collection.limit(1).where(created_by: current_user.uuid).each do
609 return lambda { |view|
610 view.render partial: 'notifications/collections_notification'
614 @@notification_tests.push lambda { |controller, current_user|
615 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
618 return lambda { |view|
619 view.render partial: 'notifications/pipelines_notification'
623 def check_user_notifications
624 return if params['tab_pane']
626 @notification_count = 0
629 if current_user.andand.is_active
630 @showallalerts = false
631 @@notification_tests.each do |t|
632 a = t.call(self, current_user)
634 @notification_count += 1
635 @notifications.push a
640 if @notification_count == 0
641 @notification_count = ''
645 helper_method :all_projects
647 @all_projects ||= Group.
648 filter([['group_class','=','project']]).order('name')
651 helper_method :my_projects
653 return @my_projects if @my_projects
656 all_projects.each do |g|
657 root_of[g.uuid] = g.owner_uuid
663 root_of = root_of.each_with_object({}) do |(child, parent), h|
665 h[child] = root_of[parent]
672 @my_projects = @my_projects.select do |g|
673 root_of[g.uuid] == current_user.uuid
677 helper_method :projects_shared_with_me
678 def projects_shared_with_me
679 my_project_uuids = my_projects.collect &:uuid
680 all_projects.reject { |x| x.uuid.in? my_project_uuids }
683 helper_method :recent_jobs_and_pipelines
684 def recent_jobs_and_pipelines
686 PipelineInstance.limit(10)).
688 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
692 helper_method :my_project_tree
698 helper_method :shared_project_tree
699 def shared_project_tree
704 def build_project_trees
705 return if @my_project_tree and @shared_project_tree
706 parent_of = {current_user.uuid => 'me'}
707 all_projects.each do |ob|
708 parent_of[ob.uuid] = ob.owner_uuid
710 children_of = {false => [], 'me' => [current_user]}
711 all_projects.each do |ob|
712 if ob.owner_uuid != current_user.uuid and
713 not parent_of.has_key? ob.owner_uuid
714 parent_of[ob.uuid] = false
716 children_of[parent_of[ob.uuid]] ||= []
717 children_of[parent_of[ob.uuid]] << ob
719 buildtree = lambda do |children_of, root_uuid=false|
721 children_of[root_uuid].andand.each do |ob|
722 tree[ob] = buildtree.call(children_of, ob.uuid)
726 sorted_paths = lambda do |tree, depth=0|
728 tree.keys.sort_by { |ob|
729 ob.is_a?(String) ? ob : ob.friendly_link_name
731 paths << {object: ob, depth: depth}
732 paths += sorted_paths.call tree[ob], depth+1
737 sorted_paths.call buildtree.call(children_of, 'me')
738 @shared_project_tree =
739 sorted_paths.call({'Shared with me' =>
740 buildtree.call(children_of, false)})
743 helper_method :get_object
745 if @get_object.nil? and @objects
746 @get_object = @objects.each_with_object({}) do |object, h|
747 h[object.uuid] = object
754 helper_method :project_breadcrumbs
755 def project_breadcrumbs
757 current = @name_link || @object
759 if current.is_a?(Group) and current.group_class == 'project'
760 crumbs.prepend current
762 if current.is_a? Link
763 current = Group.find?(current.tail_uuid)
765 current = Group.find?(current.owner_uuid)
771 helper_method :current_project_uuid
772 def current_project_uuid
773 if @object.is_a? Group and @object.group_class == 'project'
775 elsif @name_link.andand.tail_uuid
777 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
784 # helper method to get links for given object or uuid
785 helper_method :links_for_object
786 def links_for_object object_or_uuid
787 raise ArgumentError, 'No input argument' unless object_or_uuid
788 preload_links_for_objects([object_or_uuid])
789 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
790 @all_links_for[uuid] ||= []
793 # helper method to preload links for given objects and uuids
794 helper_method :preload_links_for_objects
795 def preload_links_for_objects objects_and_uuids
796 @all_links_for ||= {}
798 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
799 return @all_links_for if objects_and_uuids.empty?
801 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
803 # if already preloaded for all of these uuids, return
804 if not uuids.select { |x| @all_links_for[x].nil? }.any?
805 return @all_links_for
809 @all_links_for[x] = []
812 # TODO: make sure we get every page of results from API server
813 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
814 @all_links_for[link.head_uuid] << link
819 # helper method to get a certain number of objects of a specific type
820 # this can be used to replace any uses of: "dataclass.limit(n)"
821 helper_method :get_n_objects_of_class
822 def get_n_objects_of_class dataclass, size
823 @objects_map_for ||= {}
825 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
826 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
828 # if the objects_map_for has a value for this dataclass, and the
829 # size used to retrieve those objects is equal, return it
830 size_key = "#{dataclass.name}_size"
831 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
832 (@objects_map_for[size_key] == size)
833 return @objects_map_for[dataclass.name]
836 @objects_map_for[size_key] = size
837 @objects_map_for[dataclass.name] = dataclass.limit(size)
840 # helper method to get collections for the given uuid
841 helper_method :collections_for_object
842 def collections_for_object uuid
843 raise ArgumentError, 'No input argument' unless uuid
844 preload_collections_for_objects([uuid])
845 @all_collections_for[uuid] ||= []
848 # helper method to preload collections for the given uuids
849 helper_method :preload_collections_for_objects
850 def preload_collections_for_objects uuids
851 @all_collections_for ||= {}
853 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
854 return @all_collections_for if uuids.empty?
856 # if already preloaded for all of these uuids, return
857 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
858 return @all_collections_for
862 @all_collections_for[x] = []
865 # TODO: make sure we get every page of results from API server
866 Collection.where(uuid: uuids).each do |collection|
867 @all_collections_for[collection.uuid] << collection
872 # helper method to get log collections for the given log
873 helper_method :log_collections_for_object
874 def log_collections_for_object log
875 raise ArgumentError, 'No input argument' unless log
877 preload_log_collections_for_objects([log])
880 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
881 if fixup && fixup.size>1
885 @all_log_collections_for[uuid] ||= []
888 # helper method to preload collections for the given uuids
889 helper_method :preload_log_collections_for_objects
890 def preload_log_collections_for_objects logs
891 @all_log_collections_for ||= {}
893 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
894 return @all_log_collections_for if logs.empty?
898 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
899 if fixup && fixup.size>1
906 # if already preloaded for all of these uuids, return
907 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
908 return @all_log_collections_for
912 @all_log_collections_for[x] = []
915 # TODO: make sure we get every page of results from API server
916 Collection.where(uuid: uuids).each do |collection|
917 @all_log_collections_for[collection.uuid] << collection
919 @all_log_collections_for
922 # helper method to get object of a given dataclass and uuid
923 helper_method :object_for_dataclass
924 def object_for_dataclass dataclass, uuid
925 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
926 preload_objects_for_dataclass(dataclass, [uuid])
930 # helper method to preload objects for given dataclass and uuids
931 helper_method :preload_objects_for_dataclass
932 def preload_objects_for_dataclass dataclass, uuids
935 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
936 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
938 return @objects_for if uuids.empty?
940 # if already preloaded for all of these uuids, return
941 if not uuids.select { |x| @objects_for[x].nil? }.any?
945 dataclass.where(uuid: uuids).each do |obj|
946 @objects_for[obj.uuid] = obj