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 e.is_a? ArvadosApiClient::NotLoggedInException
63 prep_token = :thread_clear
65 prep_token = :set_thread_api_token
68 render_error(err_opts)
72 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
73 logger.error e.inspect
74 @errors = ["Path not found"]
75 set_thread_api_token do
76 self.render_error(action: '404', status: 404)
80 def find_objects_for_index
83 @limit = params[:limit].to_i
88 @offset = params[:offset].to_i
93 filters = params[:filters]
94 if filters.is_a? String
95 filters = Oj.load filters
100 @objects ||= model_class
101 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
106 f.json { render json: @objects }
108 if params['tab_pane']
109 comparable = self.respond_to? :compare
110 render(partial: 'show_' + params['tab_pane'].downcase,
111 locals: { comparable: comparable, objects: @objects })
121 find_objects_for_index if !@objects
125 helper_method :next_page_offset
127 if @objects.respond_to?(:result_offset) and
128 @objects.respond_to?(:result_limit) and
129 @objects.respond_to?(:items_available)
130 next_offset = @objects.result_offset + @objects.result_limit
131 if next_offset < @objects.items_available
141 return render_not_found("object not found")
144 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
146 if params['tab_pane']
147 comparable = self.respond_to? :compare
148 render(partial: 'show_' + params['tab_pane'].downcase,
149 locals: { comparable: comparable, objects: @objects })
150 elsif request.method.in? ['GET', 'HEAD']
153 redirect_to params[:return_to] || @object
161 params[:limit] ||= 40
163 if params[:project_uuid] and !params[:project_uuid].empty?
164 # We want the chooser to show objects of the controllers's model_class
165 # type within a specific project specified by project_uuid, so fetch the
166 # project and request the contents of the project filtered on the
167 # controllers's model_class kind.
168 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
170 find_objects_for_index if !@objects
176 content: render_to_string(partial: "choose_rows.html",
179 multiple: params[:multiple]
181 next_page_href: @next_page_href
186 render partial: 'choose', locals: {multiple: params[:multiple]}
193 return render_not_found("object not found")
198 @object = model_class.new
202 @updates ||= params[@object.resource_param_name.to_sym]
203 @updates.keys.each do |attr|
204 if @object.send(attr).is_a? Hash
205 if @updates[attr].is_a? String
206 @updates[attr] = Oj.load @updates[attr]
208 if params[:merge] || params["merge_#{attr}".to_sym]
209 # Merge provided Hash with current Hash, instead of
211 @updates[attr] = @object.send(attr).with_indifferent_access.
212 deep_merge(@updates[attr].with_indifferent_access)
216 if @object.update_attributes @updates
219 self.render_error status: 422
224 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
225 @new_resource_attrs ||= {}
226 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
227 @object ||= model_class.new @new_resource_attrs, params["options"]
230 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
237 self.render_error status: 422
241 # Clone the given object, merging any attribute values supplied as
242 # with a create action.
244 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
245 @new_resource_attrs ||= {}
246 @object = @object.dup
247 @object.update_attributes @new_resource_attrs
248 if not @new_resource_attrs[:name] and @object.respond_to? :name
249 if @object.name and @object.name != ''
250 @object.name = "Copy of #{@object.name}"
252 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
262 f.json { render json: @object }
264 redirect_to(params[:return_to] || :back)
269 self.render_error status: 422
274 return Thread.current[:user] if Thread.current[:user]
276 if User.columns.empty?
277 # We can't even get the discovery document from the API server.
278 # We're not going to be able to instantiate any user object.
280 elsif Thread.current[:arvados_api_token]
282 if session[:user][:is_active] != true
283 Thread.current[:user] = User.current
285 Thread.current[:user] = User.new(session[:user])
288 Thread.current[:user] = User.current
291 logger.error "No API token in Thread"
297 controller_name.classify.constantize
300 def breadcrumb_page_name
301 (@breadcrumb_page_name ||
302 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
311 %w(Attributes Advanced)
316 def strip_token_from_path(path)
317 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
320 def redirect_to_login
323 if request.method.in? ['GET', 'HEAD']
324 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
326 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."
331 @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.']
332 self.render_error status: 422
335 false # For convenience to return from callbacks
338 def using_specific_api_token(api_token)
340 [:arvados_api_token, :user].each do |key|
341 start_values[key] = Thread.current[key]
343 Thread.current[:arvados_api_token] = api_token
344 Thread.current[:user] = nil
348 start_values.each_key { |key| Thread.current[key] = start_values[key] }
352 def find_object_by_uuid
353 if params[:id] and params[:id].match /\D/
354 params[:uuid] = params.delete :id
359 elsif not params[:uuid].is_a?(String)
360 @object = model_class.where(uuid: params[:uuid]).first
361 elsif params[:uuid].empty?
363 elsif (model_class != Link and
364 resource_class_for_uuid(params[:uuid]) == Link)
365 @name_link = Link.find(params[:uuid])
366 @object = model_class.find(@name_link.head_uuid)
368 @object = model_class.find(params[:uuid])
370 rescue ArvadosApiClient::NotFoundException => error
371 render_not_found(error)
377 Thread.current[:arvados_api_token] = nil
378 Thread.current[:user] = nil
379 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
381 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
384 # Save the session API token in thread-local storage, and yield.
385 # This method also takes care of session setup if the request
386 # provides a valid api_token parameter.
387 # If a token is unavailable or expired, the block is still run, with
389 def set_thread_api_token
390 # If an API token has already been found, pass it through.
391 if Thread.current[:arvados_api_token]
397 # If there's a valid api_token parameter, use it to set up the session.
398 if (Thread.current[:arvados_api_token] = params[:api_token]) and
400 session[:arvados_api_token] = params[:api_token]
405 first_name: u.first_name,
406 last_name: u.last_name,
407 is_active: u.is_active,
408 is_admin: u.is_admin,
411 if !request.format.json? and request.method.in? ['GET', 'HEAD']
412 # Repeat this request with api_token in the (new) session
413 # cookie instead of the query string. This prevents API
414 # tokens from appearing in (and being inadvisedly copied
415 # and pasted from) browser Location bars.
416 redirect_to strip_token_from_path(request.fullpath)
421 # With setup done, handle the request using the session token.
422 Thread.current[:arvados_api_token] = session[:arvados_api_token]
425 rescue ArvadosApiClient::NotLoggedInException
426 # If we got this error with a token, it must've expired.
427 # Retry the request without a token.
428 unless Thread.current[:arvados_api_token].nil?
429 Thread.current[:arvados_api_token] = nil
434 # Remove token in case this Thread is used for anything else.
435 Thread.current[:arvados_api_token] = nil
439 # Reroute this request if an API token is unavailable.
440 def require_thread_api_token
441 if Thread.current[:arvados_api_token]
443 elsif session[:arvados_api_token]
444 # Expired session. Clear it before refreshing login so that,
445 # if this login procedure fails, we end up showing the "please
446 # log in" page instead of getting stuck in a redirect loop.
447 session.delete :arvados_api_token
450 render 'users/welcome'
456 Link.where(uuid: 'just-verifying-my-api-token')
458 rescue ArvadosApiClient::NotLoggedInException
463 def ensure_current_user_is_admin
464 unless current_user and current_user.is_admin
465 @errors = ['Permission denied']
466 self.render_error status: 401
470 def check_user_agreements
471 if current_user && !current_user.is_active
472 if not current_user.is_invited
473 return render 'users/inactive'
475 signatures = UserAgreement.signatures
476 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
477 @required_user_agreements = UserAgreement.all.map do |ua|
478 if not @signed_ua_uuids.index ua.uuid
479 Collection.find(ua.uuid)
482 if @required_user_agreements.empty?
483 # No agreements to sign. Perhaps we just need to ask?
484 current_user.activate
485 if !current_user.is_active
486 logger.warn "#{current_user.uuid.inspect}: " +
487 "No user agreements to sign, but activate failed!"
490 if !current_user.is_active
491 render 'user_agreements/index'
498 return Rails.configuration.arvados_theme
501 @@notification_tests = []
503 @@notification_tests.push lambda { |controller, current_user|
504 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
507 return lambda { |view|
508 view.render partial: 'notifications/ssh_key_notification'
512 #@@notification_tests.push lambda { |controller, current_user|
513 # Job.limit(1).where(created_by: current_user.uuid).each do
516 # return lambda { |view|
517 # view.render partial: 'notifications/jobs_notification'
521 @@notification_tests.push lambda { |controller, current_user|
522 Collection.limit(1).where(created_by: current_user.uuid).each do
525 return lambda { |view|
526 view.render partial: 'notifications/collections_notification'
530 @@notification_tests.push lambda { |controller, current_user|
531 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
534 return lambda { |view|
535 view.render partial: 'notifications/pipelines_notification'
539 def check_user_notifications
540 return if params['tab_pane']
542 @notification_count = 0
546 @showallalerts = false
547 @@notification_tests.each do |t|
548 a = t.call(self, current_user)
550 @notification_count += 1
551 @notifications.push a
556 if @notification_count == 0
557 @notification_count = ''
561 helper_method :all_projects
563 @all_projects ||= Group.
564 filter([['group_class','in',['project','folder']]]).order('name')
567 helper_method :my_projects
569 return @my_projects if @my_projects
572 all_projects.each do |g|
573 root_of[g.uuid] = g.owner_uuid
579 root_of = root_of.each_with_object({}) do |(child, parent), h|
581 h[child] = root_of[parent]
588 @my_projects = @my_projects.select do |g|
589 root_of[g.uuid] == current_user.uuid
593 helper_method :projects_shared_with_me
594 def projects_shared_with_me
595 my_project_uuids = my_projects.collect &:uuid
596 all_projects.reject { |x| x.uuid.in? my_project_uuids }
599 helper_method :recent_jobs_and_pipelines
600 def recent_jobs_and_pipelines
602 PipelineInstance.limit(10)).
604 x.finished_at || x.started_at || x.created_at rescue x.created_at
608 helper_method :my_project_tree
614 helper_method :shared_project_tree
615 def shared_project_tree
620 def build_project_trees
621 return if @my_project_tree and @shared_project_tree
622 parent_of = {current_user.uuid => 'me'}
623 all_projects.each do |ob|
624 parent_of[ob.uuid] = ob.owner_uuid
626 children_of = {false => [], 'me' => [current_user]}
627 all_projects.each do |ob|
628 if ob.owner_uuid != current_user.uuid and
629 not parent_of.has_key? ob.owner_uuid
630 parent_of[ob.uuid] = false
632 children_of[parent_of[ob.uuid]] ||= []
633 children_of[parent_of[ob.uuid]] << ob
635 buildtree = lambda do |children_of, root_uuid=false|
637 children_of[root_uuid].andand.each do |ob|
638 tree[ob] = buildtree.call(children_of, ob.uuid)
642 sorted_paths = lambda do |tree, depth=0|
644 tree.keys.sort_by { |ob|
645 ob.is_a?(String) ? ob : ob.friendly_link_name
647 paths << {object: ob, depth: depth}
648 paths += sorted_paths.call tree[ob], depth+1
653 sorted_paths.call buildtree.call(children_of, 'me')
654 @shared_project_tree =
655 sorted_paths.call({'Shared with me' =>
656 buildtree.call(children_of, false)})
659 helper_method :get_object
661 if @get_object.nil? and @objects
662 @get_object = @objects.each_with_object({}) do |object, h|
663 h[object.uuid] = object
670 helper_method :project_breadcrumbs
671 def project_breadcrumbs
673 current = @name_link || @object
675 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
676 crumbs.prepend current
678 if current.is_a? Link
679 current = Group.find?(current.tail_uuid)
681 current = Group.find?(current.owner_uuid)
687 helper_method :current_project_uuid
688 def current_project_uuid
689 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
691 elsif @name_link.andand.tail_uuid
693 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
700 # helper method to get links for given object or uuid
701 helper_method :links_for_object
702 def links_for_object object_or_uuid
703 raise ArgumentError, 'No input argument' unless object_or_uuid
704 preload_links_for_objects([object_or_uuid])
705 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
706 @all_links_for[uuid] ||= []
709 # helper method to preload links for given objects and uuids
710 helper_method :preload_links_for_objects
711 def preload_links_for_objects objects_and_uuids
712 @all_links_for ||= {}
714 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
715 return @all_links_for if objects_and_uuids.empty?
717 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
719 # if already preloaded for all of these uuids, return
720 if not uuids.select { |x| @all_links_for[x].nil? }.any?
721 return @all_links_for
725 @all_links_for[x] = []
728 # TODO: make sure we get every page of results from API server
729 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
730 @all_links_for[link.head_uuid] << link
735 # helper method to get a certain number of objects of a specific type
736 # this can be used to replace any uses of: "dataclass.limit(n)"
737 helper_method :get_n_objects_of_class
738 def get_n_objects_of_class dataclass, size
739 @objects_map_for ||= {}
741 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
742 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
744 # if the objects_map_for has a value for this dataclass, and the
745 # size used to retrieve those objects is equal, return it
746 size_key = "#{dataclass.name}_size"
747 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
748 (@objects_map_for[size_key] == size)
749 return @objects_map_for[dataclass.name]
752 @objects_map_for[size_key] = size
753 @objects_map_for[dataclass.name] = dataclass.limit(size)
756 # helper method to get collections for the given uuid
757 helper_method :collections_for_object
758 def collections_for_object uuid
759 raise ArgumentError, 'No input argument' unless uuid
760 preload_collections_for_objects([uuid])
761 @all_collections_for[uuid] ||= []
764 # helper method to preload collections for the given uuids
765 helper_method :preload_collections_for_objects
766 def preload_collections_for_objects uuids
767 @all_collections_for ||= {}
769 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
770 return @all_collections_for if uuids.empty?
772 # if already preloaded for all of these uuids, return
773 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
774 return @all_collections_for
778 @all_collections_for[x] = []
781 # TODO: make sure we get every page of results from API server
782 Collection.where(uuid: uuids).each do |collection|
783 @all_collections_for[collection.uuid] << collection
788 # helper method to get log collections for the given log
789 helper_method :log_collections_for_object
790 def log_collections_for_object log
791 raise ArgumentError, 'No input argument' unless log
793 preload_log_collections_for_objects([log])
796 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
797 if fixup && fixup.size>1
801 @all_log_collections_for[uuid] ||= []
804 # helper method to preload collections for the given uuids
805 helper_method :preload_log_collections_for_objects
806 def preload_log_collections_for_objects logs
807 @all_log_collections_for ||= {}
809 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
810 return @all_log_collections_for if logs.empty?
814 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
815 if fixup && fixup.size>1
822 # if already preloaded for all of these uuids, return
823 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
824 return @all_log_collections_for
828 @all_log_collections_for[x] = []
831 # TODO: make sure we get every page of results from API server
832 Collection.where(uuid: uuids).each do |collection|
833 @all_log_collections_for[collection.uuid] << collection
835 @all_log_collections_for
838 # helper method to get object of a given dataclass and uuid
839 helper_method :object_for_dataclass
840 def object_for_dataclass dataclass, uuid
841 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
842 preload_objects_for_dataclass(dataclass, [uuid])
846 # helper method to preload objects for given dataclass and uuids
847 helper_method :preload_objects_for_dataclass
848 def preload_objects_for_dataclass dataclass, uuids
851 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
852 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
854 return @objects_for if uuids.empty?
856 # if already preloaded for all of these uuids, return
857 if not uuids.select { |x| @objects_for[x].nil? }.any?
861 dataclass.where(uuid: uuids).each do |obj|
862 @objects_for[obj.uuid] = obj