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: [:update_profile] + 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 # If the user has an active session, and the API server is available,
66 # make user information available on the error page.
68 load_api_token(session[:arvados_api_token])
69 rescue ArvadosApiClient::ApiError
72 # Preload projects trees for the template. If that fails, set empty
73 # trees so error page rendering can proceed. (It's easier to rescue the
74 # exception here than in a template.)
77 rescue ArvadosApiClient::ApiError
78 @my_project_tree ||= []
79 @shared_project_tree ||= []
81 render_error(err_opts)
84 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
85 logger.error e.inspect
86 @errors = ["Path not found"]
87 set_thread_api_token do
88 self.render_error(action: '404', status: 404)
92 def load_filters_and_paging_params
95 @limit = params[:limit].to_i
100 @offset = params[:offset].to_i
105 filters = params[:filters]
106 if filters.is_a? String
107 filters = Oj.load filters
108 elsif filters.is_a? Array
109 filters = filters.collect do |filter|
110 if filter.is_a? String
111 # Accept filters[]=["foo","=","bar"]
114 # Accept filters=[["foo","=","bar"]]
123 def find_objects_for_index
124 @objects ||= model_class
125 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
130 f.json { render json: @objects }
132 if params['tab_pane']
133 comparable = self.respond_to? :compare
134 render(partial: 'show_' + params['tab_pane'].downcase,
135 locals: { comparable: comparable, objects: @objects })
145 find_objects_for_index if !@objects
149 helper_method :next_page_offset
150 def next_page_offset objects=nil
154 if objects.respond_to?(:result_offset) and
155 objects.respond_to?(:result_limit) and
156 objects.respond_to?(:items_available)
157 next_offset = objects.result_offset + objects.result_limit
158 if next_offset < objects.items_available
166 helper_method :next_page_href
167 def next_page_href with_params={}
169 url_for with_params.merge(offset: next_page_offset)
175 return render_not_found("object not found")
178 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
180 if params['tab_pane']
181 comparable = self.respond_to? :compare
182 render(partial: 'show_' + params['tab_pane'].downcase,
183 locals: { comparable: comparable, objects: @objects })
184 elsif request.method.in? ['GET', 'HEAD']
187 redirect_to params[:return_to] || @object
195 params[:limit] ||= 40
196 find_objects_for_index if !@objects
201 content: render_to_string(partial: "choose_rows.html",
203 next_page_href: next_page_href(partial: params[:partial])
208 render partial: 'choose', locals: {multiple: params[:multiple]}
215 return render_not_found("object not found")
220 @object = model_class.new
224 @updates ||= params[@object.resource_param_name.to_sym]
225 @updates.keys.each do |attr|
226 if @object.send(attr).is_a? Hash
227 if @updates[attr].is_a? String
228 @updates[attr] = Oj.load @updates[attr]
230 if params[:merge] || params["merge_#{attr}".to_sym]
231 # Merge provided Hash with current Hash, instead of
233 @updates[attr] = @object.send(attr).with_indifferent_access.
234 deep_merge(@updates[attr].with_indifferent_access)
238 if @object.update_attributes @updates
241 self.render_error status: 422
246 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
247 @new_resource_attrs ||= {}
248 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
249 @object ||= model_class.new @new_resource_attrs, params["options"]
252 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
259 self.render_error status: 422
263 # Clone the given object, merging any attribute values supplied as
264 # with a create action.
266 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
267 @new_resource_attrs ||= {}
268 @object = @object.dup
269 @object.update_attributes @new_resource_attrs
270 if not @new_resource_attrs[:name] and @object.respond_to? :name
271 if @object.name and @object.name != ''
272 @object.name = "Copy of #{@object.name}"
284 f.json { render json: @object }
286 redirect_to(params[:return_to] || :back)
291 self.render_error status: 422
296 Thread.current[:user]
300 controller_name.classify.constantize
303 def breadcrumb_page_name
304 (@breadcrumb_page_name ||
305 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
314 %w(Attributes Advanced)
319 def strip_token_from_path(path)
320 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
323 def redirect_to_login
326 if request.method.in? ['GET', 'HEAD']
327 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
329 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."
334 @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.']
335 self.render_error status: 422
338 false # For convenience to return from callbacks
341 def using_specific_api_token(api_token)
343 [:arvados_api_token, :user].each do |key|
344 start_values[key] = Thread.current[key]
346 load_api_token(api_token)
350 start_values.each_key { |key| Thread.current[key] = start_values[key] }
355 def accept_uuid_as_id_param
356 if params[:id] and params[:id].match /\D/
357 params[:uuid] = params.delete :id
361 def find_object_by_uuid
365 elsif not params[:uuid].is_a?(String)
366 @object = model_class.where(uuid: params[:uuid]).first
367 elsif params[:uuid].empty?
369 elsif (model_class != Link and
370 resource_class_for_uuid(params[:uuid]) == Link)
371 @name_link = Link.find(params[:uuid])
372 @object = model_class.find(@name_link.head_uuid)
374 @object = model_class.find(params[:uuid])
376 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
377 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
380 render_not_found(error)
387 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
389 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
392 # Set up the thread with the given API token and associated user object.
393 def load_api_token(new_token)
394 Thread.current[:arvados_api_token] = new_token
396 Thread.current[:user] = nil
397 elsif (new_token == session[:arvados_api_token]) and
398 session[:user].andand[:is_active]
399 Thread.current[:user] = User.new(session[:user])
401 Thread.current[:user] = User.current
405 # If there's a valid api_token parameter, set up the session with that
406 # user's information. Return true if the method redirects the request
407 # (usually a post-login redirect); false otherwise.
408 def setup_user_session
409 return false unless params[:api_token]
410 Thread.current[:arvados_api_token] = params[:api_token]
413 rescue ArvadosApiClient::NotLoggedInException
414 false # We may redirect to login, or not, based on the current action.
416 session[:arvados_api_token] = params[:api_token]
420 first_name: user.first_name,
421 last_name: user.last_name,
422 is_active: user.is_active,
423 is_admin: user.is_admin,
427 if !request.format.json? and request.method.in? ['GET', 'HEAD']
428 # Repeat this request with api_token in the (new) session
429 # cookie instead of the query string. This prevents API
430 # tokens from appearing in (and being inadvisedly copied
431 # and pasted from) browser Location bars.
432 redirect_to strip_token_from_path(request.fullpath)
438 Thread.current[:arvados_api_token] = nil
442 # Save the session API token in thread-local storage, and yield.
443 # This method also takes care of session setup if the request
444 # provides a valid api_token parameter.
445 # If a token is unavailable or expired, the block is still run, with
447 def set_thread_api_token
448 if Thread.current[:arvados_api_token]
449 yield # An API token has already been found - pass it through.
451 elsif setup_user_session
452 return # A new session was set up and received a response.
456 load_api_token(session[:arvados_api_token])
458 rescue ArvadosApiClient::NotLoggedInException
459 # If we got this error with a token, it must've expired.
460 # Retry the request without a token.
461 unless Thread.current[:arvados_api_token].nil?
466 # Remove token in case this Thread is used for anything else.
471 # Reroute this request if an API token is unavailable.
472 def require_thread_api_token
473 if Thread.current[:arvados_api_token]
475 elsif session[:arvados_api_token]
476 # Expired session. Clear it before refreshing login so that,
477 # if this login procedure fails, we end up showing the "please
478 # log in" page instead of getting stuck in a redirect loop.
479 session.delete :arvados_api_token
482 render 'users/welcome'
486 def ensure_current_user_is_admin
487 unless current_user and current_user.is_admin
488 @errors = ['Permission denied']
489 self.render_error status: 401
493 def check_user_agreements
494 if current_user && !current_user.is_active
495 if not current_user.is_invited
496 return render 'users/inactive'
498 signatures = UserAgreement.signatures
499 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
500 @required_user_agreements = UserAgreement.all.map do |ua|
501 if not @signed_ua_uuids.index ua.uuid
502 Collection.find(ua.uuid)
505 if @required_user_agreements.empty?
506 # No agreements to sign. Perhaps we just need to ask?
507 current_user.activate
508 if !current_user.is_active
509 logger.warn "#{current_user.uuid.inspect}: " +
510 "No user agreements to sign, but activate failed!"
513 if !current_user.is_active
514 render 'user_agreements/index'
520 def check_user_profile
521 profile_config = Rails.configuration.user_profile_form_fields
523 if request.method.downcase != 'get' || params[:partial] ||
524 params[:tab_pane] || params[:action_method] ||
525 params[:action] == 'setup_popup'
529 if current_user && profile_config
530 missing_required_profile = false
532 user_prefs = current_user.prefs
533 current_user.reload if !user_prefs[:profile]
534 user_prefs = current_user.prefs
535 current_user_profile = user_prefs[:profile] if user_prefs
537 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
539 if !current_user_profile || !current_user_profile[entry['key'].to_sym]
540 missing_required_profile = true
546 if missing_required_profile
547 render 'users/profile'
554 return Rails.configuration.arvados_theme
557 @@notification_tests = []
559 @@notification_tests.push lambda { |controller, current_user|
560 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
563 return lambda { |view|
564 view.render partial: 'notifications/ssh_key_notification'
568 #@@notification_tests.push lambda { |controller, current_user|
569 # Job.limit(1).where(created_by: current_user.uuid).each do
572 # return lambda { |view|
573 # view.render partial: 'notifications/jobs_notification'
577 @@notification_tests.push lambda { |controller, current_user|
578 Collection.limit(1).where(created_by: current_user.uuid).each do
581 return lambda { |view|
582 view.render partial: 'notifications/collections_notification'
586 @@notification_tests.push lambda { |controller, current_user|
587 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
590 return lambda { |view|
591 view.render partial: 'notifications/pipelines_notification'
595 def check_user_notifications
596 return if params['tab_pane']
598 @notification_count = 0
602 @showallalerts = false
603 @@notification_tests.each do |t|
604 a = t.call(self, current_user)
606 @notification_count += 1
607 @notifications.push a
612 if @notification_count == 0
613 @notification_count = ''
617 helper_method :all_projects
619 @all_projects ||= Group.
620 filter([['group_class','=','project']]).order('name')
623 helper_method :my_projects
625 return @my_projects if @my_projects
628 all_projects.each do |g|
629 root_of[g.uuid] = g.owner_uuid
635 root_of = root_of.each_with_object({}) do |(child, parent), h|
637 h[child] = root_of[parent]
644 @my_projects = @my_projects.select do |g|
645 root_of[g.uuid] == current_user.uuid
649 helper_method :projects_shared_with_me
650 def projects_shared_with_me
651 my_project_uuids = my_projects.collect &:uuid
652 all_projects.reject { |x| x.uuid.in? my_project_uuids }
655 helper_method :recent_jobs_and_pipelines
656 def recent_jobs_and_pipelines
658 PipelineInstance.limit(10)).
660 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
664 helper_method :my_project_tree
670 helper_method :shared_project_tree
671 def shared_project_tree
676 def build_project_trees
677 return if @my_project_tree and @shared_project_tree
678 parent_of = {current_user.uuid => 'me'}
679 all_projects.each do |ob|
680 parent_of[ob.uuid] = ob.owner_uuid
682 children_of = {false => [], 'me' => [current_user]}
683 all_projects.each do |ob|
684 if ob.owner_uuid != current_user.uuid and
685 not parent_of.has_key? ob.owner_uuid
686 parent_of[ob.uuid] = false
688 children_of[parent_of[ob.uuid]] ||= []
689 children_of[parent_of[ob.uuid]] << ob
691 buildtree = lambda do |children_of, root_uuid=false|
693 children_of[root_uuid].andand.each do |ob|
694 tree[ob] = buildtree.call(children_of, ob.uuid)
698 sorted_paths = lambda do |tree, depth=0|
700 tree.keys.sort_by { |ob|
701 ob.is_a?(String) ? ob : ob.friendly_link_name
703 paths << {object: ob, depth: depth}
704 paths += sorted_paths.call tree[ob], depth+1
709 sorted_paths.call buildtree.call(children_of, 'me')
710 @shared_project_tree =
711 sorted_paths.call({'Shared with me' =>
712 buildtree.call(children_of, false)})
715 helper_method :get_object
717 if @get_object.nil? and @objects
718 @get_object = @objects.each_with_object({}) do |object, h|
719 h[object.uuid] = object
726 helper_method :project_breadcrumbs
727 def project_breadcrumbs
729 current = @name_link || @object
731 if current.is_a?(Group) and current.group_class == 'project'
732 crumbs.prepend current
734 if current.is_a? Link
735 current = Group.find?(current.tail_uuid)
737 current = Group.find?(current.owner_uuid)
743 helper_method :current_project_uuid
744 def current_project_uuid
745 if @object.is_a? Group and @object.group_class == 'project'
747 elsif @name_link.andand.tail_uuid
749 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
756 # helper method to get links for given object or uuid
757 helper_method :links_for_object
758 def links_for_object object_or_uuid
759 raise ArgumentError, 'No input argument' unless object_or_uuid
760 preload_links_for_objects([object_or_uuid])
761 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
762 @all_links_for[uuid] ||= []
765 # helper method to preload links for given objects and uuids
766 helper_method :preload_links_for_objects
767 def preload_links_for_objects objects_and_uuids
768 @all_links_for ||= {}
770 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
771 return @all_links_for if objects_and_uuids.empty?
773 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
775 # if already preloaded for all of these uuids, return
776 if not uuids.select { |x| @all_links_for[x].nil? }.any?
777 return @all_links_for
781 @all_links_for[x] = []
784 # TODO: make sure we get every page of results from API server
785 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
786 @all_links_for[link.head_uuid] << link
791 # helper method to get a certain number of objects of a specific type
792 # this can be used to replace any uses of: "dataclass.limit(n)"
793 helper_method :get_n_objects_of_class
794 def get_n_objects_of_class dataclass, size
795 @objects_map_for ||= {}
797 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
798 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
800 # if the objects_map_for has a value for this dataclass, and the
801 # size used to retrieve those objects is equal, return it
802 size_key = "#{dataclass.name}_size"
803 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
804 (@objects_map_for[size_key] == size)
805 return @objects_map_for[dataclass.name]
808 @objects_map_for[size_key] = size
809 @objects_map_for[dataclass.name] = dataclass.limit(size)
812 # helper method to get collections for the given uuid
813 helper_method :collections_for_object
814 def collections_for_object uuid
815 raise ArgumentError, 'No input argument' unless uuid
816 preload_collections_for_objects([uuid])
817 @all_collections_for[uuid] ||= []
820 # helper method to preload collections for the given uuids
821 helper_method :preload_collections_for_objects
822 def preload_collections_for_objects uuids
823 @all_collections_for ||= {}
825 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
826 return @all_collections_for if uuids.empty?
828 # if already preloaded for all of these uuids, return
829 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
830 return @all_collections_for
834 @all_collections_for[x] = []
837 # TODO: make sure we get every page of results from API server
838 Collection.where(uuid: uuids).each do |collection|
839 @all_collections_for[collection.uuid] << collection
844 # helper method to get log collections for the given log
845 helper_method :log_collections_for_object
846 def log_collections_for_object log
847 raise ArgumentError, 'No input argument' unless log
849 preload_log_collections_for_objects([log])
852 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
853 if fixup && fixup.size>1
857 @all_log_collections_for[uuid] ||= []
860 # helper method to preload collections for the given uuids
861 helper_method :preload_log_collections_for_objects
862 def preload_log_collections_for_objects logs
863 @all_log_collections_for ||= {}
865 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
866 return @all_log_collections_for if logs.empty?
870 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
871 if fixup && fixup.size>1
878 # if already preloaded for all of these uuids, return
879 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
880 return @all_log_collections_for
884 @all_log_collections_for[x] = []
887 # TODO: make sure we get every page of results from API server
888 Collection.where(uuid: uuids).each do |collection|
889 @all_log_collections_for[collection.uuid] << collection
891 @all_log_collections_for
894 # helper method to get object of a given dataclass and uuid
895 helper_method :object_for_dataclass
896 def object_for_dataclass dataclass, uuid
897 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
898 preload_objects_for_dataclass(dataclass, [uuid])
902 # helper method to preload objects for given dataclass and uuids
903 helper_method :preload_objects_for_dataclass
904 def preload_objects_for_dataclass dataclass, uuids
907 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
908 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
910 return @objects_for if uuids.empty?
912 # if already preloaded for all of these uuids, return
913 if not uuids.select { |x| @objects_for[x].nil? }.any?
917 dataclass.where(uuid: uuids).each do |obj|
918 @objects_for[obj.uuid] = obj