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 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
271 f.json { render json: @object }
273 redirect_to(params[:return_to] || :back)
278 self.render_error status: 422
283 Thread.current[:user]
287 controller_name.classify.constantize
290 def breadcrumb_page_name
291 (@breadcrumb_page_name ||
292 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
301 %w(Attributes Advanced)
306 def strip_token_from_path(path)
307 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
310 def redirect_to_login
313 if request.method.in? ['GET', 'HEAD']
314 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
316 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."
321 @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.']
322 self.render_error status: 422
325 false # For convenience to return from callbacks
328 def using_specific_api_token(api_token)
330 [:arvados_api_token, :user].each do |key|
331 start_values[key] = Thread.current[key]
333 load_api_token(api_token)
337 start_values.each_key { |key| Thread.current[key] = start_values[key] }
341 def find_object_by_uuid
342 if params[:id] and params[:id].match /\D/
343 params[:uuid] = params.delete :id
348 elsif not params[:uuid].is_a?(String)
349 @object = model_class.where(uuid: params[:uuid]).first
350 elsif params[:uuid].empty?
352 elsif (model_class != Link and
353 resource_class_for_uuid(params[:uuid]) == Link)
354 @name_link = Link.find(params[:uuid])
355 @object = model_class.find(@name_link.head_uuid)
357 @object = model_class.find(params[:uuid])
359 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
360 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
363 render_not_found(error)
370 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
372 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
375 # Set up the thread with the given API token and associated user object.
376 def load_api_token(new_token)
377 Thread.current[:arvados_api_token] = new_token
379 Thread.current[:user] = nil
380 elsif (new_token == session[:arvados_api_token]) and
381 session[:user].andand[:is_active]
382 Thread.current[:user] = User.new(session[:user])
384 Thread.current[:user] = User.current
388 # If there's a valid api_token parameter, set up the session with that
389 # user's information. Return true if the method redirects the request
390 # (usually a post-login redirect); false otherwise.
391 def setup_user_session
392 return false unless params[:api_token]
393 Thread.current[:arvados_api_token] = params[:api_token]
396 rescue ArvadosApiClient::NotLoggedInException
397 false # We may redirect to login, or not, based on the current action.
399 session[:arvados_api_token] = params[:api_token]
403 first_name: user.first_name,
404 last_name: user.last_name,
405 is_active: user.is_active,
406 is_admin: user.is_admin,
409 if !request.format.json? and request.method.in? ['GET', 'HEAD']
410 # Repeat this request with api_token in the (new) session
411 # cookie instead of the query string. This prevents API
412 # tokens from appearing in (and being inadvisedly copied
413 # and pasted from) browser Location bars.
414 redirect_to strip_token_from_path(request.fullpath)
420 Thread.current[:arvados_api_token] = nil
424 # Save the session API token in thread-local storage, and yield.
425 # This method also takes care of session setup if the request
426 # provides a valid api_token parameter.
427 # If a token is unavailable or expired, the block is still run, with
429 def set_thread_api_token
430 if Thread.current[:arvados_api_token]
431 yield # An API token has already been found - pass it through.
433 elsif setup_user_session
434 return # A new session was set up and received a response.
438 load_api_token(session[:arvados_api_token])
440 rescue ArvadosApiClient::NotLoggedInException
441 # If we got this error with a token, it must've expired.
442 # Retry the request without a token.
443 unless Thread.current[:arvados_api_token].nil?
448 # Remove token in case this Thread is used for anything else.
453 # Reroute this request if an API token is unavailable.
454 def require_thread_api_token
455 if Thread.current[:arvados_api_token]
457 elsif session[:arvados_api_token]
458 # Expired session. Clear it before refreshing login so that,
459 # if this login procedure fails, we end up showing the "please
460 # log in" page instead of getting stuck in a redirect loop.
461 session.delete :arvados_api_token
464 render 'users/welcome'
468 def ensure_current_user_is_admin
469 unless current_user and current_user.is_admin
470 @errors = ['Permission denied']
471 self.render_error status: 401
475 def check_user_agreements
476 if current_user && !current_user.is_active
477 if not current_user.is_invited
478 return render 'users/inactive'
480 signatures = UserAgreement.signatures
481 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
482 @required_user_agreements = UserAgreement.all.map do |ua|
483 if not @signed_ua_uuids.index ua.uuid
484 Collection.find(ua.uuid)
487 if @required_user_agreements.empty?
488 # No agreements to sign. Perhaps we just need to ask?
489 current_user.activate
490 if !current_user.is_active
491 logger.warn "#{current_user.uuid.inspect}: " +
492 "No user agreements to sign, but activate failed!"
495 if !current_user.is_active
496 render 'user_agreements/index'
503 return Rails.configuration.arvados_theme
506 @@notification_tests = []
508 @@notification_tests.push lambda { |controller, current_user|
509 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
512 return lambda { |view|
513 view.render partial: 'notifications/ssh_key_notification'
517 #@@notification_tests.push lambda { |controller, current_user|
518 # Job.limit(1).where(created_by: current_user.uuid).each do
521 # return lambda { |view|
522 # view.render partial: 'notifications/jobs_notification'
526 @@notification_tests.push lambda { |controller, current_user|
527 Collection.limit(1).where(created_by: current_user.uuid).each do
530 return lambda { |view|
531 view.render partial: 'notifications/collections_notification'
535 @@notification_tests.push lambda { |controller, current_user|
536 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
539 return lambda { |view|
540 view.render partial: 'notifications/pipelines_notification'
544 def check_user_notifications
545 return if params['tab_pane']
547 @notification_count = 0
551 @showallalerts = false
552 @@notification_tests.each do |t|
553 a = t.call(self, current_user)
555 @notification_count += 1
556 @notifications.push a
561 if @notification_count == 0
562 @notification_count = ''
566 helper_method :all_projects
568 @all_projects ||= Group.
569 filter([['group_class','in',['project','folder']]]).order('name')
572 helper_method :my_projects
574 return @my_projects if @my_projects
577 all_projects.each do |g|
578 root_of[g.uuid] = g.owner_uuid
584 root_of = root_of.each_with_object({}) do |(child, parent), h|
586 h[child] = root_of[parent]
593 @my_projects = @my_projects.select do |g|
594 root_of[g.uuid] == current_user.uuid
598 helper_method :projects_shared_with_me
599 def projects_shared_with_me
600 my_project_uuids = my_projects.collect &:uuid
601 all_projects.reject { |x| x.uuid.in? my_project_uuids }
604 helper_method :recent_jobs_and_pipelines
605 def recent_jobs_and_pipelines
607 PipelineInstance.limit(10)).
609 x.finished_at || x.started_at || x.created_at rescue x.created_at
613 helper_method :my_project_tree
619 helper_method :shared_project_tree
620 def shared_project_tree
625 def build_project_trees
626 return if @my_project_tree and @shared_project_tree
627 parent_of = {current_user.uuid => 'me'}
628 all_projects.each do |ob|
629 parent_of[ob.uuid] = ob.owner_uuid
631 children_of = {false => [], 'me' => [current_user]}
632 all_projects.each do |ob|
633 if ob.owner_uuid != current_user.uuid and
634 not parent_of.has_key? ob.owner_uuid
635 parent_of[ob.uuid] = false
637 children_of[parent_of[ob.uuid]] ||= []
638 children_of[parent_of[ob.uuid]] << ob
640 buildtree = lambda do |children_of, root_uuid=false|
642 children_of[root_uuid].andand.each do |ob|
643 tree[ob] = buildtree.call(children_of, ob.uuid)
647 sorted_paths = lambda do |tree, depth=0|
649 tree.keys.sort_by { |ob|
650 ob.is_a?(String) ? ob : ob.friendly_link_name
652 paths << {object: ob, depth: depth}
653 paths += sorted_paths.call tree[ob], depth+1
658 sorted_paths.call buildtree.call(children_of, 'me')
659 @shared_project_tree =
660 sorted_paths.call({'Shared with me' =>
661 buildtree.call(children_of, false)})
664 helper_method :get_object
666 if @get_object.nil? and @objects
667 @get_object = @objects.each_with_object({}) do |object, h|
668 h[object.uuid] = object
675 helper_method :project_breadcrumbs
676 def project_breadcrumbs
678 current = @name_link || @object
680 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
681 crumbs.prepend current
683 if current.is_a? Link
684 current = Group.find?(current.tail_uuid)
686 current = Group.find?(current.owner_uuid)
692 helper_method :current_project_uuid
693 def current_project_uuid
694 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
696 elsif @name_link.andand.tail_uuid
698 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
705 # helper method to get links for given object or uuid
706 helper_method :links_for_object
707 def links_for_object object_or_uuid
708 raise ArgumentError, 'No input argument' unless object_or_uuid
709 preload_links_for_objects([object_or_uuid])
710 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
711 @all_links_for[uuid] ||= []
714 # helper method to preload links for given objects and uuids
715 helper_method :preload_links_for_objects
716 def preload_links_for_objects objects_and_uuids
717 @all_links_for ||= {}
719 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
720 return @all_links_for if objects_and_uuids.empty?
722 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
724 # if already preloaded for all of these uuids, return
725 if not uuids.select { |x| @all_links_for[x].nil? }.any?
726 return @all_links_for
730 @all_links_for[x] = []
733 # TODO: make sure we get every page of results from API server
734 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
735 @all_links_for[link.head_uuid] << link
740 # helper method to get a certain number of objects of a specific type
741 # this can be used to replace any uses of: "dataclass.limit(n)"
742 helper_method :get_n_objects_of_class
743 def get_n_objects_of_class dataclass, size
744 @objects_map_for ||= {}
746 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
747 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
749 # if the objects_map_for has a value for this dataclass, and the
750 # size used to retrieve those objects is equal, return it
751 size_key = "#{dataclass.name}_size"
752 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
753 (@objects_map_for[size_key] == size)
754 return @objects_map_for[dataclass.name]
757 @objects_map_for[size_key] = size
758 @objects_map_for[dataclass.name] = dataclass.limit(size)
761 # helper method to get collections for the given uuid
762 helper_method :collections_for_object
763 def collections_for_object uuid
764 raise ArgumentError, 'No input argument' unless uuid
765 preload_collections_for_objects([uuid])
766 @all_collections_for[uuid] ||= []
769 # helper method to preload collections for the given uuids
770 helper_method :preload_collections_for_objects
771 def preload_collections_for_objects uuids
772 @all_collections_for ||= {}
774 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
775 return @all_collections_for if uuids.empty?
777 # if already preloaded for all of these uuids, return
778 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
779 return @all_collections_for
783 @all_collections_for[x] = []
786 # TODO: make sure we get every page of results from API server
787 Collection.where(uuid: uuids).each do |collection|
788 @all_collections_for[collection.uuid] << collection
793 # helper method to get log collections for the given log
794 helper_method :log_collections_for_object
795 def log_collections_for_object log
796 raise ArgumentError, 'No input argument' unless log
798 preload_log_collections_for_objects([log])
801 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
802 if fixup && fixup.size>1
806 @all_log_collections_for[uuid] ||= []
809 # helper method to preload collections for the given uuids
810 helper_method :preload_log_collections_for_objects
811 def preload_log_collections_for_objects logs
812 @all_log_collections_for ||= {}
814 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
815 return @all_log_collections_for if logs.empty?
819 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
820 if fixup && fixup.size>1
827 # if already preloaded for all of these uuids, return
828 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
829 return @all_log_collections_for
833 @all_log_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_log_collections_for[collection.uuid] << collection
840 @all_log_collections_for
843 # helper method to get object of a given dataclass and uuid
844 helper_method :object_for_dataclass
845 def object_for_dataclass dataclass, uuid
846 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
847 preload_objects_for_dataclass(dataclass, [uuid])
851 # helper method to preload objects for given dataclass and uuids
852 helper_method :preload_objects_for_dataclass
853 def preload_objects_for_dataclass dataclass, uuids
856 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
857 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
859 return @objects_for if uuids.empty?
861 # if already preloaded for all of these uuids, return
862 if not uuids.select { |x| @objects_for[x].nil? }.any?
866 dataclass.where(uuid: uuids).each do |obj|
867 @objects_for[obj.uuid] = obj