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 :check_user_agreements, except: ERROR_ACTIONS
16 before_filter :check_user_profile, except: [:update_profile] + ERROR_ACTIONS
17 before_filter :check_user_notifications, except: ERROR_ACTIONS
18 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
19 before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
23 rescue_from(ActiveRecord::RecordNotFound,
24 ActionController::RoutingError,
25 ActionController::UnknownController,
26 AbstractController::ActionNotFound,
27 with: :render_not_found)
28 rescue_from(Exception,
29 ActionController::UrlGenerationError,
30 with: :render_exception)
33 def unprocessable(message=nil)
36 @errors << message if message
37 render_error status: 422
40 def render_error(opts={})
43 # json must come before html here, so it gets used as the
44 # default format when js is requested by the client. This lets
45 # ajax:error callback parse the response correctly, even though
47 f.json { render opts.merge(json: {success: false, errors: @errors}) }
48 f.html { render({action: 'error'}.merge(opts)) }
52 def render_exception(e)
53 logger.error e.inspect
54 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
55 err_opts = {status: 422}
56 if e.is_a?(ArvadosApiClient::ApiError)
57 err_opts.merge!(action: 'api_error', locals: {api_error: e})
58 @errors = e.api_response[:errors]
59 elsif @object.andand.errors.andand.full_messages.andand.any?
60 @errors = @object.errors.full_messages
64 # If the user has an active session, and the API server is available,
65 # make user information available on the error page.
67 load_api_token(session[:arvados_api_token])
68 rescue ArvadosApiClient::ApiError
71 # Preload projects trees for the template. If that fails, set empty
72 # trees so error page rendering can proceed. (It's easier to rescue the
73 # exception here than in a template.)
76 rescue ArvadosApiClient::ApiError
77 @my_project_tree ||= []
78 @shared_project_tree ||= []
80 render_error(err_opts)
83 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
84 logger.error e.inspect
85 @errors = ["Path not found"]
86 set_thread_api_token do
87 self.render_error(action: '404', status: 404)
91 def load_filters_and_paging_params
94 @limit = params[:limit].to_i
99 @offset = params[:offset].to_i
104 filters = params[:filters]
105 if filters.is_a? String
106 filters = Oj.load filters
107 elsif filters.is_a? Array
108 filters = filters.collect do |filter|
109 if filter.is_a? String
110 # Accept filters[]=["foo","=","bar"]
113 # Accept filters=[["foo","=","bar"]]
122 def find_objects_for_index
123 @objects ||= model_class
124 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
129 f.json { render json: @objects }
131 if params['tab_pane']
132 comparable = self.respond_to? :compare
133 render(partial: 'show_' + params['tab_pane'].downcase,
134 locals: { comparable: comparable, objects: @objects })
144 find_objects_for_index if !@objects
148 helper_method :next_page_offset
149 def next_page_offset objects=nil
153 if objects.respond_to?(:result_offset) and
154 objects.respond_to?(:result_limit) and
155 objects.respond_to?(:items_available)
156 next_offset = objects.result_offset + objects.result_limit
157 if next_offset < objects.items_available
165 helper_method :next_page_href
166 def next_page_href with_params={}
168 url_for with_params.merge(offset: next_page_offset)
174 return render_not_found("object not found")
177 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
179 if params['tab_pane']
180 comparable = self.respond_to? :compare
181 render(partial: 'show_' + params['tab_pane'].downcase,
182 locals: { comparable: comparable, objects: @objects })
183 elsif request.method.in? ['GET', 'HEAD']
186 redirect_to params[:return_to] || @object
194 params[:limit] ||= 40
195 find_objects_for_index if !@objects
200 content: render_to_string(partial: "choose_rows.html",
202 next_page_href: next_page_href(partial: params[:partial])
207 render partial: 'choose', locals: {multiple: params[:multiple]}
214 return render_not_found("object not found")
219 @object = model_class.new
223 @updates ||= params[@object.resource_param_name.to_sym]
224 @updates.keys.each do |attr|
225 if @object.send(attr).is_a? Hash
226 if @updates[attr].is_a? String
227 @updates[attr] = Oj.load @updates[attr]
229 if params[:merge] || params["merge_#{attr}".to_sym]
230 # Merge provided Hash with current Hash, instead of
232 @updates[attr] = @object.send(attr).with_indifferent_access.
233 deep_merge(@updates[attr].with_indifferent_access)
237 if @object.update_attributes @updates
240 self.render_error status: 422
245 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
246 @new_resource_attrs ||= {}
247 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
248 @object ||= model_class.new @new_resource_attrs, params["options"]
251 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
258 self.render_error status: 422
262 # Clone the given object, merging any attribute values supplied as
263 # with a create action.
265 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
266 @new_resource_attrs ||= {}
267 @object = @object.dup
268 @object.update_attributes @new_resource_attrs
269 if not @new_resource_attrs[:name] and @object.respond_to? :name
270 if @object.name and @object.name != ''
271 @object.name = "Copy of #{@object.name}"
283 f.json { render json: @object }
285 redirect_to(params[:return_to] || :back)
290 self.render_error status: 422
295 Thread.current[:user]
299 controller_name.classify.constantize
302 def breadcrumb_page_name
303 (@breadcrumb_page_name ||
304 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
313 %w(Attributes Advanced)
318 def strip_token_from_path(path)
319 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
322 def redirect_to_login
325 if request.method.in? ['GET', 'HEAD']
326 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
328 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."
333 @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.']
334 self.render_error status: 422
337 false # For convenience to return from callbacks
340 def using_specific_api_token(api_token)
342 [:arvados_api_token, :user].each do |key|
343 start_values[key] = Thread.current[key]
345 load_api_token(api_token)
349 start_values.each_key { |key| Thread.current[key] = start_values[key] }
353 def find_object_by_uuid
354 if params[:id] and params[:id].match /\D/
355 params[:uuid] = params.delete :id
360 elsif not params[:uuid].is_a?(String)
361 @object = model_class.where(uuid: params[:uuid]).first
362 elsif params[:uuid].empty?
364 elsif (model_class != Link and
365 resource_class_for_uuid(params[:uuid]) == Link)
366 @name_link = Link.find(params[:uuid])
367 @object = model_class.find(@name_link.head_uuid)
369 @object = model_class.find(params[:uuid])
371 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
372 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
375 render_not_found(error)
382 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
384 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
387 # Set up the thread with the given API token and associated user object.
388 def load_api_token(new_token)
389 Thread.current[:arvados_api_token] = new_token
391 Thread.current[:user] = nil
392 elsif (new_token == session[:arvados_api_token]) and
393 session[:user].andand[:is_active]
394 Thread.current[:user] = User.new(session[:user])
396 Thread.current[:user] = User.current
400 # If there's a valid api_token parameter, set up the session with that
401 # user's information. Return true if the method redirects the request
402 # (usually a post-login redirect); false otherwise.
403 def setup_user_session
404 return false unless params[:api_token]
405 Thread.current[:arvados_api_token] = params[:api_token]
408 rescue ArvadosApiClient::NotLoggedInException
409 false # We may redirect to login, or not, based on the current action.
411 session[:arvados_api_token] = params[:api_token]
415 first_name: user.first_name,
416 last_name: user.last_name,
417 is_active: user.is_active,
418 is_admin: user.is_admin,
421 session[:skip_profile] = params[:skip_profile]
423 if !request.format.json? and request.method.in? ['GET', 'HEAD']
424 # Repeat this request with api_token in the (new) session
425 # cookie instead of the query string. This prevents API
426 # tokens from appearing in (and being inadvisedly copied
427 # and pasted from) browser Location bars.
428 redirect_to strip_token_from_path(request.fullpath)
434 Thread.current[:arvados_api_token] = nil
438 # Save the session API token in thread-local storage, and yield.
439 # This method also takes care of session setup if the request
440 # provides a valid api_token parameter.
441 # If a token is unavailable or expired, the block is still run, with
443 def set_thread_api_token
444 if Thread.current[:arvados_api_token]
445 yield # An API token has already been found - pass it through.
447 elsif setup_user_session
448 return # A new session was set up and received a response.
452 load_api_token(session[:arvados_api_token])
454 rescue ArvadosApiClient::NotLoggedInException
455 # If we got this error with a token, it must've expired.
456 # Retry the request without a token.
457 unless Thread.current[:arvados_api_token].nil?
462 # Remove token in case this Thread is used for anything else.
467 # Reroute this request if an API token is unavailable.
468 def require_thread_api_token
469 if Thread.current[:arvados_api_token]
471 elsif session[:arvados_api_token]
472 # Expired session. Clear it before refreshing login so that,
473 # if this login procedure fails, we end up showing the "please
474 # log in" page instead of getting stuck in a redirect loop.
475 session.delete :arvados_api_token
478 render 'users/welcome'
482 def ensure_current_user_is_admin
483 unless current_user and current_user.is_admin
484 @errors = ['Permission denied']
485 self.render_error status: 401
489 def check_user_agreements
490 if current_user && !current_user.is_active
491 if not current_user.is_invited
492 return render 'users/inactive'
494 signatures = UserAgreement.signatures
495 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
496 @required_user_agreements = UserAgreement.all.map do |ua|
497 if not @signed_ua_uuids.index ua.uuid
498 Collection.find(ua.uuid)
501 if @required_user_agreements.empty?
502 # No agreements to sign. Perhaps we just need to ask?
503 current_user.activate
504 if !current_user.is_active
505 logger.warn "#{current_user.uuid.inspect}: " +
506 "No user agreements to sign, but activate failed!"
509 if !current_user.is_active
510 render 'user_agreements/index'
516 def check_user_profile
517 @profile_config = Rails.configuration.user_profile_form_fields
519 if params[:skip_profile] || session[:skip_profile]
523 if current_user && @profile_config
524 missing_required_profile = false
526 @this_user = User.limit(1).where(uuid: current_user.uuid).first
527 user_prefs = @this_user.prefs
528 @current_user_profile = user_prefs[:profile] if user_prefs
530 @profile_config.andand.each do |entry|
532 if !@current_user_profile || !@current_user_profile[entry['key'].to_sym]
533 missing_required_profile = true
539 if missing_required_profile
540 render 'users/profile'
547 return Rails.configuration.arvados_theme
550 @@notification_tests = []
552 @@notification_tests.push lambda { |controller, current_user|
553 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
556 return lambda { |view|
557 view.render partial: 'notifications/ssh_key_notification'
561 #@@notification_tests.push lambda { |controller, current_user|
562 # Job.limit(1).where(created_by: current_user.uuid).each do
565 # return lambda { |view|
566 # view.render partial: 'notifications/jobs_notification'
570 @@notification_tests.push lambda { |controller, current_user|
571 Collection.limit(1).where(created_by: current_user.uuid).each do
574 return lambda { |view|
575 view.render partial: 'notifications/collections_notification'
579 @@notification_tests.push lambda { |controller, current_user|
580 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
583 return lambda { |view|
584 view.render partial: 'notifications/pipelines_notification'
588 def check_user_notifications
589 return if params['tab_pane']
591 @notification_count = 0
595 @showallalerts = false
596 @@notification_tests.each do |t|
597 a = t.call(self, current_user)
599 @notification_count += 1
600 @notifications.push a
605 if @notification_count == 0
606 @notification_count = ''
610 helper_method :all_projects
612 @all_projects ||= Group.
613 filter([['group_class','in',['project','folder']]]).order('name')
616 helper_method :my_projects
618 return @my_projects if @my_projects
621 all_projects.each do |g|
622 root_of[g.uuid] = g.owner_uuid
628 root_of = root_of.each_with_object({}) do |(child, parent), h|
630 h[child] = root_of[parent]
637 @my_projects = @my_projects.select do |g|
638 root_of[g.uuid] == current_user.uuid
642 helper_method :projects_shared_with_me
643 def projects_shared_with_me
644 my_project_uuids = my_projects.collect &:uuid
645 all_projects.reject { |x| x.uuid.in? my_project_uuids }
648 helper_method :recent_jobs_and_pipelines
649 def recent_jobs_and_pipelines
651 PipelineInstance.limit(10)).
653 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
657 helper_method :my_project_tree
663 helper_method :shared_project_tree
664 def shared_project_tree
669 def build_project_trees
670 return if @my_project_tree and @shared_project_tree
671 parent_of = {current_user.uuid => 'me'}
672 all_projects.each do |ob|
673 parent_of[ob.uuid] = ob.owner_uuid
675 children_of = {false => [], 'me' => [current_user]}
676 all_projects.each do |ob|
677 if ob.owner_uuid != current_user.uuid and
678 not parent_of.has_key? ob.owner_uuid
679 parent_of[ob.uuid] = false
681 children_of[parent_of[ob.uuid]] ||= []
682 children_of[parent_of[ob.uuid]] << ob
684 buildtree = lambda do |children_of, root_uuid=false|
686 children_of[root_uuid].andand.each do |ob|
687 tree[ob] = buildtree.call(children_of, ob.uuid)
691 sorted_paths = lambda do |tree, depth=0|
693 tree.keys.sort_by { |ob|
694 ob.is_a?(String) ? ob : ob.friendly_link_name
696 paths << {object: ob, depth: depth}
697 paths += sorted_paths.call tree[ob], depth+1
702 sorted_paths.call buildtree.call(children_of, 'me')
703 @shared_project_tree =
704 sorted_paths.call({'Shared with me' =>
705 buildtree.call(children_of, false)})
708 helper_method :get_object
710 if @get_object.nil? and @objects
711 @get_object = @objects.each_with_object({}) do |object, h|
712 h[object.uuid] = object
719 helper_method :project_breadcrumbs
720 def project_breadcrumbs
722 current = @name_link || @object
724 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
725 crumbs.prepend current
727 if current.is_a? Link
728 current = Group.find?(current.tail_uuid)
730 current = Group.find?(current.owner_uuid)
736 helper_method :current_project_uuid
737 def current_project_uuid
738 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
740 elsif @name_link.andand.tail_uuid
742 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
749 # helper method to get links for given object or uuid
750 helper_method :links_for_object
751 def links_for_object object_or_uuid
752 raise ArgumentError, 'No input argument' unless object_or_uuid
753 preload_links_for_objects([object_or_uuid])
754 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
755 @all_links_for[uuid] ||= []
758 # helper method to preload links for given objects and uuids
759 helper_method :preload_links_for_objects
760 def preload_links_for_objects objects_and_uuids
761 @all_links_for ||= {}
763 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
764 return @all_links_for if objects_and_uuids.empty?
766 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
768 # if already preloaded for all of these uuids, return
769 if not uuids.select { |x| @all_links_for[x].nil? }.any?
770 return @all_links_for
774 @all_links_for[x] = []
777 # TODO: make sure we get every page of results from API server
778 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
779 @all_links_for[link.head_uuid] << link
784 # helper method to get a certain number of objects of a specific type
785 # this can be used to replace any uses of: "dataclass.limit(n)"
786 helper_method :get_n_objects_of_class
787 def get_n_objects_of_class dataclass, size
788 @objects_map_for ||= {}
790 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
791 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
793 # if the objects_map_for has a value for this dataclass, and the
794 # size used to retrieve those objects is equal, return it
795 size_key = "#{dataclass.name}_size"
796 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
797 (@objects_map_for[size_key] == size)
798 return @objects_map_for[dataclass.name]
801 @objects_map_for[size_key] = size
802 @objects_map_for[dataclass.name] = dataclass.limit(size)
805 # helper method to get collections for the given uuid
806 helper_method :collections_for_object
807 def collections_for_object uuid
808 raise ArgumentError, 'No input argument' unless uuid
809 preload_collections_for_objects([uuid])
810 @all_collections_for[uuid] ||= []
813 # helper method to preload collections for the given uuids
814 helper_method :preload_collections_for_objects
815 def preload_collections_for_objects uuids
816 @all_collections_for ||= {}
818 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
819 return @all_collections_for if uuids.empty?
821 # if already preloaded for all of these uuids, return
822 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
823 return @all_collections_for
827 @all_collections_for[x] = []
830 # TODO: make sure we get every page of results from API server
831 Collection.where(uuid: uuids).each do |collection|
832 @all_collections_for[collection.uuid] << collection
837 # helper method to get log collections for the given log
838 helper_method :log_collections_for_object
839 def log_collections_for_object log
840 raise ArgumentError, 'No input argument' unless log
842 preload_log_collections_for_objects([log])
845 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
846 if fixup && fixup.size>1
850 @all_log_collections_for[uuid] ||= []
853 # helper method to preload collections for the given uuids
854 helper_method :preload_log_collections_for_objects
855 def preload_log_collections_for_objects logs
856 @all_log_collections_for ||= {}
858 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
859 return @all_log_collections_for if logs.empty?
863 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
864 if fixup && fixup.size>1
871 # if already preloaded for all of these uuids, return
872 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
873 return @all_log_collections_for
877 @all_log_collections_for[x] = []
880 # TODO: make sure we get every page of results from API server
881 Collection.where(uuid: uuids).each do |collection|
882 @all_log_collections_for[collection.uuid] << collection
884 @all_log_collections_for
887 # helper method to get object of a given dataclass and uuid
888 helper_method :object_for_dataclass
889 def object_for_dataclass dataclass, uuid
890 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
891 preload_objects_for_dataclass(dataclass, [uuid])
895 # helper method to preload objects for given dataclass and uuids
896 helper_method :preload_objects_for_dataclass
897 def preload_objects_for_dataclass dataclass, uuids
900 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
901 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
903 return @objects_for if uuids.empty?
905 # if already preloaded for all of these uuids, return
906 if not uuids.select { |x| @objects_for[x].nil? }.any?
910 dataclass.where(uuid: uuids).each do |obj|
911 @objects_for[obj.uuid] = obj