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
93 @order = params[:order] || 'created_at desc'
94 @order = [@order] unless @order.is_a? Array
98 @limit = params[:limit].to_i
103 @offset = params[:offset].to_i
108 filters = params[:filters]
109 if filters.is_a? String
110 filters = Oj.load filters
111 elsif filters.is_a? Array
112 filters = filters.collect do |filter|
113 if filter.is_a? String
114 # Accept filters[]=["foo","=","bar"]
117 # Accept filters=[["foo","=","bar"]]
126 def find_objects_for_index
127 @objects ||= model_class
128 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
133 f.json { render json: @objects }
136 render_pane params[:tab_pane]
145 helper_method :render_pane
146 def render_pane tab_pane, opts={}
148 partial: 'show_' + tab_pane.downcase,
150 comparable: self.respond_to?(:compare),
153 }.merge(opts[:locals] || {})
156 render_to_string render_opts
163 find_objects_for_index if !@objects
167 helper_method :next_page_offset
168 def next_page_offset objects=nil
172 if objects.respond_to?(:result_offset) and
173 objects.respond_to?(:result_limit) and
174 objects.respond_to?(:items_available)
175 next_offset = objects.result_offset + objects.result_limit
176 if next_offset < objects.items_available
184 helper_method :next_page_href
185 def next_page_href with_params={}
187 url_for with_params.merge(offset: next_page_offset)
193 return render_not_found("object not found")
196 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
198 if params['tab_pane']
199 render_pane params['tab_pane']
200 elsif request.method.in? ['GET', 'HEAD']
203 redirect_to params[:return_to] || @object
211 params[:limit] ||= 40
212 find_objects_for_index if !@objects
217 content: render_to_string(partial: "choose_rows.html",
219 next_page_href: next_page_href(partial: params[:partial])
224 render partial: 'choose', locals: {multiple: params[:multiple]}
231 return render_not_found("object not found")
236 @object = model_class.new
240 @updates ||= params[@object.resource_param_name.to_sym]
241 @updates.keys.each do |attr|
242 if @object.send(attr).is_a? Hash
243 if @updates[attr].is_a? String
244 @updates[attr] = Oj.load @updates[attr]
246 if params[:merge] || params["merge_#{attr}".to_sym]
247 # Merge provided Hash with current Hash, instead of
249 @updates[attr] = @object.send(attr).with_indifferent_access.
250 deep_merge(@updates[attr].with_indifferent_access)
254 if @object.update_attributes @updates
257 self.render_error status: 422
262 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
263 @new_resource_attrs ||= {}
264 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
265 @object ||= model_class.new @new_resource_attrs, params["options"]
268 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
275 self.render_error status: 422
279 # Clone the given object, merging any attribute values supplied as
280 # with a create action.
282 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
283 @new_resource_attrs ||= {}
284 @object = @object.dup
285 @object.update_attributes @new_resource_attrs
286 if not @new_resource_attrs[:name] and @object.respond_to? :name
287 if @object.name and @object.name != ''
288 @object.name = "Copy of #{@object.name}"
300 f.json { render json: @object }
302 redirect_to(params[:return_to] || :back)
307 self.render_error status: 422
312 Thread.current[:user]
316 controller_name.classify.constantize
319 def breadcrumb_page_name
320 (@breadcrumb_page_name ||
321 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
330 %w(Attributes Advanced)
335 def strip_token_from_path(path)
336 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
339 def redirect_to_login
342 if request.method.in? ['GET', 'HEAD']
343 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
345 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."
350 @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.']
351 self.render_error status: 422
354 false # For convenience to return from callbacks
357 def using_specific_api_token(api_token)
359 [:arvados_api_token, :user].each do |key|
360 start_values[key] = Thread.current[key]
362 load_api_token(api_token)
366 start_values.each_key { |key| Thread.current[key] = start_values[key] }
371 def accept_uuid_as_id_param
372 if params[:id] and params[:id].match /\D/
373 params[:uuid] = params.delete :id
377 def find_object_by_uuid
381 elsif not params[:uuid].is_a?(String)
382 @object = model_class.where(uuid: params[:uuid]).first
383 elsif params[:uuid].empty?
385 elsif (model_class != Link and
386 resource_class_for_uuid(params[:uuid]) == Link)
387 @name_link = Link.find(params[:uuid])
388 @object = model_class.find(@name_link.head_uuid)
390 @object = model_class.find(params[:uuid])
392 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
393 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
396 render_not_found(error)
403 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
405 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
408 # Set up the thread with the given API token and associated user object.
409 def load_api_token(new_token)
410 Thread.current[:arvados_api_token] = new_token
412 Thread.current[:user] = nil
414 Thread.current[:user] = User.current
418 # If there's a valid api_token parameter, set up the session with that
419 # user's information. Return true if the method redirects the request
420 # (usually a post-login redirect); false otherwise.
421 def setup_user_session
422 return false unless params[:api_token]
423 Thread.current[:arvados_api_token] = params[:api_token]
426 rescue ArvadosApiClient::NotLoggedInException
427 false # We may redirect to login, or not, based on the current action.
429 session[:arvados_api_token] = params[:api_token]
431 if !request.format.json? and request.method.in? ['GET', 'HEAD']
432 # Repeat this request with api_token in the (new) session
433 # cookie instead of the query string. This prevents API
434 # tokens from appearing in (and being inadvisedly copied
435 # and pasted from) browser Location bars.
436 redirect_to strip_token_from_path(request.fullpath)
442 Thread.current[:arvados_api_token] = nil
446 # Save the session API token in thread-local storage, and yield.
447 # This method also takes care of session setup if the request
448 # provides a valid api_token parameter.
449 # If a token is unavailable or expired, the block is still run, with
451 def set_thread_api_token
452 if Thread.current[:arvados_api_token]
453 yield # An API token has already been found - pass it through.
455 elsif setup_user_session
456 return # A new session was set up and received a response.
460 load_api_token(session[:arvados_api_token])
462 rescue ArvadosApiClient::NotLoggedInException
463 # If we got this error with a token, it must've expired.
464 # Retry the request without a token.
465 unless Thread.current[:arvados_api_token].nil?
470 # Remove token in case this Thread is used for anything else.
475 # Reroute this request if an API token is unavailable.
476 def require_thread_api_token
477 if Thread.current[:arvados_api_token]
479 elsif session[:arvados_api_token]
480 # Expired session. Clear it before refreshing login so that,
481 # if this login procedure fails, we end up showing the "please
482 # log in" page instead of getting stuck in a redirect loop.
483 session.delete :arvados_api_token
486 render 'users/welcome'
490 def ensure_current_user_is_admin
491 unless current_user and current_user.is_admin
492 @errors = ['Permission denied']
493 self.render_error status: 401
497 def check_user_agreements
498 if current_user && !current_user.is_active
499 if not current_user.is_invited
500 return render 'users/inactive'
502 signatures = UserAgreement.signatures
503 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
504 @required_user_agreements = UserAgreement.all.map do |ua|
505 if not @signed_ua_uuids.index ua.uuid
506 Collection.find(ua.uuid)
509 if @required_user_agreements.empty?
510 # No agreements to sign. Perhaps we just need to ask?
511 current_user.activate
512 if !current_user.is_active
513 logger.warn "#{current_user.uuid.inspect}: " +
514 "No user agreements to sign, but activate failed!"
517 if !current_user.is_active
518 render 'user_agreements/index'
524 def check_user_profile
525 if request.method.downcase != 'get' || params[:partial] ||
526 params[:tab_pane] || params[:action_method] ||
527 params[:action] == 'setup_popup'
531 if missing_required_profile?
532 render 'users/profile'
537 helper_method :missing_required_profile?
538 def missing_required_profile?
539 missing_required = false
541 profile_config = Rails.configuration.user_profile_form_fields
542 if current_user && profile_config
543 current_user_profile = current_user.prefs[:profile]
544 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
546 if !current_user_profile ||
547 !current_user_profile[entry['key'].to_sym] ||
548 current_user_profile[entry['key'].to_sym].empty?
549 missing_required = true
560 return Rails.configuration.arvados_theme
563 @@notification_tests = []
565 @@notification_tests.push lambda { |controller, current_user|
566 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
569 return lambda { |view|
570 view.render partial: 'notifications/ssh_key_notification'
574 #@@notification_tests.push lambda { |controller, current_user|
575 # Job.limit(1).where(created_by: current_user.uuid).each do
578 # return lambda { |view|
579 # view.render partial: 'notifications/jobs_notification'
583 @@notification_tests.push lambda { |controller, current_user|
584 Collection.limit(1).where(created_by: current_user.uuid).each do
587 return lambda { |view|
588 view.render partial: 'notifications/collections_notification'
592 @@notification_tests.push lambda { |controller, current_user|
593 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
596 return lambda { |view|
597 view.render partial: 'notifications/pipelines_notification'
601 def check_user_notifications
602 return if params['tab_pane']
604 @notification_count = 0
608 @showallalerts = false
609 @@notification_tests.each do |t|
610 a = t.call(self, current_user)
612 @notification_count += 1
613 @notifications.push a
618 if @notification_count == 0
619 @notification_count = ''
623 helper_method :all_projects
625 @all_projects ||= Group.
626 filter([['group_class','=','project']]).order('name')
629 helper_method :my_projects
631 return @my_projects if @my_projects
634 all_projects.each do |g|
635 root_of[g.uuid] = g.owner_uuid
641 root_of = root_of.each_with_object({}) do |(child, parent), h|
643 h[child] = root_of[parent]
650 @my_projects = @my_projects.select do |g|
651 root_of[g.uuid] == current_user.uuid
655 helper_method :projects_shared_with_me
656 def projects_shared_with_me
657 my_project_uuids = my_projects.collect &:uuid
658 all_projects.reject { |x| x.uuid.in? my_project_uuids }
661 helper_method :recent_jobs_and_pipelines
662 def recent_jobs_and_pipelines
664 PipelineInstance.limit(10)).
666 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
670 helper_method :my_project_tree
676 helper_method :shared_project_tree
677 def shared_project_tree
682 def build_project_trees
683 return if @my_project_tree and @shared_project_tree
684 parent_of = {current_user.uuid => 'me'}
685 all_projects.each do |ob|
686 parent_of[ob.uuid] = ob.owner_uuid
688 children_of = {false => [], 'me' => [current_user]}
689 all_projects.each do |ob|
690 if ob.owner_uuid != current_user.uuid and
691 not parent_of.has_key? ob.owner_uuid
692 parent_of[ob.uuid] = false
694 children_of[parent_of[ob.uuid]] ||= []
695 children_of[parent_of[ob.uuid]] << ob
697 buildtree = lambda do |children_of, root_uuid=false|
699 children_of[root_uuid].andand.each do |ob|
700 tree[ob] = buildtree.call(children_of, ob.uuid)
704 sorted_paths = lambda do |tree, depth=0|
706 tree.keys.sort_by { |ob|
707 ob.is_a?(String) ? ob : ob.friendly_link_name
709 paths << {object: ob, depth: depth}
710 paths += sorted_paths.call tree[ob], depth+1
715 sorted_paths.call buildtree.call(children_of, 'me')
716 @shared_project_tree =
717 sorted_paths.call({'Shared with me' =>
718 buildtree.call(children_of, false)})
721 helper_method :get_object
723 if @get_object.nil? and @objects
724 @get_object = @objects.each_with_object({}) do |object, h|
725 h[object.uuid] = object
732 helper_method :project_breadcrumbs
733 def project_breadcrumbs
735 current = @name_link || @object
737 if current.is_a?(Group) and current.group_class == 'project'
738 crumbs.prepend current
740 if current.is_a? Link
741 current = Group.find?(current.tail_uuid)
743 current = Group.find?(current.owner_uuid)
749 helper_method :current_project_uuid
750 def current_project_uuid
751 if @object.is_a? Group and @object.group_class == 'project'
753 elsif @name_link.andand.tail_uuid
755 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
762 # helper method to get links for given object or uuid
763 helper_method :links_for_object
764 def links_for_object object_or_uuid
765 raise ArgumentError, 'No input argument' unless object_or_uuid
766 preload_links_for_objects([object_or_uuid])
767 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
768 @all_links_for[uuid] ||= []
771 # helper method to preload links for given objects and uuids
772 helper_method :preload_links_for_objects
773 def preload_links_for_objects objects_and_uuids
774 @all_links_for ||= {}
776 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
777 return @all_links_for if objects_and_uuids.empty?
779 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
781 # if already preloaded for all of these uuids, return
782 if not uuids.select { |x| @all_links_for[x].nil? }.any?
783 return @all_links_for
787 @all_links_for[x] = []
790 # TODO: make sure we get every page of results from API server
791 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
792 @all_links_for[link.head_uuid] << link
797 # helper method to get a certain number of objects of a specific type
798 # this can be used to replace any uses of: "dataclass.limit(n)"
799 helper_method :get_n_objects_of_class
800 def get_n_objects_of_class dataclass, size
801 @objects_map_for ||= {}
803 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
804 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
806 # if the objects_map_for has a value for this dataclass, and the
807 # size used to retrieve those objects is equal, return it
808 size_key = "#{dataclass.name}_size"
809 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
810 (@objects_map_for[size_key] == size)
811 return @objects_map_for[dataclass.name]
814 @objects_map_for[size_key] = size
815 @objects_map_for[dataclass.name] = dataclass.limit(size)
818 # helper method to get collections for the given uuid
819 helper_method :collections_for_object
820 def collections_for_object uuid
821 raise ArgumentError, 'No input argument' unless uuid
822 preload_collections_for_objects([uuid])
823 @all_collections_for[uuid] ||= []
826 # helper method to preload collections for the given uuids
827 helper_method :preload_collections_for_objects
828 def preload_collections_for_objects uuids
829 @all_collections_for ||= {}
831 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
832 return @all_collections_for if uuids.empty?
834 # if already preloaded for all of these uuids, return
835 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
836 return @all_collections_for
840 @all_collections_for[x] = []
843 # TODO: make sure we get every page of results from API server
844 Collection.where(uuid: uuids).each do |collection|
845 @all_collections_for[collection.uuid] << collection
850 # helper method to get log collections for the given log
851 helper_method :log_collections_for_object
852 def log_collections_for_object log
853 raise ArgumentError, 'No input argument' unless log
855 preload_log_collections_for_objects([log])
858 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
859 if fixup && fixup.size>1
863 @all_log_collections_for[uuid] ||= []
866 # helper method to preload collections for the given uuids
867 helper_method :preload_log_collections_for_objects
868 def preload_log_collections_for_objects logs
869 @all_log_collections_for ||= {}
871 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
872 return @all_log_collections_for if logs.empty?
876 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
877 if fixup && fixup.size>1
884 # if already preloaded for all of these uuids, return
885 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
886 return @all_log_collections_for
890 @all_log_collections_for[x] = []
893 # TODO: make sure we get every page of results from API server
894 Collection.where(uuid: uuids).each do |collection|
895 @all_log_collections_for[collection.uuid] << collection
897 @all_log_collections_for
900 # helper method to get object of a given dataclass and uuid
901 helper_method :object_for_dataclass
902 def object_for_dataclass dataclass, uuid
903 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
904 preload_objects_for_dataclass(dataclass, [uuid])
908 # helper method to preload objects for given dataclass and uuids
909 helper_method :preload_objects_for_dataclass
910 def preload_objects_for_dataclass dataclass, uuids
913 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
914 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
916 return @objects_for if uuids.empty?
918 # if already preloaded for all of these uuids, return
919 if not uuids.select { |x| @objects_for[x].nil? }.any?
923 dataclass.where(uuid: uuids).each do |obj|
924 @objects_for[obj.uuid] = obj