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 # We want the chooser to show objects of the controllers's model_class
152 # type within a specific project specified by project_uuid, so fetch the
153 # project and request the contents of the project filtered on the
154 # controllers's model_class kind.
155 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
157 find_objects_for_index if !@objects
163 content: render_to_string(partial: "choose_rows.html",
166 multiple: params[:multiple]
168 next_page_href: @next_page_href
173 render partial: 'choose', locals: {multiple: params[:multiple]}
180 return render_not_found("object not found")
185 @object = model_class.new
189 @updates ||= params[@object.resource_param_name.to_sym]
190 @updates.keys.each do |attr|
191 if @object.send(attr).is_a? Hash
192 if @updates[attr].is_a? String
193 @updates[attr] = Oj.load @updates[attr]
195 if params[:merge] || params["merge_#{attr}".to_sym]
196 # Merge provided Hash with current Hash, instead of
198 @updates[attr] = @object.send(attr).with_indifferent_access.
199 deep_merge(@updates[attr].with_indifferent_access)
203 if @object.update_attributes @updates
206 self.render_error status: 422
211 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
212 @new_resource_attrs ||= {}
213 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
214 @object ||= model_class.new @new_resource_attrs, params["options"]
217 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
224 self.render_error status: 422
228 # Clone the given object, merging any attribute values supplied as
229 # with a create action.
231 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
232 @new_resource_attrs ||= {}
233 @object = @object.dup
234 @object.update_attributes @new_resource_attrs
235 if not @new_resource_attrs[:name] and @object.respond_to? :name
236 if @object.name and @object.name != ''
237 @object.name = "Copy of #{@object.name}"
239 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
249 f.json { render json: @object }
251 redirect_to(params[:return_to] || :back)
256 self.render_error status: 422
261 return Thread.current[:user] if Thread.current[:user]
263 if Thread.current[:arvados_api_token]
265 if session[:user][:is_active] != true
266 Thread.current[:user] = User.current
268 Thread.current[:user] = User.new(session[:user])
271 Thread.current[:user] = User.current
274 logger.error "No API token in Thread"
280 controller_name.classify.constantize
283 def breadcrumb_page_name
284 (@breadcrumb_page_name ||
285 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
294 %w(Attributes Advanced)
299 def redirect_to_login
302 if request.method.in? ['GET', 'HEAD']
303 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
305 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."
310 @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.']
311 self.render_error status: 422
314 false # For convenience to return from callbacks
317 def using_specific_api_token(api_token)
319 [:arvados_api_token, :user].each do |key|
320 start_values[key] = Thread.current[key]
322 Thread.current[:arvados_api_token] = api_token
323 Thread.current[:user] = nil
327 start_values.each_key { |key| Thread.current[key] = start_values[key] }
331 def find_object_by_uuid
332 if params[:id] and params[:id].match /\D/
333 params[:uuid] = params.delete :id
337 elsif params[:uuid].is_a? String
338 if params[:uuid].empty?
341 if (model_class != Link and
342 resource_class_for_uuid(params[:uuid]) == Link)
343 @name_link = Link.find(params[:uuid])
344 @object = model_class.find(@name_link.head_uuid)
346 @object = model_class.find(params[:uuid])
350 @object = model_class.where(uuid: params[:uuid]).first
355 Thread.current[:arvados_api_token] = nil
356 Thread.current[:user] = nil
357 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
359 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
362 def thread_with_api_token(login_optional = false)
364 try_redirect_to_login = true
365 if params[:api_token]
366 try_redirect_to_login = false
367 Thread.current[:arvados_api_token] = params[:api_token]
368 # Before copying the token into session[], do a simple API
369 # call to verify its authenticity.
371 session[:arvados_api_token] = params[:api_token]
376 first_name: u.first_name,
377 last_name: u.last_name,
378 is_active: u.is_active,
379 is_admin: u.is_admin,
382 if !request.format.json? and request.method.in? ['GET', 'HEAD']
383 # Repeat this request with api_token in the (new) session
384 # cookie instead of the query string. This prevents API
385 # tokens from appearing in (and being inadvisedly copied
386 # and pasted from) browser Location bars.
387 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
392 @errors = ['Invalid API token']
393 self.render_error status: 401
395 elsif session[:arvados_api_token]
396 # In this case, the token must have already verified at some
397 # point, but it might have been revoked since. We'll try
398 # using it, and catch the exception if it doesn't work.
399 try_redirect_to_login = false
400 Thread.current[:arvados_api_token] = session[:arvados_api_token]
403 rescue ArvadosApiClient::NotLoggedInException
404 try_redirect_to_login = true
407 logger.debug "No token received, session is #{session.inspect}"
409 if try_redirect_to_login
410 unless login_optional
413 # login is optional for this route so go on to the regular controller
414 Thread.current[:arvados_api_token] = nil
419 # Remove token in case this Thread is used for anything else.
420 Thread.current[:arvados_api_token] = nil
424 def thread_with_mandatory_api_token
425 thread_with_api_token(true) do
426 if Thread.current[:arvados_api_token]
428 elsif session[:arvados_api_token]
429 # Expired session. Clear it before refreshing login so that,
430 # if this login procedure fails, we end up showing the "please
431 # log in" page instead of getting stuck in a redirect loop.
432 session.delete :arvados_api_token
435 render 'users/welcome'
440 # This runs after thread_with_mandatory_api_token in the filter chain.
441 def thread_with_optional_api_token
442 if Thread.current[:arvados_api_token]
443 # We are already inside thread_with_mandatory_api_token.
446 # We skipped thread_with_mandatory_api_token. Use the optional version.
447 thread_with_api_token(true) do
455 Link.where(uuid: 'just-verifying-my-api-token')
457 rescue ArvadosApiClient::NotLoggedInException
462 def ensure_current_user_is_admin
463 unless current_user and current_user.is_admin
464 @errors = ['Permission denied']
465 self.render_error status: 401
469 def check_user_agreements
470 if current_user && !current_user.is_active
471 if not current_user.is_invited
472 return render 'users/inactive'
474 signatures = UserAgreement.signatures
475 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
476 @required_user_agreements = UserAgreement.all.map do |ua|
477 if not @signed_ua_uuids.index ua.uuid
478 Collection.find(ua.uuid)
481 if @required_user_agreements.empty?
482 # No agreements to sign. Perhaps we just need to ask?
483 current_user.activate
484 if !current_user.is_active
485 logger.warn "#{current_user.uuid.inspect}: " +
486 "No user agreements to sign, but activate failed!"
489 if !current_user.is_active
490 render 'user_agreements/index'
497 return Rails.configuration.arvados_theme
500 @@notification_tests = []
502 @@notification_tests.push lambda { |controller, current_user|
503 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
506 return lambda { |view|
507 view.render partial: 'notifications/ssh_key_notification'
511 #@@notification_tests.push lambda { |controller, current_user|
512 # Job.limit(1).where(created_by: current_user.uuid).each do
515 # return lambda { |view|
516 # view.render partial: 'notifications/jobs_notification'
520 @@notification_tests.push lambda { |controller, current_user|
521 Collection.limit(1).where(created_by: current_user.uuid).each do
524 return lambda { |view|
525 view.render partial: 'notifications/collections_notification'
529 @@notification_tests.push lambda { |controller, current_user|
530 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
533 return lambda { |view|
534 view.render partial: 'notifications/pipelines_notification'
538 def check_user_notifications
539 return if params['tab_pane']
541 @notification_count = 0
545 @showallalerts = false
546 @@notification_tests.each do |t|
547 a = t.call(self, current_user)
549 @notification_count += 1
550 @notifications.push a
555 if @notification_count == 0
556 @notification_count = ''
560 helper_method :all_projects
562 @all_projects ||= Group.
563 filter([['group_class','in',['project','folder']]]).order('name')
566 helper_method :my_projects
568 return @my_projects if @my_projects
571 all_projects.each do |g|
572 root_of[g.uuid] = g.owner_uuid
578 root_of = root_of.each_with_object({}) do |(child, parent), h|
580 h[child] = root_of[parent]
587 @my_projects = @my_projects.select do |g|
588 root_of[g.uuid] == current_user.uuid
592 helper_method :projects_shared_with_me
593 def projects_shared_with_me
594 my_project_uuids = my_projects.collect &:uuid
595 all_projects.reject { |x| x.uuid.in? my_project_uuids }
598 helper_method :recent_jobs_and_pipelines
599 def recent_jobs_and_pipelines
601 PipelineInstance.limit(10)).
603 x.finished_at || x.started_at || x.created_at rescue x.created_at
607 helper_method :my_project_tree
613 helper_method :shared_project_tree
614 def shared_project_tree
619 def build_project_trees
620 return if @my_project_tree and @shared_project_tree
621 parent_of = {current_user.uuid => 'me'}
622 all_projects.each do |ob|
623 parent_of[ob.uuid] = ob.owner_uuid
625 children_of = {false => [], 'me' => [current_user]}
626 all_projects.each do |ob|
627 if ob.owner_uuid != current_user.uuid and
628 not parent_of.has_key? ob.owner_uuid
629 parent_of[ob.uuid] = false
631 children_of[parent_of[ob.uuid]] ||= []
632 children_of[parent_of[ob.uuid]] << ob
634 buildtree = lambda do |children_of, root_uuid=false|
636 children_of[root_uuid].andand.each do |ob|
637 tree[ob] = buildtree.call(children_of, ob.uuid)
641 sorted_paths = lambda do |tree, depth=0|
643 tree.keys.sort_by { |ob|
644 ob.is_a?(String) ? ob : ob.friendly_link_name
646 paths << {object: ob, depth: depth}
647 paths += sorted_paths.call tree[ob], depth+1
652 sorted_paths.call buildtree.call(children_of, 'me')
653 @shared_project_tree =
654 sorted_paths.call({'Shared with me' =>
655 buildtree.call(children_of, false)})
658 helper_method :get_object
660 if @get_object.nil? and @objects
661 @get_object = @objects.each_with_object({}) do |object, h|
662 h[object.uuid] = object
669 helper_method :project_breadcrumbs
670 def project_breadcrumbs
672 current = @name_link || @object
674 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
675 crumbs.prepend current
677 if current.is_a? Link
678 current = Group.find?(current.tail_uuid)
680 current = Group.find?(current.owner_uuid)
686 helper_method :current_project_uuid
687 def current_project_uuid
688 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
690 elsif @name_link.andand.tail_uuid
692 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
699 # helper method to get links for given object or uuid
700 helper_method :links_for_object
701 def links_for_object object_or_uuid
702 raise ArgumentError, 'No input argument' unless object_or_uuid
703 preload_links_for_objects([object_or_uuid])
704 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
705 @all_links_for[uuid] ||= []
708 # helper method to preload links for given objects and uuids
709 helper_method :preload_links_for_objects
710 def preload_links_for_objects objects_and_uuids
711 @all_links_for ||= {}
713 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
714 return @all_links_for if objects_and_uuids.empty?
716 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
718 # if already preloaded for all of these uuids, return
719 if not uuids.select { |x| @all_links_for[x].nil? }.any?
720 return @all_links_for
724 @all_links_for[x] = []
727 # TODO: make sure we get every page of results from API server
728 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
729 @all_links_for[link.head_uuid] << link
734 # helper method to get a certain number of objects of a specific type
735 # this can be used to replace any uses of: "dataclass.limit(n)"
736 helper_method :get_n_objects_of_class
737 def get_n_objects_of_class dataclass, size
738 @objects_map_for ||= {}
740 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
741 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
743 # if the objects_map_for has a value for this dataclass, and the
744 # size used to retrieve those objects is equal, return it
745 size_key = "#{dataclass.name}_size"
746 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
747 (@objects_map_for[size_key] == size)
748 return @objects_map_for[dataclass.name]
751 @objects_map_for[size_key] = size
752 @objects_map_for[dataclass.name] = dataclass.limit(size)
755 # helper method to get collections for the given uuid
756 helper_method :collections_for_object
757 def collections_for_object uuid
758 raise ArgumentError, 'No input argument' unless uuid
759 preload_collections_for_objects([uuid])
760 @all_collections_for[uuid] ||= []
763 # helper method to preload collections for the given uuids
764 helper_method :preload_collections_for_objects
765 def preload_collections_for_objects uuids
766 @all_collections_for ||= {}
768 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
769 return @all_collections_for if uuids.empty?
771 # if already preloaded for all of these uuids, return
772 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
773 return @all_collections_for
777 @all_collections_for[x] = []
780 # TODO: make sure we get every page of results from API server
781 Collection.where(uuid: uuids).each do |collection|
782 @all_collections_for[collection.uuid] << collection
787 # helper method to get log collections for the given log
788 helper_method :log_collections_for_object
789 def log_collections_for_object log
790 raise ArgumentError, 'No input argument' unless log
792 preload_log_collections_for_objects([log])
795 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
796 if fixup && fixup.size>1
800 @all_log_collections_for[uuid] ||= []
803 # helper method to preload collections for the given uuids
804 helper_method :preload_log_collections_for_objects
805 def preload_log_collections_for_objects logs
806 @all_log_collections_for ||= {}
808 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
809 return @all_log_collections_for if logs.empty?
813 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
814 if fixup && fixup.size>1
821 # if already preloaded for all of these uuids, return
822 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
823 return @all_log_collections_for
827 @all_log_collections_for[x] = []
830 # TODO: make sure we get every page of results from API server
831 Collection.where(uuid: uuids).each do |collection|
832 @all_log_collections_for[collection.uuid] << collection
834 @all_log_collections_for
837 # helper method to get object of a given dataclass and uuid
838 helper_method :object_for_dataclass
839 def object_for_dataclass dataclass, uuid
840 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
841 preload_objects_for_dataclass(dataclass, [uuid])
845 # helper method to preload objects for given dataclass and uuids
846 helper_method :preload_objects_for_dataclass
847 def preload_objects_for_dataclass dataclass, uuids
850 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
851 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
853 return @objects_for if uuids.empty?
855 # if already preloaded for all of these uuids, return
856 if not uuids.select { |x| @objects_for[x].nil? }.any?
860 dataclass.where(uuid: uuids).each do |obj|
861 @objects_for[obj.uuid] = obj