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
135 def next_page_offset objects=nil
139 if objects.respond_to?(:result_offset) and
140 objects.respond_to?(:result_limit) and
141 objects.respond_to?(:items_available)
142 next_offset = objects.result_offset + objects.result_limit
143 if next_offset < objects.items_available
153 return render_not_found("object not found")
156 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
158 if params['tab_pane']
159 comparable = self.respond_to? :compare
160 render(partial: 'show_' + params['tab_pane'].downcase,
161 locals: { comparable: comparable, objects: @objects })
162 elsif request.method.in? ['GET', 'HEAD']
165 redirect_to params[:return_to] || @object
173 params[:limit] ||= 40
175 if params[:project_uuid] and !params[:project_uuid].empty?
176 # We want the chooser to show objects of the controllers's model_class
177 # type within a specific project specified by project_uuid, so fetch the
178 # project and request the contents of the project filtered on the
179 # controllers's model_class kind.
180 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
182 find_objects_for_index if !@objects
188 content: render_to_string(partial: "choose_rows.html",
191 multiple: params[:multiple]
193 next_page_href: @next_page_href
198 render partial: 'choose', locals: {multiple: params[:multiple]}
205 return render_not_found("object not found")
210 @object = model_class.new
214 @updates ||= params[@object.resource_param_name.to_sym]
215 @updates.keys.each do |attr|
216 if @object.send(attr).is_a? Hash
217 if @updates[attr].is_a? String
218 @updates[attr] = Oj.load @updates[attr]
220 if params[:merge] || params["merge_#{attr}".to_sym]
221 # Merge provided Hash with current Hash, instead of
223 @updates[attr] = @object.send(attr).with_indifferent_access.
224 deep_merge(@updates[attr].with_indifferent_access)
228 if @object.update_attributes @updates
231 self.render_error status: 422
236 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
237 @new_resource_attrs ||= {}
238 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
239 @object ||= model_class.new @new_resource_attrs, params["options"]
242 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
249 self.render_error status: 422
253 # Clone the given object, merging any attribute values supplied as
254 # with a create action.
256 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
257 @new_resource_attrs ||= {}
258 @object = @object.dup
259 @object.update_attributes @new_resource_attrs
260 if not @new_resource_attrs[:name] and @object.respond_to? :name
261 if @object.name and @object.name != ''
262 @object.name = "Copy of #{@object.name}"
274 f.json { render json: @object }
276 redirect_to(params[:return_to] || :back)
281 self.render_error status: 422
286 Thread.current[:user]
290 controller_name.classify.constantize
293 def breadcrumb_page_name
294 (@breadcrumb_page_name ||
295 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
304 %w(Attributes Advanced)
309 def strip_token_from_path(path)
310 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
313 def redirect_to_login
316 if request.method.in? ['GET', 'HEAD']
317 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
319 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."
324 @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.']
325 self.render_error status: 422
328 false # For convenience to return from callbacks
331 def using_specific_api_token(api_token)
333 [:arvados_api_token, :user].each do |key|
334 start_values[key] = Thread.current[key]
336 load_api_token(api_token)
340 start_values.each_key { |key| Thread.current[key] = start_values[key] }
344 def find_object_by_uuid
345 if params[:id] and params[:id].match /\D/
346 params[:uuid] = params.delete :id
351 elsif not params[:uuid].is_a?(String)
352 @object = model_class.where(uuid: params[:uuid]).first
353 elsif params[:uuid].empty?
355 elsif (model_class != Link and
356 resource_class_for_uuid(params[:uuid]) == Link)
357 @name_link = Link.find(params[:uuid])
358 @object = model_class.find(@name_link.head_uuid)
360 @object = model_class.find(params[:uuid])
362 rescue ArvadosApiClient::NotFoundException, RuntimeError => error
363 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
366 render_not_found(error)
373 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
375 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
378 # Set up the thread with the given API token and associated user object.
379 def load_api_token(new_token)
380 Thread.current[:arvados_api_token] = new_token
382 Thread.current[:user] = nil
383 elsif (new_token == session[:arvados_api_token]) and
384 session[:user].andand[:is_active]
385 Thread.current[:user] = User.new(session[:user])
387 Thread.current[:user] = User.current
391 # If there's a valid api_token parameter, set up the session with that
392 # user's information. Return true if the method redirects the request
393 # (usually a post-login redirect); false otherwise.
394 def setup_user_session
395 return false unless params[:api_token]
396 Thread.current[:arvados_api_token] = params[:api_token]
399 rescue ArvadosApiClient::NotLoggedInException
400 false # We may redirect to login, or not, based on the current action.
402 session[:arvados_api_token] = params[:api_token]
406 first_name: user.first_name,
407 last_name: user.last_name,
408 is_active: user.is_active,
409 is_admin: user.is_admin,
412 if !request.format.json? and request.method.in? ['GET', 'HEAD']
413 # Repeat this request with api_token in the (new) session
414 # cookie instead of the query string. This prevents API
415 # tokens from appearing in (and being inadvisedly copied
416 # and pasted from) browser Location bars.
417 redirect_to strip_token_from_path(request.fullpath)
423 Thread.current[:arvados_api_token] = nil
427 # Save the session API token in thread-local storage, and yield.
428 # This method also takes care of session setup if the request
429 # provides a valid api_token parameter.
430 # If a token is unavailable or expired, the block is still run, with
432 def set_thread_api_token
433 if Thread.current[:arvados_api_token]
434 yield # An API token has already been found - pass it through.
436 elsif setup_user_session
437 return # A new session was set up and received a response.
441 load_api_token(session[:arvados_api_token])
443 rescue ArvadosApiClient::NotLoggedInException
444 # If we got this error with a token, it must've expired.
445 # Retry the request without a token.
446 unless Thread.current[:arvados_api_token].nil?
451 # Remove token in case this Thread is used for anything else.
456 # Reroute this request if an API token is unavailable.
457 def require_thread_api_token
458 if Thread.current[:arvados_api_token]
460 elsif session[:arvados_api_token]
461 # Expired session. Clear it before refreshing login so that,
462 # if this login procedure fails, we end up showing the "please
463 # log in" page instead of getting stuck in a redirect loop.
464 session.delete :arvados_api_token
467 render 'users/welcome'
471 def ensure_current_user_is_admin
472 unless current_user and current_user.is_admin
473 @errors = ['Permission denied']
474 self.render_error status: 401
478 def check_user_agreements
479 if current_user && !current_user.is_active
480 if not current_user.is_invited
481 return render 'users/inactive'
483 signatures = UserAgreement.signatures
484 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
485 @required_user_agreements = UserAgreement.all.map do |ua|
486 if not @signed_ua_uuids.index ua.uuid
487 Collection.find(ua.uuid)
490 if @required_user_agreements.empty?
491 # No agreements to sign. Perhaps we just need to ask?
492 current_user.activate
493 if !current_user.is_active
494 logger.warn "#{current_user.uuid.inspect}: " +
495 "No user agreements to sign, but activate failed!"
498 if !current_user.is_active
499 render 'user_agreements/index'
506 return Rails.configuration.arvados_theme
509 @@notification_tests = []
511 @@notification_tests.push lambda { |controller, current_user|
512 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
515 return lambda { |view|
516 view.render partial: 'notifications/ssh_key_notification'
520 #@@notification_tests.push lambda { |controller, current_user|
521 # Job.limit(1).where(created_by: current_user.uuid).each do
524 # return lambda { |view|
525 # view.render partial: 'notifications/jobs_notification'
529 @@notification_tests.push lambda { |controller, current_user|
530 Collection.limit(1).where(created_by: current_user.uuid).each do
533 return lambda { |view|
534 view.render partial: 'notifications/collections_notification'
538 @@notification_tests.push lambda { |controller, current_user|
539 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
542 return lambda { |view|
543 view.render partial: 'notifications/pipelines_notification'
547 def check_user_notifications
548 return if params['tab_pane']
550 @notification_count = 0
554 @showallalerts = false
555 @@notification_tests.each do |t|
556 a = t.call(self, current_user)
558 @notification_count += 1
559 @notifications.push a
564 if @notification_count == 0
565 @notification_count = ''
569 helper_method :all_projects
571 @all_projects ||= Group.
572 filter([['group_class','in',['project','folder']]]).order('name')
575 helper_method :my_projects
577 return @my_projects if @my_projects
580 all_projects.each do |g|
581 root_of[g.uuid] = g.owner_uuid
587 root_of = root_of.each_with_object({}) do |(child, parent), h|
589 h[child] = root_of[parent]
596 @my_projects = @my_projects.select do |g|
597 root_of[g.uuid] == current_user.uuid
601 helper_method :projects_shared_with_me
602 def projects_shared_with_me
603 my_project_uuids = my_projects.collect &:uuid
604 all_projects.reject { |x| x.uuid.in? my_project_uuids }
607 helper_method :recent_jobs_and_pipelines
608 def recent_jobs_and_pipelines
610 PipelineInstance.limit(10)).
612 x.finished_at || x.started_at || x.created_at rescue x.created_at
616 helper_method :my_project_tree
622 helper_method :shared_project_tree
623 def shared_project_tree
628 def build_project_trees
629 return if @my_project_tree and @shared_project_tree
630 parent_of = {current_user.uuid => 'me'}
631 all_projects.each do |ob|
632 parent_of[ob.uuid] = ob.owner_uuid
634 children_of = {false => [], 'me' => [current_user]}
635 all_projects.each do |ob|
636 if ob.owner_uuid != current_user.uuid and
637 not parent_of.has_key? ob.owner_uuid
638 parent_of[ob.uuid] = false
640 children_of[parent_of[ob.uuid]] ||= []
641 children_of[parent_of[ob.uuid]] << ob
643 buildtree = lambda do |children_of, root_uuid=false|
645 children_of[root_uuid].andand.each do |ob|
646 tree[ob] = buildtree.call(children_of, ob.uuid)
650 sorted_paths = lambda do |tree, depth=0|
652 tree.keys.sort_by { |ob|
653 ob.is_a?(String) ? ob : ob.friendly_link_name
655 paths << {object: ob, depth: depth}
656 paths += sorted_paths.call tree[ob], depth+1
661 sorted_paths.call buildtree.call(children_of, 'me')
662 @shared_project_tree =
663 sorted_paths.call({'Shared with me' =>
664 buildtree.call(children_of, false)})
667 helper_method :get_object
669 if @get_object.nil? and @objects
670 @get_object = @objects.each_with_object({}) do |object, h|
671 h[object.uuid] = object
678 helper_method :project_breadcrumbs
679 def project_breadcrumbs
681 current = @name_link || @object
683 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
684 crumbs.prepend current
686 if current.is_a? Link
687 current = Group.find?(current.tail_uuid)
689 current = Group.find?(current.owner_uuid)
695 helper_method :current_project_uuid
696 def current_project_uuid
697 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
699 elsif @name_link.andand.tail_uuid
701 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
708 # helper method to get links for given object or uuid
709 helper_method :links_for_object
710 def links_for_object object_or_uuid
711 raise ArgumentError, 'No input argument' unless object_or_uuid
712 preload_links_for_objects([object_or_uuid])
713 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
714 @all_links_for[uuid] ||= []
717 # helper method to preload links for given objects and uuids
718 helper_method :preload_links_for_objects
719 def preload_links_for_objects objects_and_uuids
720 @all_links_for ||= {}
722 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
723 return @all_links_for if objects_and_uuids.empty?
725 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
727 # if already preloaded for all of these uuids, return
728 if not uuids.select { |x| @all_links_for[x].nil? }.any?
729 return @all_links_for
733 @all_links_for[x] = []
736 # TODO: make sure we get every page of results from API server
737 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
738 @all_links_for[link.head_uuid] << link
743 # helper method to get a certain number of objects of a specific type
744 # this can be used to replace any uses of: "dataclass.limit(n)"
745 helper_method :get_n_objects_of_class
746 def get_n_objects_of_class dataclass, size
747 @objects_map_for ||= {}
749 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
750 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
752 # if the objects_map_for has a value for this dataclass, and the
753 # size used to retrieve those objects is equal, return it
754 size_key = "#{dataclass.name}_size"
755 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
756 (@objects_map_for[size_key] == size)
757 return @objects_map_for[dataclass.name]
760 @objects_map_for[size_key] = size
761 @objects_map_for[dataclass.name] = dataclass.limit(size)
764 # helper method to get collections for the given uuid
765 helper_method :collections_for_object
766 def collections_for_object uuid
767 raise ArgumentError, 'No input argument' unless uuid
768 preload_collections_for_objects([uuid])
769 @all_collections_for[uuid] ||= []
772 # helper method to preload collections for the given uuids
773 helper_method :preload_collections_for_objects
774 def preload_collections_for_objects uuids
775 @all_collections_for ||= {}
777 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
778 return @all_collections_for if uuids.empty?
780 # if already preloaded for all of these uuids, return
781 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
782 return @all_collections_for
786 @all_collections_for[x] = []
789 # TODO: make sure we get every page of results from API server
790 Collection.where(uuid: uuids).each do |collection|
791 @all_collections_for[collection.uuid] << collection
796 # helper method to get log collections for the given log
797 helper_method :log_collections_for_object
798 def log_collections_for_object log
799 raise ArgumentError, 'No input argument' unless log
801 preload_log_collections_for_objects([log])
804 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
805 if fixup && fixup.size>1
809 @all_log_collections_for[uuid] ||= []
812 # helper method to preload collections for the given uuids
813 helper_method :preload_log_collections_for_objects
814 def preload_log_collections_for_objects logs
815 @all_log_collections_for ||= {}
817 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
818 return @all_log_collections_for if logs.empty?
822 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
823 if fixup && fixup.size>1
830 # if already preloaded for all of these uuids, return
831 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
832 return @all_log_collections_for
836 @all_log_collections_for[x] = []
839 # TODO: make sure we get every page of results from API server
840 Collection.where(uuid: uuids).each do |collection|
841 @all_log_collections_for[collection.uuid] << collection
843 @all_log_collections_for
846 # helper method to get object of a given dataclass and uuid
847 helper_method :object_for_dataclass
848 def object_for_dataclass dataclass, uuid
849 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
850 preload_objects_for_dataclass(dataclass, [uuid])
854 # helper method to preload objects for given dataclass and uuids
855 helper_method :preload_objects_for_dataclass
856 def preload_objects_for_dataclass dataclass, uuids
859 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
860 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
862 return @objects_for if uuids.empty?
864 # if already preloaded for all of these uuids, return
865 if not uuids.select { |x| @objects_for[x].nil? }.any?
869 dataclass.where(uuid: uuids).each do |obj|
870 @objects_for[obj.uuid] = obj