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] + 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] ||= 20
149 find_objects_for_index if !@objects
154 content: render_to_string(partial: "choose_rows.html",
157 multiple: params[:multiple]
159 next_page_href: @next_page_href
164 render partial: 'choose', locals: {multiple: params[:multiple]}
171 return render_not_found("object not found")
176 @object = model_class.new
180 @updates ||= params[@object.resource_param_name.to_sym]
181 @updates.keys.each do |attr|
182 if @object.send(attr).is_a? Hash
183 if @updates[attr].is_a? String
184 @updates[attr] = Oj.load @updates[attr]
186 if params[:merge] || params["merge_#{attr}".to_sym]
187 # Merge provided Hash with current Hash, instead of
189 @updates[attr] = @object.send(attr).with_indifferent_access.
190 deep_merge(@updates[attr].with_indifferent_access)
194 if @object.update_attributes @updates
197 self.render_error status: 422
202 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
203 @new_resource_attrs ||= {}
204 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
205 @object ||= model_class.new @new_resource_attrs, params["options"]
208 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
215 self.render_error status: 422
219 # Clone the given object, merging any attribute values supplied as
220 # with a create action.
222 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
223 @new_resource_attrs ||= {}
224 @object = @object.dup
225 @object.update_attributes @new_resource_attrs
226 if not @new_resource_attrs[:name] and @object.respond_to? :name
227 if @object.name and @object.name != ''
228 @object.name = "Copy of #{@object.name}"
230 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
240 f.json { render json: @object }
242 redirect_to(params[:return_to] || :back)
247 self.render_error status: 422
252 return Thread.current[:user] if Thread.current[:user]
254 if Thread.current[:arvados_api_token]
256 if session[:user][:is_active] != true
257 Thread.current[:user] = User.current
259 Thread.current[:user] = User.new(session[:user])
262 Thread.current[:user] = User.current
265 logger.error "No API token in Thread"
271 controller_name.classify.constantize
274 def breadcrumb_page_name
275 (@breadcrumb_page_name ||
276 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
285 %w(Attributes Advanced)
290 def redirect_to_login
293 if request.method.in? ['GET', 'HEAD']
294 redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
296 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."
301 @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.']
302 self.render_error status: 422
305 false # For convenience to return from callbacks
308 def using_specific_api_token(api_token)
310 [:arvados_api_token, :user].each do |key|
311 start_values[key] = Thread.current[key]
313 Thread.current[:arvados_api_token] = api_token
314 Thread.current[:user] = nil
318 start_values.each_key { |key| Thread.current[key] = start_values[key] }
322 def find_object_by_uuid
323 if params[:id] and params[:id].match /\D/
324 params[:uuid] = params.delete :id
328 elsif params[:uuid].is_a? String
329 if params[:uuid].empty?
332 if (model_class != Link and
333 resource_class_for_uuid(params[:uuid]) == Link)
334 @name_link = Link.find(params[:uuid])
335 @object = model_class.find(@name_link.head_uuid)
337 @object = model_class.find(params[:uuid])
341 @object = model_class.where(uuid: params[:uuid]).first
346 Thread.current[:arvados_api_token] = nil
347 Thread.current[:user] = nil
348 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
350 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
353 def thread_with_api_token(login_optional = false)
355 try_redirect_to_login = true
356 if params[:api_token]
357 try_redirect_to_login = false
358 Thread.current[:arvados_api_token] = params[:api_token]
359 # Before copying the token into session[], do a simple API
360 # call to verify its authenticity.
362 session[:arvados_api_token] = params[:api_token]
367 first_name: u.first_name,
368 last_name: u.last_name,
369 is_active: u.is_active,
370 is_admin: u.is_admin,
373 if !request.format.json? and request.method.in? ['GET', 'HEAD']
374 # Repeat this request with api_token in the (new) session
375 # cookie instead of the query string. This prevents API
376 # tokens from appearing in (and being inadvisedly copied
377 # and pasted from) browser Location bars.
378 redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
383 @errors = ['Invalid API token']
384 self.render_error status: 401
386 elsif session[:arvados_api_token]
387 # In this case, the token must have already verified at some
388 # point, but it might have been revoked since. We'll try
389 # using it, and catch the exception if it doesn't work.
390 try_redirect_to_login = false
391 Thread.current[:arvados_api_token] = session[:arvados_api_token]
394 rescue ArvadosApiClient::NotLoggedInException
395 try_redirect_to_login = true
398 logger.debug "No token received, session is #{session.inspect}"
400 if try_redirect_to_login
401 unless login_optional
404 # login is optional for this route so go on to the regular controller
405 Thread.current[:arvados_api_token] = nil
410 # Remove token in case this Thread is used for anything else.
411 Thread.current[:arvados_api_token] = nil
415 def thread_with_mandatory_api_token
416 thread_with_api_token(true) do
417 if Thread.current[:arvados_api_token]
419 elsif session[:arvados_api_token]
420 # Expired session. Clear it before refreshing login so that,
421 # if this login procedure fails, we end up showing the "please
422 # log in" page instead of getting stuck in a redirect loop.
423 session.delete :arvados_api_token
426 render 'users/welcome'
431 # This runs after thread_with_mandatory_api_token in the filter chain.
432 def thread_with_optional_api_token
433 if Thread.current[:arvados_api_token]
434 # We are already inside thread_with_mandatory_api_token.
437 # We skipped thread_with_mandatory_api_token. Use the optional version.
438 thread_with_api_token(true) do
446 Link.where(uuid: 'just-verifying-my-api-token')
448 rescue ArvadosApiClient::NotLoggedInException
453 def ensure_current_user_is_admin
454 unless current_user and current_user.is_admin
455 @errors = ['Permission denied']
456 self.render_error status: 401
460 def check_user_agreements
461 if current_user && !current_user.is_active
462 if not current_user.is_invited
463 return render 'users/inactive'
465 signatures = UserAgreement.signatures
466 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
467 @required_user_agreements = UserAgreement.all.map do |ua|
468 if not @signed_ua_uuids.index ua.uuid
469 Collection.find(ua.uuid)
472 if @required_user_agreements.empty?
473 # No agreements to sign. Perhaps we just need to ask?
474 current_user.activate
475 if !current_user.is_active
476 logger.warn "#{current_user.uuid.inspect}: " +
477 "No user agreements to sign, but activate failed!"
480 if !current_user.is_active
481 render 'user_agreements/index'
488 return Rails.configuration.arvados_theme
491 @@notification_tests = []
493 @@notification_tests.push lambda { |controller, current_user|
494 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
497 return lambda { |view|
498 view.render partial: 'notifications/ssh_key_notification'
502 #@@notification_tests.push lambda { |controller, current_user|
503 # Job.limit(1).where(created_by: current_user.uuid).each do
506 # return lambda { |view|
507 # view.render partial: 'notifications/jobs_notification'
511 @@notification_tests.push lambda { |controller, current_user|
512 Collection.limit(1).where(created_by: current_user.uuid).each do
515 return lambda { |view|
516 view.render partial: 'notifications/collections_notification'
520 @@notification_tests.push lambda { |controller, current_user|
521 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
524 return lambda { |view|
525 view.render partial: 'notifications/pipelines_notification'
529 def check_user_notifications
530 return if params['tab_pane']
532 @notification_count = 0
536 @showallalerts = false
537 @@notification_tests.each do |t|
538 a = t.call(self, current_user)
540 @notification_count += 1
541 @notifications.push a
546 if @notification_count == 0
547 @notification_count = ''
551 helper_method :all_projects
553 @all_projects ||= Group.
554 filter([['group_class','in',['project','folder']]]).order('name')
557 helper_method :my_projects
559 return @my_projects if @my_projects
562 all_projects.each do |g|
563 root_of[g.uuid] = g.owner_uuid
569 root_of = root_of.each_with_object({}) do |(child, parent), h|
571 h[child] = root_of[parent]
578 @my_projects = @my_projects.select do |g|
579 root_of[g.uuid] == current_user.uuid
583 helper_method :projects_shared_with_me
584 def projects_shared_with_me
585 my_project_uuids = my_projects.collect &:uuid
586 all_projects.reject { |x| x.uuid.in? my_project_uuids }
589 helper_method :recent_jobs_and_pipelines
590 def recent_jobs_and_pipelines
592 PipelineInstance.limit(10)).
594 x.finished_at || x.started_at || x.created_at rescue x.created_at
598 helper_method :my_project_tree
604 helper_method :shared_project_tree
605 def shared_project_tree
610 def build_project_trees
611 return if @my_project_tree and @shared_project_tree
612 parent_of = {current_user.uuid => 'me'}
613 all_projects.each do |ob|
614 parent_of[ob.uuid] = ob.owner_uuid
616 children_of = {false => [], 'me' => [current_user]}
617 all_projects.each do |ob|
618 if ob.owner_uuid != current_user.uuid and
619 not parent_of.has_key? ob.owner_uuid
620 parent_of[ob.uuid] = false
622 children_of[parent_of[ob.uuid]] ||= []
623 children_of[parent_of[ob.uuid]] << ob
625 buildtree = lambda do |children_of, root_uuid=false|
627 children_of[root_uuid].andand.each do |ob|
628 tree[ob] = buildtree.call(children_of, ob.uuid)
632 sorted_paths = lambda do |tree, depth=0|
634 tree.keys.sort_by { |ob|
635 ob.is_a?(String) ? ob : ob.friendly_link_name
637 paths << {object: ob, depth: depth}
638 paths += sorted_paths.call tree[ob], depth+1
643 sorted_paths.call buildtree.call(children_of, 'me')
644 @shared_project_tree =
645 sorted_paths.call({'Shared with me' =>
646 buildtree.call(children_of, false)})
649 helper_method :get_object
651 if @get_object.nil? and @objects
652 @get_object = @objects.each_with_object({}) do |object, h|
653 h[object.uuid] = object
660 helper_method :project_breadcrumbs
661 def project_breadcrumbs
663 current = @name_link || @object
665 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
666 crumbs.prepend current
668 if current.is_a? Link
669 current = Group.find?(current.tail_uuid)
671 current = Group.find?(current.owner_uuid)
677 helper_method :current_project_uuid
678 def current_project_uuid
679 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
681 elsif @name_link.andand.tail_uuid
683 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
690 # helper method to get links for given object or uuid
691 helper_method :links_for_object
692 def links_for_object object_or_uuid
693 raise ArgumentError, 'No input argument' unless object_or_uuid
694 preload_links_for_objects([object_or_uuid])
695 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
696 @all_links_for[uuid] ||= []
699 # helper method to preload links for given objects and uuids
700 helper_method :preload_links_for_objects
701 def preload_links_for_objects objects_and_uuids
702 @all_links_for ||= {}
704 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
705 return @all_links_for if objects_and_uuids.empty?
707 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
709 # if already preloaded for all of these uuids, return
710 if not uuids.select { |x| @all_links_for[x].nil? }.any?
711 return @all_links_for
715 @all_links_for[x] = []
718 # TODO: make sure we get every page of results from API server
719 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
720 @all_links_for[link.head_uuid] << link
725 # helper method to get a certain number of objects of a specific type
726 # this can be used to replace any uses of: "dataclass.limit(n)"
727 helper_method :get_n_objects_of_class
728 def get_n_objects_of_class dataclass, size
729 @objects_map_for ||= {}
731 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
732 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
734 # if the objects_map_for has a value for this dataclass, and the
735 # size used to retrieve those objects is equal, return it
736 size_key = "#{dataclass.name}_size"
737 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
738 (@objects_map_for[size_key] == size)
739 return @objects_map_for[dataclass.name]
742 @objects_map_for[size_key] = size
743 @objects_map_for[dataclass.name] = dataclass.limit(size)
746 # helper method to get collections for the given uuid
747 helper_method :collections_for_object
748 def collections_for_object uuid
749 raise ArgumentError, 'No input argument' unless uuid
750 preload_collections_for_objects([uuid])
751 @all_collections_for[uuid] ||= []
754 # helper method to preload collections for the given uuids
755 helper_method :preload_collections_for_objects
756 def preload_collections_for_objects uuids
757 @all_collections_for ||= {}
759 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
760 return @all_collections_for if uuids.empty?
762 # if already preloaded for all of these uuids, return
763 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
764 return @all_collections_for
768 @all_collections_for[x] = []
771 # TODO: make sure we get every page of results from API server
772 Collection.where(uuid: uuids).each do |collection|
773 @all_collections_for[collection.uuid] << collection
778 # helper method to get log collections for the given log
779 helper_method :log_collections_for_object
780 def log_collections_for_object log
781 raise ArgumentError, 'No input argument' unless log
783 preload_log_collections_for_objects([log])
786 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
787 if fixup && fixup.size>1
791 @all_log_collections_for[uuid] ||= []
794 # helper method to preload collections for the given uuids
795 helper_method :preload_log_collections_for_objects
796 def preload_log_collections_for_objects logs
797 @all_log_collections_for ||= {}
799 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
800 return @all_log_collections_for if logs.empty?
804 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
805 if fixup && fixup.size>1
812 # if already preloaded for all of these uuids, return
813 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
814 return @all_log_collections_for
818 @all_log_collections_for[x] = []
821 # TODO: make sure we get every page of results from API server
822 Collection.where(uuid: uuids).each do |collection|
823 @all_log_collections_for[collection.uuid] << collection
825 @all_log_collections_for
828 # helper method to get object of a given dataclass and uuid
829 helper_method :object_for_dataclass
830 def object_for_dataclass dataclass, uuid
831 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
832 preload_objects_for_dataclass(dataclass, [uuid])
836 # helper method to preload objects for given dataclass and uuids
837 helper_method :preload_objects_for_dataclass
838 def preload_objects_for_dataclass dataclass, uuids
841 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
842 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
844 return @objects_for if uuids.empty?
846 # if already preloaded for all of these uuids, return
847 if not uuids.select { |x| @objects_for[x].nil? }.any?
851 dataclass.where(uuid: uuids).each do |obj|
852 @objects_for[obj.uuid] = obj