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 :thread_with_mandatory_api_token, except: ERROR_ACTIONS
12 around_filter :thread_with_optional_api_token
13 before_filter :check_user_agreements, except: ERROR_ACTIONS
14 before_filter :check_user_notifications, except: ERROR_ACTIONS
15 before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
19 rescue_from Exception,
20 :with => :render_exception
21 rescue_from ActiveRecord::RecordNotFound,
22 :with => :render_not_found
23 rescue_from ActionController::RoutingError,
24 :with => :render_not_found
25 rescue_from ActionController::UnknownController,
26 :with => :render_not_found
27 rescue_from ::AbstractController::ActionNotFound,
28 :with => :render_not_found
31 def unprocessable(message=nil)
34 @errors << message if message
35 render_error status: 422
38 def render_error(opts)
39 opts = {status: 500}.merge 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 opts.merge(controller: 'application', action: 'error') }
50 def render_exception(e)
51 logger.error e.inspect
52 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
53 if @object.andand.errors.andand.full_messages.andand.any?
54 @errors = @object.errors.full_messages
58 self.render_error status: 422
61 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
62 logger.error e.inspect
63 @errors = ["Path not found"]
64 self.render_error status: 404
67 def find_objects_for_index
70 @limit = params[:limit].to_i
75 @offset = params[:offset].to_i
80 filters = params[:filters]
81 if filters.is_a? String
82 filters = Oj.load filters
87 @objects ||= model_class
88 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
93 f.json { render json: @objects }
96 comparable = self.respond_to? :compare
97 render(partial: 'show_' + params['tab_pane'].downcase,
98 locals: { comparable: comparable, objects: @objects })
108 find_objects_for_index if !@objects
112 helper_method :next_page_offset
114 if @objects.respond_to?(:result_offset) and
115 @objects.respond_to?(:result_limit) and
116 @objects.respond_to?(:items_available)
117 next_offset = @objects.result_offset + @objects.result_limit
118 if next_offset < @objects.items_available
128 return render_not_found("object not found")
131 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
133 if params['tab_pane']
134 comparable = self.respond_to? :compare
135 render(partial: 'show_' + params['tab_pane'].downcase,
136 locals: { comparable: comparable, objects: @objects })
137 elsif request.method.in? ['GET', 'HEAD']
140 redirect_to params[:return_to] || @object
148 params[:limit] ||= 40
150 if params[:project_uuid] and !params[:project_uuid].empty?
151 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
153 find_objects_for_index if !@objects
159 content: render_to_string(partial: "choose_rows.html",
162 multiple: params[:multiple]
164 next_page_href: @next_page_href
169 render partial: 'choose', locals: {multiple: params[:multiple]}
176 return render_not_found("object not found")
181 @object = model_class.new
185 @updates ||= params[@object.resource_param_name.to_sym]
186 @updates.keys.each do |attr|
187 if @object.send(attr).is_a? Hash
188 if @updates[attr].is_a? String
189 @updates[attr] = Oj.load @updates[attr]
191 if params[:merge] || params["merge_#{attr}".to_sym]
192 # Merge provided Hash with current Hash, instead of
194 @updates[attr] = @object.send(attr).with_indifferent_access.
195 deep_merge(@updates[attr].with_indifferent_access)
199 if @object.update_attributes @updates
202 self.render_error status: 422
207 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
208 @new_resource_attrs ||= {}
209 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
210 @object ||= model_class.new @new_resource_attrs, params["options"]
213 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
220 self.render_error status: 422
224 # Clone the given object, merging any attribute values supplied as
225 # with a create action.
227 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
228 @new_resource_attrs ||= {}
229 @object = @object.dup
230 @object.update_attributes @new_resource_attrs
231 if not @new_resource_attrs[:name] and @object.respond_to? :name
232 if @object.name and @object.name != ''
233 @object.name = "Copy of #{@object.name}"
235 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
245 f.json { render json: @object }
247 redirect_to(params[:return_to] || :back)
252 self.render_error status: 422
257 return Thread.current[:user] if Thread.current[:user]
259 if Thread.current[:arvados_api_token]
261 if session[:user][:is_active] != true
262 Thread.current[:user] = User.current
264 Thread.current[:user] = User.new(session[:user])
267 Thread.current[:user] = User.current
270 logger.error "No API token in Thread"
276 controller_name.classify.constantize
279 def breadcrumb_page_name
280 (@breadcrumb_page_name ||
281 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
290 %w(Attributes Advanced)
295 def redirect_to_login
298 if request.method.in? ['GET', 'HEAD']
299 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
301 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."
306 @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.']
307 self.render_error status: 422
310 false # For convenience to return from callbacks
313 def using_specific_api_token(api_token)
315 [:arvados_api_token, :user].each do |key|
316 start_values[key] = Thread.current[key]
318 Thread.current[:arvados_api_token] = api_token
319 Thread.current[:user] = nil
323 start_values.each_key { |key| Thread.current[key] = start_values[key] }
327 def find_object_by_uuid
328 if params[:id] and params[:id].match /\D/
329 params[:uuid] = params.delete :id
333 elsif params[:uuid].is_a? String
334 if params[:uuid].empty?
337 if (model_class != Link and
338 resource_class_for_uuid(params[:uuid]) == Link)
339 @name_link = Link.find(params[:uuid])
340 @object = model_class.find(@name_link.head_uuid)
342 @object = model_class.find(params[:uuid])
346 @object = model_class.where(uuid: params[:uuid]).first
351 Thread.current[:arvados_api_token] = nil
352 Thread.current[:user] = nil
353 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
355 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
358 def thread_with_api_token(login_optional = false)
360 try_redirect_to_login = true
361 if params[:api_token]
362 try_redirect_to_login = false
363 Thread.current[:arvados_api_token] = params[:api_token]
364 # Before copying the token into session[], do a simple API
365 # call to verify its authenticity.
367 session[:arvados_api_token] = params[:api_token]
372 first_name: u.first_name,
373 last_name: u.last_name,
374 is_active: u.is_active,
375 is_admin: u.is_admin,
378 if !request.format.json? and request.method.in? ['GET', 'HEAD']
379 # Repeat this request with api_token in the (new) session
380 # cookie instead of the query string. This prevents API
381 # tokens from appearing in (and being inadvisedly copied
382 # and pasted from) browser Location bars.
383 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
388 @errors = ['Invalid API token']
389 self.render_error status: 401
391 elsif session[:arvados_api_token]
392 # In this case, the token must have already verified at some
393 # point, but it might have been revoked since. We'll try
394 # using it, and catch the exception if it doesn't work.
395 try_redirect_to_login = false
396 Thread.current[:arvados_api_token] = session[:arvados_api_token]
399 rescue ArvadosApiClient::NotLoggedInException
400 try_redirect_to_login = true
403 logger.debug "No token received, session is #{session.inspect}"
405 if try_redirect_to_login
406 unless login_optional
409 # login is optional for this route so go on to the regular controller
410 Thread.current[:arvados_api_token] = nil
415 # Remove token in case this Thread is used for anything else.
416 Thread.current[:arvados_api_token] = nil
420 def thread_with_mandatory_api_token
421 thread_with_api_token(true) do
422 if Thread.current[:arvados_api_token]
424 elsif session[:arvados_api_token]
425 # Expired session. Clear it before refreshing login so that,
426 # if this login procedure fails, we end up showing the "please
427 # log in" page instead of getting stuck in a redirect loop.
428 session.delete :arvados_api_token
431 render 'users/welcome'
436 # This runs after thread_with_mandatory_api_token in the filter chain.
437 def thread_with_optional_api_token
438 if Thread.current[:arvados_api_token]
439 # We are already inside thread_with_mandatory_api_token.
442 # We skipped thread_with_mandatory_api_token. Use the optional version.
443 thread_with_api_token(true) do
451 Link.where(uuid: 'just-verifying-my-api-token')
453 rescue ArvadosApiClient::NotLoggedInException
458 def ensure_current_user_is_admin
459 unless current_user and current_user.is_admin
460 @errors = ['Permission denied']
461 self.render_error status: 401
465 def check_user_agreements
466 if current_user && !current_user.is_active
467 if not current_user.is_invited
468 return render 'users/inactive'
470 signatures = UserAgreement.signatures
471 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
472 @required_user_agreements = UserAgreement.all.map do |ua|
473 if not @signed_ua_uuids.index ua.uuid
474 Collection.find(ua.uuid)
477 if @required_user_agreements.empty?
478 # No agreements to sign. Perhaps we just need to ask?
479 current_user.activate
480 if !current_user.is_active
481 logger.warn "#{current_user.uuid.inspect}: " +
482 "No user agreements to sign, but activate failed!"
485 if !current_user.is_active
486 render 'user_agreements/index'
493 return Rails.configuration.arvados_theme
496 @@notification_tests = []
498 @@notification_tests.push lambda { |controller, current_user|
499 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
502 return lambda { |view|
503 view.render partial: 'notifications/ssh_key_notification'
507 #@@notification_tests.push lambda { |controller, current_user|
508 # Job.limit(1).where(created_by: current_user.uuid).each do
511 # return lambda { |view|
512 # view.render partial: 'notifications/jobs_notification'
516 @@notification_tests.push lambda { |controller, current_user|
517 Collection.limit(1).where(created_by: current_user.uuid).each do
520 return lambda { |view|
521 view.render partial: 'notifications/collections_notification'
525 @@notification_tests.push lambda { |controller, current_user|
526 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
529 return lambda { |view|
530 view.render partial: 'notifications/pipelines_notification'
534 def check_user_notifications
535 return if params['tab_pane']
537 @notification_count = 0
541 @showallalerts = false
542 @@notification_tests.each do |t|
543 a = t.call(self, current_user)
545 @notification_count += 1
546 @notifications.push a
551 if @notification_count == 0
552 @notification_count = ''
556 helper_method :all_projects
558 @all_projects ||= Group.
559 filter([['group_class','in',['project','folder']]]).order('name')
562 helper_method :my_projects
564 return @my_projects if @my_projects
567 all_projects.each do |g|
568 root_of[g.uuid] = g.owner_uuid
574 root_of = root_of.each_with_object({}) do |(child, parent), h|
576 h[child] = root_of[parent]
583 @my_projects = @my_projects.select do |g|
584 root_of[g.uuid] == current_user.uuid
588 helper_method :projects_shared_with_me
589 def projects_shared_with_me
590 my_project_uuids = my_projects.collect &:uuid
591 all_projects.reject { |x| x.uuid.in? my_project_uuids }
594 helper_method :recent_jobs_and_pipelines
595 def recent_jobs_and_pipelines
597 PipelineInstance.limit(10)).
599 x.finished_at || x.started_at || x.created_at rescue x.created_at
603 helper_method :my_project_tree
609 helper_method :shared_project_tree
610 def shared_project_tree
615 def build_project_trees
616 return if @my_project_tree and @shared_project_tree
617 parent_of = {current_user.uuid => 'me'}
618 all_projects.each do |ob|
619 parent_of[ob.uuid] = ob.owner_uuid
621 children_of = {false => [], 'me' => [current_user]}
622 all_projects.each do |ob|
623 if ob.owner_uuid != current_user.uuid and
624 not parent_of.has_key? ob.owner_uuid
625 parent_of[ob.uuid] = false
627 children_of[parent_of[ob.uuid]] ||= []
628 children_of[parent_of[ob.uuid]] << ob
630 buildtree = lambda do |children_of, root_uuid=false|
632 children_of[root_uuid].andand.each do |ob|
633 tree[ob] = buildtree.call(children_of, ob.uuid)
637 sorted_paths = lambda do |tree, depth=0|
639 tree.keys.sort_by { |ob|
640 ob.is_a?(String) ? ob : ob.friendly_link_name
642 paths << {object: ob, depth: depth}
643 paths += sorted_paths.call tree[ob], depth+1
648 sorted_paths.call buildtree.call(children_of, 'me')
649 @shared_project_tree =
650 sorted_paths.call({'Shared with me' =>
651 buildtree.call(children_of, false)})
654 helper_method :get_object
656 if @get_object.nil? and @objects
657 @get_object = @objects.each_with_object({}) do |object, h|
658 h[object.uuid] = object
665 helper_method :project_breadcrumbs
666 def project_breadcrumbs
668 current = @name_link || @object
670 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
671 crumbs.prepend current
673 if current.is_a? Link
674 current = Group.find?(current.tail_uuid)
676 current = Group.find?(current.owner_uuid)
682 helper_method :current_project_uuid
683 def current_project_uuid
684 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
686 elsif @name_link.andand.tail_uuid
688 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
695 # helper method to get links for given object or uuid
696 helper_method :links_for_object
697 def links_for_object object_or_uuid
698 raise ArgumentError, 'No input argument' unless object_or_uuid
699 preload_links_for_objects([object_or_uuid])
700 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
701 @all_links_for[uuid] ||= []
704 # helper method to preload links for given objects and uuids
705 helper_method :preload_links_for_objects
706 def preload_links_for_objects objects_and_uuids
707 @all_links_for ||= {}
709 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
710 return @all_links_for if objects_and_uuids.empty?
712 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
714 # if already preloaded for all of these uuids, return
715 if not uuids.select { |x| @all_links_for[x].nil? }.any?
716 return @all_links_for
720 @all_links_for[x] = []
723 # TODO: make sure we get every page of results from API server
724 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
725 @all_links_for[link.head_uuid] << link
730 # helper method to get a certain number of objects of a specific type
731 # this can be used to replace any uses of: "dataclass.limit(n)"
732 helper_method :get_n_objects_of_class
733 def get_n_objects_of_class dataclass, size
734 @objects_map_for ||= {}
736 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
737 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
739 # if the objects_map_for has a value for this dataclass, and the
740 # size used to retrieve those objects is equal, return it
741 size_key = "#{dataclass.name}_size"
742 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
743 (@objects_map_for[size_key] == size)
744 return @objects_map_for[dataclass.name]
747 @objects_map_for[size_key] = size
748 @objects_map_for[dataclass.name] = dataclass.limit(size)
751 # helper method to get collections for the given uuid
752 helper_method :collections_for_object
753 def collections_for_object uuid
754 raise ArgumentError, 'No input argument' unless uuid
755 preload_collections_for_objects([uuid])
756 @all_collections_for[uuid] ||= []
759 # helper method to preload collections for the given uuids
760 helper_method :preload_collections_for_objects
761 def preload_collections_for_objects uuids
762 @all_collections_for ||= {}
764 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
765 return @all_collections_for if uuids.empty?
767 # if already preloaded for all of these uuids, return
768 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
769 return @all_collections_for
773 @all_collections_for[x] = []
776 # TODO: make sure we get every page of results from API server
777 Collection.where(uuid: uuids).each do |collection|
778 @all_collections_for[collection.uuid] << collection
783 # helper method to get log collections for the given log
784 helper_method :log_collections_for_object
785 def log_collections_for_object log
786 raise ArgumentError, 'No input argument' unless log
788 preload_log_collections_for_objects([log])
791 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
792 if fixup && fixup.size>1
796 @all_log_collections_for[uuid] ||= []
799 # helper method to preload collections for the given uuids
800 helper_method :preload_log_collections_for_objects
801 def preload_log_collections_for_objects logs
802 @all_log_collections_for ||= {}
804 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
805 return @all_log_collections_for if logs.empty?
809 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
810 if fixup && fixup.size>1
817 # if already preloaded for all of these uuids, return
818 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
819 return @all_log_collections_for
823 @all_log_collections_for[x] = []
826 # TODO: make sure we get every page of results from API server
827 Collection.where(uuid: uuids).each do |collection|
828 @all_log_collections_for[collection.uuid] << collection
830 @all_log_collections_for
833 # helper method to get object of a given dataclass and uuid
834 helper_method :object_for_dataclass
835 def object_for_dataclass dataclass, uuid
836 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
837 preload_objects_for_dataclass(dataclass, [uuid])
841 # helper method to preload objects for given dataclass and uuids
842 helper_method :preload_objects_for_dataclass
843 def preload_objects_for_dataclass dataclass, uuids
846 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
847 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
849 return @objects_for if uuids.empty?
851 # if already preloaded for all of these uuids, return
852 if not uuids.select { |x| @objects_for[x].nil? }.any?
856 dataclass.where(uuid: uuids).each do |obj|
857 @objects_for[obj.uuid] = obj