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_notifications, except: ERROR_ACTIONS
17 before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
21 rescue_from(ActiveRecord::RecordNotFound,
22 ActionController::RoutingError,
23 ActionController::UnknownController,
24 AbstractController::ActionNotFound,
25 with: :render_not_found)
26 rescue_from(Exception,
27 ActionController::UrlGenerationError,
28 with: :render_exception)
31 def unprocessable(message=nil)
34 @errors << message if message
35 render_error status: 422
38 def render_error(opts={})
41 # json must come before html here, so it gets used as the
42 # default format when js is requested by the client. This lets
43 # ajax:error callback parse the response correctly, even though
45 f.json { render opts.merge(json: {success: false, errors: @errors}) }
46 f.html { render({action: 'error'}.merge(opts)) }
50 def render_exception(e)
51 logger.error e.inspect
52 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
53 err_opts = {status: 422}
54 if e.is_a?(ArvadosApiClient::ApiError)
55 err_opts.merge!(action: 'api_error', locals: {api_error: e})
56 @errors = e.api_response[:errors]
57 elsif @object.andand.errors.andand.full_messages.andand.any?
58 @errors = @object.errors.full_messages
62 # If the user has an active session, and the API server is available,
63 # make user information available on the error page.
65 load_api_token(session[:arvados_api_token])
66 rescue ArvadosApiClient::ApiError
69 # Preload projects trees for the template. If that fails, set empty
70 # trees so error page rendering can proceed. (It's easier to rescue the
71 # exception here than in a template.)
74 rescue ArvadosApiClient::ApiError
75 @my_project_tree ||= []
76 @shared_project_tree ||= []
78 render_error(err_opts)
81 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
82 logger.error e.inspect
83 @errors = ["Path not found"]
84 set_thread_api_token do
85 self.render_error(action: '404', status: 404)
89 def find_objects_for_index
92 @limit = params[:limit].to_i
97 @offset = params[:offset].to_i
102 filters = params[:filters]
103 if filters.is_a? String
104 filters = Oj.load filters
109 @objects ||= model_class
110 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
115 f.json { render json: @objects }
117 if params['tab_pane']
118 comparable = self.respond_to? :compare
119 render(partial: 'show_' + params['tab_pane'].downcase,
120 locals: { comparable: comparable, objects: @objects })
130 find_objects_for_index if !@objects
134 helper_method :next_page_offset
136 if @objects.respond_to?(:result_offset) and
137 @objects.respond_to?(:result_limit) and
138 @objects.respond_to?(:items_available)
139 next_offset = @objects.result_offset + @objects.result_limit
140 if next_offset < @objects.items_available
150 return render_not_found("object not found")
153 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
155 if params['tab_pane']
156 comparable = self.respond_to? :compare
157 render(partial: 'show_' + params['tab_pane'].downcase,
158 locals: { comparable: comparable, objects: @objects })
159 elsif request.method.in? ['GET', 'HEAD']
162 redirect_to params[:return_to] || @object
170 params[:limit] ||= 40
172 if params[:project_uuid] and !params[:project_uuid].empty?
173 # We want the chooser to show objects of the controllers's model_class
174 # type within a specific project specified by project_uuid, so fetch the
175 # project and request the contents of the project filtered on the
176 # controllers's model_class kind.
177 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
179 find_objects_for_index if !@objects
185 content: render_to_string(partial: "choose_rows.html",
188 multiple: params[:multiple]
190 next_page_href: @next_page_href
195 render partial: 'choose', locals: {multiple: params[:multiple]}
202 return render_not_found("object not found")
207 @object = model_class.new
211 @updates ||= params[@object.resource_param_name.to_sym]
212 @updates.keys.each do |attr|
213 if @object.send(attr).is_a? Hash
214 if @updates[attr].is_a? String
215 @updates[attr] = Oj.load @updates[attr]
217 if params[:merge] || params["merge_#{attr}".to_sym]
218 # Merge provided Hash with current Hash, instead of
220 @updates[attr] = @object.send(attr).with_indifferent_access.
221 deep_merge(@updates[attr].with_indifferent_access)
225 if @object.update_attributes @updates
228 self.render_error status: 422
233 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
234 @new_resource_attrs ||= {}
235 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
236 @object ||= model_class.new @new_resource_attrs, params["options"]
239 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
246 self.render_error status: 422
250 # Clone the given object, merging any attribute values supplied as
251 # with a create action.
253 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
254 @new_resource_attrs ||= {}
255 @object = @object.dup
256 @object.update_attributes @new_resource_attrs
257 if not @new_resource_attrs[:name] and @object.respond_to? :name
258 if @object.name and @object.name != ''
259 @object.name = "Copy of #{@object.name}"
261 if @object.class.name == 'PipelineInstance'
264 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
275 f.json { render json: @object }
277 redirect_to(params[:return_to] || :back)
282 self.render_error status: 422
287 Thread.current[:user]
291 controller_name.classify.constantize
294 def breadcrumb_page_name
295 (@breadcrumb_page_name ||
296 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
305 %w(Attributes Advanced)
310 def strip_token_from_path(path)
311 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
314 def redirect_to_login
317 if request.method.in? ['GET', 'HEAD']
318 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
320 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."
325 @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.']
326 self.render_error status: 422
329 false # For convenience to return from callbacks
332 def using_specific_api_token(api_token)
334 [:arvados_api_token, :user].each do |key|
335 start_values[key] = Thread.current[key]
337 load_api_token(api_token)
341 start_values.each_key { |key| Thread.current[key] = start_values[key] }
345 def find_object_by_uuid
346 if params[:id] and params[:id].match /\D/
347 params[:uuid] = params.delete :id
352 elsif not params[:uuid].is_a?(String)
353 @object = model_class.where(uuid: params[:uuid]).first
354 elsif params[:uuid].empty?
356 elsif (model_class != Link and
357 resource_class_for_uuid(params[:uuid]) == Link)
358 @name_link = Link.find(params[:uuid])
359 @object = model_class.find(@name_link.head_uuid)
361 @object = model_class.find(params[:uuid])
363 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
364 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
367 render_not_found(error)
374 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
376 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
379 # Set up the thread with the given API token and associated user object.
380 def load_api_token(new_token)
381 Thread.current[:arvados_api_token] = new_token
383 Thread.current[:user] = nil
384 elsif (new_token == session[:arvados_api_token]) and
385 session[:user].andand[:is_active]
386 Thread.current[:user] = User.new(session[:user])
388 Thread.current[:user] = User.current
392 # If there's a valid api_token parameter, set up the session with that
393 # user's information. Return true if the method redirects the request
394 # (usually a post-login redirect); false otherwise.
395 def setup_user_session
396 return false unless params[:api_token]
397 Thread.current[:arvados_api_token] = params[:api_token]
400 rescue ArvadosApiClient::NotLoggedInException
401 false # We may redirect to login, or not, based on the current action.
403 session[:arvados_api_token] = params[:api_token]
407 first_name: user.first_name,
408 last_name: user.last_name,
409 is_active: user.is_active,
410 is_admin: user.is_admin,
413 if !request.format.json? and request.method.in? ['GET', 'HEAD']
414 # Repeat this request with api_token in the (new) session
415 # cookie instead of the query string. This prevents API
416 # tokens from appearing in (and being inadvisedly copied
417 # and pasted from) browser Location bars.
418 redirect_to strip_token_from_path(request.fullpath)
424 Thread.current[:arvados_api_token] = nil
428 # Save the session API token in thread-local storage, and yield.
429 # This method also takes care of session setup if the request
430 # provides a valid api_token parameter.
431 # If a token is unavailable or expired, the block is still run, with
433 def set_thread_api_token
434 if Thread.current[:arvados_api_token]
435 yield # An API token has already been found - pass it through.
437 elsif setup_user_session
438 return # A new session was set up and received a response.
442 load_api_token(session[:arvados_api_token])
444 rescue ArvadosApiClient::NotLoggedInException
445 # If we got this error with a token, it must've expired.
446 # Retry the request without a token.
447 unless Thread.current[:arvados_api_token].nil?
452 # Remove token in case this Thread is used for anything else.
457 # Reroute this request if an API token is unavailable.
458 def require_thread_api_token
459 if Thread.current[:arvados_api_token]
461 elsif session[:arvados_api_token]
462 # Expired session. Clear it before refreshing login so that,
463 # if this login procedure fails, we end up showing the "please
464 # log in" page instead of getting stuck in a redirect loop.
465 session.delete :arvados_api_token
468 render 'users/welcome'
472 def ensure_current_user_is_admin
473 unless current_user and current_user.is_admin
474 @errors = ['Permission denied']
475 self.render_error status: 401
479 def check_user_agreements
480 if current_user && !current_user.is_active
481 if not current_user.is_invited
482 return render 'users/inactive'
484 signatures = UserAgreement.signatures
485 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
486 @required_user_agreements = UserAgreement.all.map do |ua|
487 if not @signed_ua_uuids.index ua.uuid
488 Collection.find(ua.uuid)
491 if @required_user_agreements.empty?
492 # No agreements to sign. Perhaps we just need to ask?
493 current_user.activate
494 if !current_user.is_active
495 logger.warn "#{current_user.uuid.inspect}: " +
496 "No user agreements to sign, but activate failed!"
499 if !current_user.is_active
500 render 'user_agreements/index'
507 return Rails.configuration.arvados_theme
510 @@notification_tests = []
512 @@notification_tests.push lambda { |controller, current_user|
513 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
516 return lambda { |view|
517 view.render partial: 'notifications/ssh_key_notification'
521 #@@notification_tests.push lambda { |controller, current_user|
522 # Job.limit(1).where(created_by: current_user.uuid).each do
525 # return lambda { |view|
526 # view.render partial: 'notifications/jobs_notification'
530 @@notification_tests.push lambda { |controller, current_user|
531 Collection.limit(1).where(created_by: current_user.uuid).each do
534 return lambda { |view|
535 view.render partial: 'notifications/collections_notification'
539 @@notification_tests.push lambda { |controller, current_user|
540 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
543 return lambda { |view|
544 view.render partial: 'notifications/pipelines_notification'
548 def check_user_notifications
549 return if params['tab_pane']
551 @notification_count = 0
555 @showallalerts = false
556 @@notification_tests.each do |t|
557 a = t.call(self, current_user)
559 @notification_count += 1
560 @notifications.push a
565 if @notification_count == 0
566 @notification_count = ''
570 helper_method :all_projects
572 @all_projects ||= Group.
573 filter([['group_class','in',['project','folder']]]).order('name')
576 helper_method :my_projects
578 return @my_projects if @my_projects
581 all_projects.each do |g|
582 root_of[g.uuid] = g.owner_uuid
588 root_of = root_of.each_with_object({}) do |(child, parent), h|
590 h[child] = root_of[parent]
597 @my_projects = @my_projects.select do |g|
598 root_of[g.uuid] == current_user.uuid
602 helper_method :projects_shared_with_me
603 def projects_shared_with_me
604 my_project_uuids = my_projects.collect &:uuid
605 all_projects.reject { |x| x.uuid.in? my_project_uuids }
608 helper_method :recent_jobs_and_pipelines
609 def recent_jobs_and_pipelines
611 PipelineInstance.limit(10)).
613 x.finished_at || x.started_at || x.created_at rescue x.created_at
617 helper_method :my_project_tree
623 helper_method :shared_project_tree
624 def shared_project_tree
629 def build_project_trees
630 return if @my_project_tree and @shared_project_tree
631 parent_of = {current_user.uuid => 'me'}
632 all_projects.each do |ob|
633 parent_of[ob.uuid] = ob.owner_uuid
635 children_of = {false => [], 'me' => [current_user]}
636 all_projects.each do |ob|
637 if ob.owner_uuid != current_user.uuid and
638 not parent_of.has_key? ob.owner_uuid
639 parent_of[ob.uuid] = false
641 children_of[parent_of[ob.uuid]] ||= []
642 children_of[parent_of[ob.uuid]] << ob
644 buildtree = lambda do |children_of, root_uuid=false|
646 children_of[root_uuid].andand.each do |ob|
647 tree[ob] = buildtree.call(children_of, ob.uuid)
651 sorted_paths = lambda do |tree, depth=0|
653 tree.keys.sort_by { |ob|
654 ob.is_a?(String) ? ob : ob.friendly_link_name
656 paths << {object: ob, depth: depth}
657 paths += sorted_paths.call tree[ob], depth+1
662 sorted_paths.call buildtree.call(children_of, 'me')
663 @shared_project_tree =
664 sorted_paths.call({'Shared with me' =>
665 buildtree.call(children_of, false)})
668 helper_method :get_object
670 if @get_object.nil? and @objects
671 @get_object = @objects.each_with_object({}) do |object, h|
672 h[object.uuid] = object
679 helper_method :project_breadcrumbs
680 def project_breadcrumbs
682 current = @name_link || @object
684 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
685 crumbs.prepend current
687 if current.is_a? Link
688 current = Group.find?(current.tail_uuid)
690 current = Group.find?(current.owner_uuid)
696 helper_method :current_project_uuid
697 def current_project_uuid
698 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
700 elsif @name_link.andand.tail_uuid
702 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
709 # helper method to get links for given object or uuid
710 helper_method :links_for_object
711 def links_for_object object_or_uuid
712 raise ArgumentError, 'No input argument' unless object_or_uuid
713 preload_links_for_objects([object_or_uuid])
714 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
715 @all_links_for[uuid] ||= []
718 # helper method to preload links for given objects and uuids
719 helper_method :preload_links_for_objects
720 def preload_links_for_objects objects_and_uuids
721 @all_links_for ||= {}
723 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
724 return @all_links_for if objects_and_uuids.empty?
726 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
728 # if already preloaded for all of these uuids, return
729 if not uuids.select { |x| @all_links_for[x].nil? }.any?
730 return @all_links_for
734 @all_links_for[x] = []
737 # TODO: make sure we get every page of results from API server
738 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
739 @all_links_for[link.head_uuid] << link
744 # helper method to get a certain number of objects of a specific type
745 # this can be used to replace any uses of: "dataclass.limit(n)"
746 helper_method :get_n_objects_of_class
747 def get_n_objects_of_class dataclass, size
748 @objects_map_for ||= {}
750 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
751 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
753 # if the objects_map_for has a value for this dataclass, and the
754 # size used to retrieve those objects is equal, return it
755 size_key = "#{dataclass.name}_size"
756 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
757 (@objects_map_for[size_key] == size)
758 return @objects_map_for[dataclass.name]
761 @objects_map_for[size_key] = size
762 @objects_map_for[dataclass.name] = dataclass.limit(size)
765 # helper method to get collections for the given uuid
766 helper_method :collections_for_object
767 def collections_for_object uuid
768 raise ArgumentError, 'No input argument' unless uuid
769 preload_collections_for_objects([uuid])
770 @all_collections_for[uuid] ||= []
773 # helper method to preload collections for the given uuids
774 helper_method :preload_collections_for_objects
775 def preload_collections_for_objects uuids
776 @all_collections_for ||= {}
778 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
779 return @all_collections_for if uuids.empty?
781 # if already preloaded for all of these uuids, return
782 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
783 return @all_collections_for
787 @all_collections_for[x] = []
790 # TODO: make sure we get every page of results from API server
791 Collection.where(uuid: uuids).each do |collection|
792 @all_collections_for[collection.uuid] << collection
797 # helper method to get log collections for the given log
798 helper_method :log_collections_for_object
799 def log_collections_for_object log
800 raise ArgumentError, 'No input argument' unless log
802 preload_log_collections_for_objects([log])
805 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
806 if fixup && fixup.size>1
810 @all_log_collections_for[uuid] ||= []
813 # helper method to preload collections for the given uuids
814 helper_method :preload_log_collections_for_objects
815 def preload_log_collections_for_objects logs
816 @all_log_collections_for ||= {}
818 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
819 return @all_log_collections_for if logs.empty?
823 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
824 if fixup && fixup.size>1
831 # if already preloaded for all of these uuids, return
832 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
833 return @all_log_collections_for
837 @all_log_collections_for[x] = []
840 # TODO: make sure we get every page of results from API server
841 Collection.where(uuid: uuids).each do |collection|
842 @all_log_collections_for[collection.uuid] << collection
844 @all_log_collections_for
847 # helper method to get object of a given dataclass and uuid
848 helper_method :object_for_dataclass
849 def object_for_dataclass dataclass, uuid
850 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
851 preload_objects_for_dataclass(dataclass, [uuid])
855 # helper method to preload objects for given dataclass and uuids
856 helper_method :preload_objects_for_dataclass
857 def preload_objects_for_dataclass dataclass, uuids
860 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
861 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
863 return @objects_for if uuids.empty?
865 # if already preloaded for all of these uuids, return
866 if not uuids.select { |x| @objects_for[x].nil? }.any?
870 dataclass.where(uuid: uuids).each do |obj|
871 @objects_for[obj.uuid] = obj