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_api_token
12 around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
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(ActiveRecord::RecordNotFound,
20 ActionController::RoutingError,
21 ActionController::UnknownController,
22 AbstractController::ActionNotFound,
23 with: :render_not_found)
24 rescue_from(Exception,
25 ActionController::UrlGenerationError,
26 with: :render_exception)
29 def unprocessable(message=nil)
32 @errors << message if message
33 render_error status: 422
36 def render_error(opts)
37 opts = {status: 500}.merge opts
39 # json must come before html here, so it gets used as the
40 # default format when js is requested by the client. This lets
41 # ajax:error callback parse the response correctly, even though
43 f.json { render opts.merge(json: {success: false, errors: @errors}) }
44 f.html { render opts.merge(controller: 'application', action: 'error') }
48 def render_exception(e)
49 logger.error e.inspect
50 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
51 if @object.andand.errors.andand.full_messages.andand.any?
52 @errors = @object.errors.full_messages
56 if e.is_a? ArvadosApiClient::NotLoggedInException
57 self.render_error status: 422
59 thread_with_api_token do
60 self.render_error status: 422
65 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
66 logger.error e.inspect
67 @errors = ["Path not found"]
68 thread_with_api_token do
69 self.render_error status: 404
73 def find_objects_for_index
76 @limit = params[:limit].to_i
81 @offset = params[:offset].to_i
86 filters = params[:filters]
87 if filters.is_a? String
88 filters = Oj.load filters
93 @objects ||= model_class
94 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
99 f.json { render json: @objects }
101 if params['tab_pane']
102 comparable = self.respond_to? :compare
103 render(partial: 'show_' + params['tab_pane'].downcase,
104 locals: { comparable: comparable, objects: @objects })
114 find_objects_for_index if !@objects
118 helper_method :next_page_offset
120 if @objects.respond_to?(:result_offset) and
121 @objects.respond_to?(:result_limit) and
122 @objects.respond_to?(:items_available)
123 next_offset = @objects.result_offset + @objects.result_limit
124 if next_offset < @objects.items_available
134 return render_not_found("object not found")
137 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
139 if params['tab_pane']
140 comparable = self.respond_to? :compare
141 render(partial: 'show_' + params['tab_pane'].downcase,
142 locals: { comparable: comparable, objects: @objects })
143 elsif request.method.in? ['GET', 'HEAD']
146 redirect_to params[:return_to] || @object
154 params[:limit] ||= 40
156 if params[:project_uuid] and !params[:project_uuid].empty?
157 # We want the chooser to show objects of the controllers's model_class
158 # type within a specific project specified by project_uuid, so fetch the
159 # project and request the contents of the project filtered on the
160 # controllers's model_class kind.
161 @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
163 find_objects_for_index if !@objects
169 content: render_to_string(partial: "choose_rows.html",
172 multiple: params[:multiple]
174 next_page_href: @next_page_href
179 render partial: 'choose', locals: {multiple: params[:multiple]}
186 return render_not_found("object not found")
191 @object = model_class.new
195 @updates ||= params[@object.resource_param_name.to_sym]
196 @updates.keys.each do |attr|
197 if @object.send(attr).is_a? Hash
198 if @updates[attr].is_a? String
199 @updates[attr] = Oj.load @updates[attr]
201 if params[:merge] || params["merge_#{attr}".to_sym]
202 # Merge provided Hash with current Hash, instead of
204 @updates[attr] = @object.send(attr).with_indifferent_access.
205 deep_merge(@updates[attr].with_indifferent_access)
209 if @object.update_attributes @updates
212 self.render_error status: 422
217 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
218 @new_resource_attrs ||= {}
219 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
220 @object ||= model_class.new @new_resource_attrs, params["options"]
223 f.json { render json: @object.attributes.merge(href: url_for(@object)) }
230 self.render_error status: 422
234 # Clone the given object, merging any attribute values supplied as
235 # with a create action.
237 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
238 @new_resource_attrs ||= {}
239 @object = @object.dup
240 @object.update_attributes @new_resource_attrs
241 if not @new_resource_attrs[:name] and @object.respond_to? :name
242 if @object.name and @object.name != ''
243 @object.name = "Copy of #{@object.name}"
245 @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
255 f.json { render json: @object }
257 redirect_to(params[:return_to] || :back)
262 self.render_error status: 422
267 return Thread.current[:user] if Thread.current[:user]
269 if Thread.current[:arvados_api_token]
271 if session[:user][:is_active] != true
272 Thread.current[:user] = User.current
274 Thread.current[:user] = User.new(session[:user])
277 Thread.current[:user] = User.current
280 logger.error "No API token in Thread"
286 controller_name.classify.constantize
289 def breadcrumb_page_name
290 (@breadcrumb_page_name ||
291 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
300 %w(Attributes Advanced)
305 def strip_token_from_path(path)
306 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
309 def redirect_to_login
312 if request.method.in? ['GET', 'HEAD']
313 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
315 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."
320 @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.']
321 self.render_error status: 422
324 false # For convenience to return from callbacks
327 def using_specific_api_token(api_token)
329 [:arvados_api_token, :user].each do |key|
330 start_values[key] = Thread.current[key]
332 Thread.current[:arvados_api_token] = api_token
333 Thread.current[:user] = nil
337 start_values.each_key { |key| Thread.current[key] = start_values[key] }
341 def find_object_by_uuid
342 if params[:id] and params[:id].match /\D/
343 params[:uuid] = params.delete :id
347 elsif params[:uuid].is_a? String
348 if params[:uuid].empty?
351 if (model_class != Link and
352 resource_class_for_uuid(params[:uuid]) == Link)
353 @name_link = Link.find(params[:uuid])
354 @object = model_class.find(@name_link.head_uuid)
356 @object = model_class.find(params[:uuid])
360 @object = model_class.where(uuid: params[:uuid]).first
365 Thread.current[:arvados_api_token] = nil
366 Thread.current[:user] = nil
367 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
369 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
372 def thread_with_api_token
373 # If an API token has already been found, pass it through.
374 if Thread.current[:arvados_api_token]
380 # If there's a valid api_token parameter, use it to set up the session.
381 if (Thread.current[:arvados_api_token] = params[:api_token]) and
383 session[:arvados_api_token] = params[:api_token]
388 first_name: u.first_name,
389 last_name: u.last_name,
390 is_active: u.is_active,
391 is_admin: u.is_admin,
394 if !request.format.json? and request.method.in? ['GET', 'HEAD']
395 # Repeat this request with api_token in the (new) session
396 # cookie instead of the query string. This prevents API
397 # tokens from appearing in (and being inadvisedly copied
398 # and pasted from) browser Location bars.
399 redirect_to strip_token_from_path(request.fullpath)
404 # With setup done, handle the request using the session token.
405 Thread.current[:arvados_api_token] = session[:arvados_api_token]
408 rescue ArvadosApiClient::NotLoggedInException
409 # If we got this error with a token, it must've expired.
410 # Retry the request without a token.
411 unless Thread.current[:arvados_api_token].nil?
412 Thread.current[:arvados_api_token] = nil
417 # Remove token in case this Thread is used for anything else.
418 Thread.current[:arvados_api_token] = nil
422 def thread_with_mandatory_api_token
423 if Thread.current[:arvados_api_token]
425 elsif session[:arvados_api_token]
426 # Expired session. Clear it before refreshing login so that,
427 # if this login procedure fails, we end up showing the "please
428 # log in" page instead of getting stuck in a redirect loop.
429 session.delete :arvados_api_token
432 render 'users/welcome'
438 Link.where(uuid: 'just-verifying-my-api-token')
440 rescue ArvadosApiClient::NotLoggedInException
445 def ensure_current_user_is_admin
446 unless current_user and current_user.is_admin
447 @errors = ['Permission denied']
448 self.render_error status: 401
452 def check_user_agreements
453 if current_user && !current_user.is_active
454 if not current_user.is_invited
455 return render 'users/inactive'
457 signatures = UserAgreement.signatures
458 @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
459 @required_user_agreements = UserAgreement.all.map do |ua|
460 if not @signed_ua_uuids.index ua.uuid
461 Collection.find(ua.uuid)
464 if @required_user_agreements.empty?
465 # No agreements to sign. Perhaps we just need to ask?
466 current_user.activate
467 if !current_user.is_active
468 logger.warn "#{current_user.uuid.inspect}: " +
469 "No user agreements to sign, but activate failed!"
472 if !current_user.is_active
473 render 'user_agreements/index'
480 return Rails.configuration.arvados_theme
483 @@notification_tests = []
485 @@notification_tests.push lambda { |controller, current_user|
486 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
489 return lambda { |view|
490 view.render partial: 'notifications/ssh_key_notification'
494 #@@notification_tests.push lambda { |controller, current_user|
495 # Job.limit(1).where(created_by: current_user.uuid).each do
498 # return lambda { |view|
499 # view.render partial: 'notifications/jobs_notification'
503 @@notification_tests.push lambda { |controller, current_user|
504 Collection.limit(1).where(created_by: current_user.uuid).each do
507 return lambda { |view|
508 view.render partial: 'notifications/collections_notification'
512 @@notification_tests.push lambda { |controller, current_user|
513 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
516 return lambda { |view|
517 view.render partial: 'notifications/pipelines_notification'
521 def check_user_notifications
522 return if params['tab_pane']
524 @notification_count = 0
528 @showallalerts = false
529 @@notification_tests.each do |t|
530 a = t.call(self, current_user)
532 @notification_count += 1
533 @notifications.push a
538 if @notification_count == 0
539 @notification_count = ''
543 helper_method :all_projects
545 @all_projects ||= Group.
546 filter([['group_class','in',['project','folder']]]).order('name')
549 helper_method :my_projects
551 return @my_projects if @my_projects
554 all_projects.each do |g|
555 root_of[g.uuid] = g.owner_uuid
561 root_of = root_of.each_with_object({}) do |(child, parent), h|
563 h[child] = root_of[parent]
570 @my_projects = @my_projects.select do |g|
571 root_of[g.uuid] == current_user.uuid
575 helper_method :projects_shared_with_me
576 def projects_shared_with_me
577 my_project_uuids = my_projects.collect &:uuid
578 all_projects.reject { |x| x.uuid.in? my_project_uuids }
581 helper_method :recent_jobs_and_pipelines
582 def recent_jobs_and_pipelines
584 PipelineInstance.limit(10)).
586 x.finished_at || x.started_at || x.created_at rescue x.created_at
590 helper_method :my_project_tree
596 helper_method :shared_project_tree
597 def shared_project_tree
602 def build_project_trees
603 return if @my_project_tree and @shared_project_tree
604 parent_of = {current_user.uuid => 'me'}
605 all_projects.each do |ob|
606 parent_of[ob.uuid] = ob.owner_uuid
608 children_of = {false => [], 'me' => [current_user]}
609 all_projects.each do |ob|
610 if ob.owner_uuid != current_user.uuid and
611 not parent_of.has_key? ob.owner_uuid
612 parent_of[ob.uuid] = false
614 children_of[parent_of[ob.uuid]] ||= []
615 children_of[parent_of[ob.uuid]] << ob
617 buildtree = lambda do |children_of, root_uuid=false|
619 children_of[root_uuid].andand.each do |ob|
620 tree[ob] = buildtree.call(children_of, ob.uuid)
624 sorted_paths = lambda do |tree, depth=0|
626 tree.keys.sort_by { |ob|
627 ob.is_a?(String) ? ob : ob.friendly_link_name
629 paths << {object: ob, depth: depth}
630 paths += sorted_paths.call tree[ob], depth+1
635 sorted_paths.call buildtree.call(children_of, 'me')
636 @shared_project_tree =
637 sorted_paths.call({'Shared with me' =>
638 buildtree.call(children_of, false)})
641 helper_method :get_object
643 if @get_object.nil? and @objects
644 @get_object = @objects.each_with_object({}) do |object, h|
645 h[object.uuid] = object
652 helper_method :project_breadcrumbs
653 def project_breadcrumbs
655 current = @name_link || @object
657 if current.is_a?(Group) and current.group_class.in?(['project','folder'])
658 crumbs.prepend current
660 if current.is_a? Link
661 current = Group.find?(current.tail_uuid)
663 current = Group.find?(current.owner_uuid)
669 helper_method :current_project_uuid
670 def current_project_uuid
671 if @object.is_a? Group and @object.group_class.in?(['project','folder'])
673 elsif @name_link.andand.tail_uuid
675 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
682 # helper method to get links for given object or uuid
683 helper_method :links_for_object
684 def links_for_object object_or_uuid
685 raise ArgumentError, 'No input argument' unless object_or_uuid
686 preload_links_for_objects([object_or_uuid])
687 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
688 @all_links_for[uuid] ||= []
691 # helper method to preload links for given objects and uuids
692 helper_method :preload_links_for_objects
693 def preload_links_for_objects objects_and_uuids
694 @all_links_for ||= {}
696 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
697 return @all_links_for if objects_and_uuids.empty?
699 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
701 # if already preloaded for all of these uuids, return
702 if not uuids.select { |x| @all_links_for[x].nil? }.any?
703 return @all_links_for
707 @all_links_for[x] = []
710 # TODO: make sure we get every page of results from API server
711 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
712 @all_links_for[link.head_uuid] << link
717 # helper method to get a certain number of objects of a specific type
718 # this can be used to replace any uses of: "dataclass.limit(n)"
719 helper_method :get_n_objects_of_class
720 def get_n_objects_of_class dataclass, size
721 @objects_map_for ||= {}
723 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
724 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
726 # if the objects_map_for has a value for this dataclass, and the
727 # size used to retrieve those objects is equal, return it
728 size_key = "#{dataclass.name}_size"
729 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
730 (@objects_map_for[size_key] == size)
731 return @objects_map_for[dataclass.name]
734 @objects_map_for[size_key] = size
735 @objects_map_for[dataclass.name] = dataclass.limit(size)
738 # helper method to get collections for the given uuid
739 helper_method :collections_for_object
740 def collections_for_object uuid
741 raise ArgumentError, 'No input argument' unless uuid
742 preload_collections_for_objects([uuid])
743 @all_collections_for[uuid] ||= []
746 # helper method to preload collections for the given uuids
747 helper_method :preload_collections_for_objects
748 def preload_collections_for_objects uuids
749 @all_collections_for ||= {}
751 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
752 return @all_collections_for if uuids.empty?
754 # if already preloaded for all of these uuids, return
755 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
756 return @all_collections_for
760 @all_collections_for[x] = []
763 # TODO: make sure we get every page of results from API server
764 Collection.where(uuid: uuids).each do |collection|
765 @all_collections_for[collection.uuid] << collection
770 # helper method to get log collections for the given log
771 helper_method :log_collections_for_object
772 def log_collections_for_object log
773 raise ArgumentError, 'No input argument' unless log
775 preload_log_collections_for_objects([log])
778 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
779 if fixup && fixup.size>1
783 @all_log_collections_for[uuid] ||= []
786 # helper method to preload collections for the given uuids
787 helper_method :preload_log_collections_for_objects
788 def preload_log_collections_for_objects logs
789 @all_log_collections_for ||= {}
791 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
792 return @all_log_collections_for if logs.empty?
796 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
797 if fixup && fixup.size>1
804 # if already preloaded for all of these uuids, return
805 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
806 return @all_log_collections_for
810 @all_log_collections_for[x] = []
813 # TODO: make sure we get every page of results from API server
814 Collection.where(uuid: uuids).each do |collection|
815 @all_log_collections_for[collection.uuid] << collection
817 @all_log_collections_for
820 # helper method to get object of a given dataclass and uuid
821 helper_method :object_for_dataclass
822 def object_for_dataclass dataclass, uuid
823 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
824 preload_objects_for_dataclass(dataclass, [uuid])
828 # helper method to preload objects for given dataclass and uuids
829 helper_method :preload_objects_for_dataclass
830 def preload_objects_for_dataclass dataclass, uuids
833 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
834 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
836 return @objects_for if uuids.empty?
838 # if already preloaded for all of these uuids, return
839 if not uuids.select { |x| @objects_for[x].nil? }.any?
843 dataclass.where(uuid: uuids).each do |obj|
844 @objects_for[obj.uuid] = obj