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 = User.limit(1).where(uuid: current_user.uuid).first.prefs
533 user_prefs = current_user.prefs if !user_prefs[:profile]
534 current_user_profile = user_prefs[:profile] if user_prefs
536 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
538 if !current_user_profile || !current_user_profile[entry['key'].to_sym]
539 missing_required_profile = true
545 if missing_required_profile
546 render 'users/profile'
553 return Rails.configuration.arvados_theme
556 @@notification_tests = []
558 @@notification_tests.push lambda { |controller, current_user|
559 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
562 return lambda { |view|
563 view.render partial: 'notifications/ssh_key_notification'
567 #@@notification_tests.push lambda { |controller, current_user|
568 # Job.limit(1).where(created_by: current_user.uuid).each do
571 # return lambda { |view|
572 # view.render partial: 'notifications/jobs_notification'
576 @@notification_tests.push lambda { |controller, current_user|
577 Collection.limit(1).where(created_by: current_user.uuid).each do
580 return lambda { |view|
581 view.render partial: 'notifications/collections_notification'
585 @@notification_tests.push lambda { |controller, current_user|
586 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
589 return lambda { |view|
590 view.render partial: 'notifications/pipelines_notification'
594 def check_user_notifications
595 return if params['tab_pane']
597 @notification_count = 0
601 @showallalerts = false
602 @@notification_tests.each do |t|
603 a = t.call(self, current_user)
605 @notification_count += 1
606 @notifications.push a
611 if @notification_count == 0
612 @notification_count = ''
616 helper_method :all_projects
618 @all_projects ||= Group.
619 filter([['group_class','=','project']]).order('name')
622 helper_method :my_projects
624 return @my_projects if @my_projects
627 all_projects.each do |g|
628 root_of[g.uuid] = g.owner_uuid
634 root_of = root_of.each_with_object({}) do |(child, parent), h|
636 h[child] = root_of[parent]
643 @my_projects = @my_projects.select do |g|
644 root_of[g.uuid] == current_user.uuid
648 helper_method :projects_shared_with_me
649 def projects_shared_with_me
650 my_project_uuids = my_projects.collect &:uuid
651 all_projects.reject { |x| x.uuid.in? my_project_uuids }
654 helper_method :recent_jobs_and_pipelines
655 def recent_jobs_and_pipelines
657 PipelineInstance.limit(10)).
659 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
663 helper_method :my_project_tree
669 helper_method :shared_project_tree
670 def shared_project_tree
675 def build_project_trees
676 return if @my_project_tree and @shared_project_tree
677 parent_of = {current_user.uuid => 'me'}
678 all_projects.each do |ob|
679 parent_of[ob.uuid] = ob.owner_uuid
681 children_of = {false => [], 'me' => [current_user]}
682 all_projects.each do |ob|
683 if ob.owner_uuid != current_user.uuid and
684 not parent_of.has_key? ob.owner_uuid
685 parent_of[ob.uuid] = false
687 children_of[parent_of[ob.uuid]] ||= []
688 children_of[parent_of[ob.uuid]] << ob
690 buildtree = lambda do |children_of, root_uuid=false|
692 children_of[root_uuid].andand.each do |ob|
693 tree[ob] = buildtree.call(children_of, ob.uuid)
697 sorted_paths = lambda do |tree, depth=0|
699 tree.keys.sort_by { |ob|
700 ob.is_a?(String) ? ob : ob.friendly_link_name
702 paths << {object: ob, depth: depth}
703 paths += sorted_paths.call tree[ob], depth+1
708 sorted_paths.call buildtree.call(children_of, 'me')
709 @shared_project_tree =
710 sorted_paths.call({'Shared with me' =>
711 buildtree.call(children_of, false)})
714 helper_method :get_object
716 if @get_object.nil? and @objects
717 @get_object = @objects.each_with_object({}) do |object, h|
718 h[object.uuid] = object
725 helper_method :project_breadcrumbs
726 def project_breadcrumbs
728 current = @name_link || @object
730 if current.is_a?(Group) and current.group_class == 'project'
731 crumbs.prepend current
733 if current.is_a? Link
734 current = Group.find?(current.tail_uuid)
736 current = Group.find?(current.owner_uuid)
742 helper_method :current_project_uuid
743 def current_project_uuid
744 if @object.is_a? Group and @object.group_class == 'project'
746 elsif @name_link.andand.tail_uuid
748 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
755 # helper method to get links for given object or uuid
756 helper_method :links_for_object
757 def links_for_object object_or_uuid
758 raise ArgumentError, 'No input argument' unless object_or_uuid
759 preload_links_for_objects([object_or_uuid])
760 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
761 @all_links_for[uuid] ||= []
764 # helper method to preload links for given objects and uuids
765 helper_method :preload_links_for_objects
766 def preload_links_for_objects objects_and_uuids
767 @all_links_for ||= {}
769 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
770 return @all_links_for if objects_and_uuids.empty?
772 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
774 # if already preloaded for all of these uuids, return
775 if not uuids.select { |x| @all_links_for[x].nil? }.any?
776 return @all_links_for
780 @all_links_for[x] = []
783 # TODO: make sure we get every page of results from API server
784 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
785 @all_links_for[link.head_uuid] << link
790 # helper method to get a certain number of objects of a specific type
791 # this can be used to replace any uses of: "dataclass.limit(n)"
792 helper_method :get_n_objects_of_class
793 def get_n_objects_of_class dataclass, size
794 @objects_map_for ||= {}
796 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
797 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
799 # if the objects_map_for has a value for this dataclass, and the
800 # size used to retrieve those objects is equal, return it
801 size_key = "#{dataclass.name}_size"
802 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
803 (@objects_map_for[size_key] == size)
804 return @objects_map_for[dataclass.name]
807 @objects_map_for[size_key] = size
808 @objects_map_for[dataclass.name] = dataclass.limit(size)
811 # helper method to get collections for the given uuid
812 helper_method :collections_for_object
813 def collections_for_object uuid
814 raise ArgumentError, 'No input argument' unless uuid
815 preload_collections_for_objects([uuid])
816 @all_collections_for[uuid] ||= []
819 # helper method to preload collections for the given uuids
820 helper_method :preload_collections_for_objects
821 def preload_collections_for_objects uuids
822 @all_collections_for ||= {}
824 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
825 return @all_collections_for if uuids.empty?
827 # if already preloaded for all of these uuids, return
828 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
829 return @all_collections_for
833 @all_collections_for[x] = []
836 # TODO: make sure we get every page of results from API server
837 Collection.where(uuid: uuids).each do |collection|
838 @all_collections_for[collection.uuid] << collection
843 # helper method to get log collections for the given log
844 helper_method :log_collections_for_object
845 def log_collections_for_object log
846 raise ArgumentError, 'No input argument' unless log
848 preload_log_collections_for_objects([log])
851 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
852 if fixup && fixup.size>1
856 @all_log_collections_for[uuid] ||= []
859 # helper method to preload collections for the given uuids
860 helper_method :preload_log_collections_for_objects
861 def preload_log_collections_for_objects logs
862 @all_log_collections_for ||= {}
864 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
865 return @all_log_collections_for if logs.empty?
869 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
870 if fixup && fixup.size>1
877 # if already preloaded for all of these uuids, return
878 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
879 return @all_log_collections_for
883 @all_log_collections_for[x] = []
886 # TODO: make sure we get every page of results from API server
887 Collection.where(uuid: uuids).each do |collection|
888 @all_log_collections_for[collection.uuid] << collection
890 @all_log_collections_for
893 # helper method to get object of a given dataclass and uuid
894 helper_method :object_for_dataclass
895 def object_for_dataclass dataclass, uuid
896 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
897 preload_objects_for_dataclass(dataclass, [uuid])
901 # helper method to preload objects for given dataclass and uuids
902 helper_method :preload_objects_for_dataclass
903 def preload_objects_for_dataclass dataclass, uuids
906 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
907 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
909 return @objects_for if uuids.empty?
911 # if already preloaded for all of these uuids, return
912 if not uuids.select { |x| @objects_for[x].nil? }.any?
916 dataclass.where(uuid: uuids).each do |obj|
917 @objects_for[obj.uuid] = obj