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")
205 f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
207 if params['tab_pane']
208 render_pane params['tab_pane']
209 elsif request.method.in? ['GET', 'HEAD']
212 redirect_to params[:return_to] || @object
220 params[:limit] ||= 40
224 find_objects_for_index if !@objects
226 content: render_to_string(partial: "choose_rows.html",
228 next_page_href: next_page_href(partial: params[:partial])
233 find_objects_for_index if !@objects
234 render partial: 'choose', locals: {multiple: params[:multiple]}
241 return render_not_found("object not found")
246 @object = model_class.new
250 @updates ||= params[@object.resource_param_name.to_sym]
251 @updates.keys.each do |attr|
252 if @object.send(attr).is_a? Hash
253 if @updates[attr].is_a? String
254 @updates[attr] = Oj.load @updates[attr]
256 if params[:merge] || params["merge_#{attr}".to_sym]
257 # Merge provided Hash with current Hash, instead of
259 @updates[attr] = @object.send(attr).with_indifferent_access.
260 deep_merge(@updates[attr].with_indifferent_access)
264 if @object.update_attributes @updates
267 self.render_error status: 422
272 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
273 @new_resource_attrs ||= {}
274 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
275 @object ||= model_class.new @new_resource_attrs, params["options"]
278 f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
285 self.render_error status: 422
289 # Clone the given object, merging any attribute values supplied as
290 # with a create action.
292 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
293 @new_resource_attrs ||= {}
294 @object = @object.dup
295 @object.update_attributes @new_resource_attrs
296 if not @new_resource_attrs[:name] and @object.respond_to? :name
297 if @object.name and @object.name != ''
298 @object.name = "Copy of #{@object.name}"
310 f.json { render json: @object }
312 redirect_to(params[:return_to] || :back)
317 self.render_error status: 422
322 Thread.current[:user]
326 controller_name.classify.constantize
329 def breadcrumb_page_name
330 (@breadcrumb_page_name ||
331 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
340 %w(Attributes Advanced)
345 def strip_token_from_path(path)
346 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
349 def redirect_to_login
352 if request.method.in? ['GET', 'HEAD']
353 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
355 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."
360 @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.']
361 self.render_error status: 422
364 false # For convenience to return from callbacks
367 def using_specific_api_token(api_token)
369 [:arvados_api_token, :user].each do |key|
370 start_values[key] = Thread.current[key]
372 load_api_token(api_token)
376 start_values.each_key { |key| Thread.current[key] = start_values[key] }
381 def accept_uuid_as_id_param
382 if params[:id] and params[:id].match /\D/
383 params[:uuid] = params.delete :id
387 def find_object_by_uuid
391 elsif not params[:uuid].is_a?(String)
392 @object = model_class.where(uuid: params[:uuid]).first
393 elsif params[:uuid].empty?
395 elsif (model_class != Link and
396 resource_class_for_uuid(params[:uuid]) == Link)
397 @name_link = Link.find(params[:uuid])
398 @object = model_class.find(@name_link.head_uuid)
400 @object = model_class.find(params[:uuid])
402 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
403 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
406 render_not_found(error)
413 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
415 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
418 # Set up the thread with the given API token and associated user object.
419 def load_api_token(new_token)
420 Thread.current[:arvados_api_token] = new_token
422 Thread.current[:user] = nil
424 Thread.current[:user] = User.current
428 # If there's a valid api_token parameter, set up the session with that
429 # user's information. Return true if the method redirects the request
430 # (usually a post-login redirect); false otherwise.
431 def setup_user_session
432 return false unless params[:api_token]
433 Thread.current[:arvados_api_token] = params[:api_token]
436 rescue ArvadosApiClient::NotLoggedInException
437 false # We may redirect to login, or not, based on the current action.
439 session[:arvados_api_token] = params[:api_token]
440 # If we later have trouble contacting the API server, we still want
441 # to be able to render basic user information in the UI--see
442 # render_exception above. We store that in the session here. This is
443 # not intended to be used as a general-purpose cache. See #2891.
447 first_name: user.first_name,
448 last_name: user.last_name,
449 is_active: user.is_active,
450 is_admin: user.is_admin,
454 if !request.format.json? and request.method.in? ['GET', 'HEAD']
455 # Repeat this request with api_token in the (new) session
456 # cookie instead of the query string. This prevents API
457 # tokens from appearing in (and being inadvisedly copied
458 # and pasted from) browser Location bars.
459 redirect_to strip_token_from_path(request.fullpath)
465 Thread.current[:arvados_api_token] = nil
469 # Save the session API token in thread-local storage, and yield.
470 # This method also takes care of session setup if the request
471 # provides a valid api_token parameter.
472 # If a token is unavailable or expired, the block is still run, with
474 def set_thread_api_token
475 if Thread.current[:arvados_api_token]
476 yield # An API token has already been found - pass it through.
478 elsif setup_user_session
479 return # A new session was set up and received a response.
483 load_api_token(session[:arvados_api_token])
485 rescue ArvadosApiClient::NotLoggedInException
486 # If we got this error with a token, it must've expired.
487 # Retry the request without a token.
488 unless Thread.current[:arvados_api_token].nil?
493 # Remove token in case this Thread is used for anything else.
498 # Redirect to login/welcome if client provided expired API token (or none at all)
499 def require_thread_api_token
500 if Thread.current[:arvados_api_token]
502 elsif session[:arvados_api_token]
503 # Expired session. Clear it before refreshing login so that,
504 # if this login procedure fails, we end up showing the "please
505 # log in" page instead of getting stuck in a redirect loop.
506 session.delete :arvados_api_token
509 redirect_to welcome_users_path(return_to: request.fullpath)
513 def ensure_current_user_is_admin
514 unless current_user and current_user.is_admin
515 @errors = ['Permission denied']
516 self.render_error status: 401
520 helper_method :unsigned_user_agreements
521 def unsigned_user_agreements
522 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
523 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
524 if not @signed_ua_uuids.index ua.uuid
525 Collection.find(ua.uuid)
530 def check_user_agreements
531 if current_user && !current_user.is_active
532 if not current_user.is_invited
533 return redirect_to inactive_users_path(return_to: request.fullpath)
535 if unsigned_user_agreements.empty?
536 # No agreements to sign. Perhaps we just need to ask?
537 current_user.activate
538 if !current_user.is_active
539 logger.warn "#{current_user.uuid.inspect}: " +
540 "No user agreements to sign, but activate failed!"
543 if !current_user.is_active
544 redirect_to user_agreements_path(return_to: request.fullpath)
550 def check_user_profile
551 if request.method.downcase != 'get' || params[:partial] ||
552 params[:tab_pane] || params[:action_method] ||
553 params[:action] == 'setup_popup'
557 if missing_required_profile?
558 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
563 helper_method :missing_required_profile?
564 def missing_required_profile?
565 missing_required = false
567 profile_config = Rails.configuration.user_profile_form_fields
568 if current_user && profile_config
569 current_user_profile = current_user.prefs[:profile]
570 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
572 if !current_user_profile ||
573 !current_user_profile[entry['key'].to_sym] ||
574 current_user_profile[entry['key'].to_sym].empty?
575 missing_required = true
586 return Rails.configuration.arvados_theme
589 @@notification_tests = []
591 @@notification_tests.push lambda { |controller, current_user|
592 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
595 return lambda { |view|
596 view.render partial: 'notifications/ssh_key_notification'
600 @@notification_tests.push lambda { |controller, current_user|
601 Collection.limit(1).where(created_by: current_user.uuid).each do
604 return lambda { |view|
605 view.render partial: 'notifications/collections_notification'
609 @@notification_tests.push lambda { |controller, current_user|
610 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
613 return lambda { |view|
614 view.render partial: 'notifications/pipelines_notification'
618 def check_user_notifications
619 return if params['tab_pane']
621 @notification_count = 0
624 if current_user.andand.is_active
625 @showallalerts = false
626 @@notification_tests.each do |t|
627 a = t.call(self, current_user)
629 @notification_count += 1
630 @notifications.push a
635 if @notification_count == 0
636 @notification_count = ''
640 helper_method :all_projects
642 @all_projects ||= Group.
643 filter([['group_class','=','project']]).order('name')
646 helper_method :my_projects
648 return @my_projects if @my_projects
651 all_projects.each do |g|
652 root_of[g.uuid] = g.owner_uuid
658 root_of = root_of.each_with_object({}) do |(child, parent), h|
660 h[child] = root_of[parent]
667 @my_projects = @my_projects.select do |g|
668 root_of[g.uuid] == current_user.uuid
672 helper_method :projects_shared_with_me
673 def projects_shared_with_me
674 my_project_uuids = my_projects.collect &:uuid
675 all_projects.reject { |x| x.uuid.in? my_project_uuids }
678 helper_method :recent_jobs_and_pipelines
679 def recent_jobs_and_pipelines
681 PipelineInstance.limit(10)).
683 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
687 helper_method :my_project_tree
693 helper_method :shared_project_tree
694 def shared_project_tree
699 def build_project_trees
700 return if @my_project_tree and @shared_project_tree
701 parent_of = {current_user.uuid => 'me'}
702 all_projects.each do |ob|
703 parent_of[ob.uuid] = ob.owner_uuid
705 children_of = {false => [], 'me' => [current_user]}
706 all_projects.each do |ob|
707 if ob.owner_uuid != current_user.uuid and
708 not parent_of.has_key? ob.owner_uuid
709 parent_of[ob.uuid] = false
711 children_of[parent_of[ob.uuid]] ||= []
712 children_of[parent_of[ob.uuid]] << ob
714 buildtree = lambda do |children_of, root_uuid=false|
716 children_of[root_uuid].andand.each do |ob|
717 tree[ob] = buildtree.call(children_of, ob.uuid)
721 sorted_paths = lambda do |tree, depth=0|
723 tree.keys.sort_by { |ob|
724 ob.is_a?(String) ? ob : ob.friendly_link_name
726 paths << {object: ob, depth: depth}
727 paths += sorted_paths.call tree[ob], depth+1
732 sorted_paths.call buildtree.call(children_of, 'me')
733 @shared_project_tree =
734 sorted_paths.call({'Shared with me' =>
735 buildtree.call(children_of, false)})
738 helper_method :get_object
740 if @get_object.nil? and @objects
741 @get_object = @objects.each_with_object({}) do |object, h|
742 h[object.uuid] = object
749 helper_method :project_breadcrumbs
750 def project_breadcrumbs
752 current = @name_link || @object
754 if current.is_a?(Group) and current.group_class == 'project'
755 crumbs.prepend current
757 if current.is_a? Link
758 current = Group.find?(current.tail_uuid)
760 current = Group.find?(current.owner_uuid)
766 helper_method :current_project_uuid
767 def current_project_uuid
768 if @object.is_a? Group and @object.group_class == 'project'
770 elsif @name_link.andand.tail_uuid
772 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
779 # helper method to get links for given object or uuid
780 helper_method :links_for_object
781 def links_for_object object_or_uuid
782 raise ArgumentError, 'No input argument' unless object_or_uuid
783 preload_links_for_objects([object_or_uuid])
784 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
785 @all_links_for[uuid] ||= []
788 # helper method to preload links for given objects and uuids
789 helper_method :preload_links_for_objects
790 def preload_links_for_objects objects_and_uuids
791 @all_links_for ||= {}
793 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
794 return @all_links_for if objects_and_uuids.empty?
796 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
798 # if already preloaded for all of these uuids, return
799 if not uuids.select { |x| @all_links_for[x].nil? }.any?
800 return @all_links_for
804 @all_links_for[x] = []
807 # TODO: make sure we get every page of results from API server
808 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
809 @all_links_for[link.head_uuid] << link
814 # helper method to get a certain number of objects of a specific type
815 # this can be used to replace any uses of: "dataclass.limit(n)"
816 helper_method :get_n_objects_of_class
817 def get_n_objects_of_class dataclass, size
818 @objects_map_for ||= {}
820 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
821 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
823 # if the objects_map_for has a value for this dataclass, and the
824 # size used to retrieve those objects is equal, return it
825 size_key = "#{dataclass.name}_size"
826 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
827 (@objects_map_for[size_key] == size)
828 return @objects_map_for[dataclass.name]
831 @objects_map_for[size_key] = size
832 @objects_map_for[dataclass.name] = dataclass.limit(size)
835 # helper method to get collections for the given uuid
836 helper_method :collections_for_object
837 def collections_for_object uuid
838 raise ArgumentError, 'No input argument' unless uuid
839 preload_collections_for_objects([uuid])
840 @all_collections_for[uuid] ||= []
843 # helper method to preload collections for the given uuids
844 helper_method :preload_collections_for_objects
845 def preload_collections_for_objects uuids
846 @all_collections_for ||= {}
848 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
849 return @all_collections_for if uuids.empty?
851 # if already preloaded for all of these uuids, return
852 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
853 return @all_collections_for
857 @all_collections_for[x] = []
860 # TODO: make sure we get every page of results from API server
861 Collection.where(uuid: uuids).each do |collection|
862 @all_collections_for[collection.uuid] << collection
867 # helper method to get log collections for the given log
868 helper_method :log_collections_for_object
869 def log_collections_for_object log
870 raise ArgumentError, 'No input argument' unless log
872 preload_log_collections_for_objects([log])
875 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
876 if fixup && fixup.size>1
880 @all_log_collections_for[uuid] ||= []
883 # helper method to preload collections for the given uuids
884 helper_method :preload_log_collections_for_objects
885 def preload_log_collections_for_objects logs
886 @all_log_collections_for ||= {}
888 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
889 return @all_log_collections_for if logs.empty?
893 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
894 if fixup && fixup.size>1
901 # if already preloaded for all of these uuids, return
902 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
903 return @all_log_collections_for
907 @all_log_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_log_collections_for[collection.uuid] << collection
914 @all_log_collections_for
917 # helper method to get object of a given dataclass and uuid
918 helper_method :object_for_dataclass
919 def object_for_dataclass dataclass, uuid
920 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
921 preload_objects_for_dataclass(dataclass, [uuid])
925 # helper method to preload objects for given dataclass and uuids
926 helper_method :preload_objects_for_dataclass
927 def preload_objects_for_dataclass dataclass, uuids
930 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
931 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
933 return @objects_for if uuids.empty?
935 # if already preloaded for all of these uuids, return
936 if not uuids.select { |x| @objects_for[x].nil? }.any?
940 dataclass.where(uuid: uuids).each do |obj|
941 @objects_for[obj.uuid] = obj