1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 class ApplicationController < ActionController::Base
6 include ArvadosApiClientHelper
7 include ApplicationHelper
9 respond_to :html, :json, :js
12 ERROR_ACTIONS = [:render_error, :render_not_found]
14 prepend_before_filter :set_current_request_id, except: ERROR_ACTIONS
15 around_filter :thread_clear
16 around_filter :set_thread_api_token
17 # Methods that don't require login should
18 # skip_around_filter :require_thread_api_token
19 around_filter :require_thread_api_token, except: ERROR_ACTIONS
20 before_filter :ensure_arvados_api_exists, only: [:index, :show]
21 before_filter :set_cache_buster
22 before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
23 before_filter :check_user_agreements, except: ERROR_ACTIONS
24 before_filter :check_user_profile, except: ERROR_ACTIONS
25 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
26 before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS
30 rescue_from(ActiveRecord::RecordNotFound,
31 ActionController::RoutingError,
32 ActionController::UnknownController,
33 AbstractController::ActionNotFound,
34 with: :render_not_found)
35 rescue_from(Exception,
36 ActionController::UrlGenerationError,
37 with: :render_exception)
41 response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
42 response.headers["Pragma"] = "no-cache"
43 response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
46 def unprocessable(message=nil)
49 @errors << message if message
50 render_error status: 422
53 def render_error(opts={})
54 # Helpers can rely on the presence of @errors to know they're
55 # being used in an error page.
59 # json must come before html here, so it gets used as the
60 # default format when js is requested by the client. This lets
61 # ajax:error callback parse the response correctly, even though
63 f.json { render opts.merge(json: {success: false, errors: @errors}) }
64 f.html { render({action: 'error'}.merge(opts)) }
68 def render_exception(e)
69 logger.error e.inspect
70 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
71 err_opts = {status: 422}
72 if e.is_a?(ArvadosApiClient::ApiError)
73 err_opts.merge!(action: 'api_error', locals: {api_error: e})
74 @errors = e.api_response[:errors]
75 elsif @object.andand.errors.andand.full_messages.andand.any?
76 @errors = @object.errors.full_messages
80 # Make user information available on the error page, falling back to the
81 # session cache if the API server is unavailable.
83 load_api_token(session[:arvados_api_token])
84 rescue ArvadosApiClient::ApiError
85 unless session[:user].nil?
87 Thread.current[:user] = User.new(session[:user])
88 rescue ArvadosApiClient::ApiError
89 # This can happen if User's columns are unavailable. Nothing to do.
93 # Preload projects trees for the template. If that's not doable, set empty
94 # trees so error page rendering can proceed. (It's easier to rescue the
95 # exception here than in a template.)
96 unless current_user.nil?
98 my_starred_projects current_user
99 build_my_wanted_projects_tree current_user
100 rescue ArvadosApiClient::ApiError
101 # Fall back to the default-setting code later.
104 @starred_projects ||= []
105 @my_wanted_projects_tree ||= []
106 render_error(err_opts)
109 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
110 logger.error e.inspect
111 @errors = ["Path not found"]
112 set_thread_api_token do
113 self.render_error(action: '404', status: 404)
119 # The order can be left empty to allow it to default.
120 # Or it can be a comma separated list of real database column names, one per model.
121 # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
122 # (e.g. "collections.name" or "collections.name desc").
123 # If a column name is specified, that table will be sorted by that column.
124 # If there are objects from different models that will be shown (such as in Pipelines and processes tab),
125 # then a sort column name can optionally be specified for each model, passed as an comma-separated list (e.g. "jobs.script, pipeline_instances.name")
126 # Currently only one sort column name and direction can be specified for each model.
127 def load_filters_and_paging_params
128 if params[:order].blank?
129 @order = 'created_at desc'
130 elsif params[:order].is_a? Array
131 @order = params[:order]
134 @order = JSON.load(params[:order])
136 @order = params[:order].split(',')
139 @order = [@order] unless @order.is_a? Array
143 @limit = params[:limit].to_i
148 @offset = params[:offset].to_i
153 filters = params[:filters]
154 if filters.is_a? String
155 filters = Oj.load filters
156 elsif filters.is_a? Array
157 filters = filters.collect do |filter|
158 if filter.is_a? String
159 # Accept filters[]=["foo","=","bar"]
162 # Accept filters=[["foo","=","bar"]]
167 # After this, params[:filters] can be trusted to be an array of arrays:
168 params[:filters] = filters
173 def find_objects_for_index
174 @objects ||= model_class
175 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
176 @objects.fetch_multiple_pages(false)
183 @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json)
185 content: render_to_string(partial: "show_#{params[:partial]}",
187 next_page_href: @next_page_href
190 render json: @objects
195 render_pane params[:tab_pane]
204 helper_method :render_pane
205 def render_pane tab_pane, opts={}
207 partial: 'show_' + tab_pane.downcase,
209 comparable: self.respond_to?(:compare),
212 }.merge(opts[:locals] || {})
215 render_to_string render_opts
221 def ensure_arvados_api_exists
222 if model_class.is_a?(Class) && model_class < ArvadosBase && !model_class.api_exists?(params['action'].to_sym)
223 @errors = ["#{params['action']} method is not supported for #{params['controller']}"]
224 return render_error(status: 404)
229 find_objects_for_index if !@objects
233 helper_method :next_page_offset
234 def next_page_offset objects=nil
238 if objects.respond_to?(:result_offset) and
239 objects.respond_to?(:result_limit)
240 next_offset = objects.result_offset + objects.result_limit
241 if objects.respond_to?(:items_available) and (next_offset < objects.items_available)
243 elsif @objects.results.size > 0 and (params[:count] == 'none' or
244 (params[:controller] == 'search' and params[:action] == 'choose'))
245 last_object_class = @objects.last.class
246 if params['last_object_class'].nil? or params['last_object_class'] == last_object_class.to_s
249 @objects.select{|obj| obj.class == last_object_class}.size
257 helper_method :next_page_href
258 def next_page_href with_params={}
260 url_for with_params.merge(offset: next_page_offset)
264 helper_method :next_page_filters
265 def next_page_filters nextpage_operator
266 next_page_filters = @filters.reject do |attr, op, val|
267 (attr == 'created_at' and op == nextpage_operator) or
268 (attr == 'uuid' and op == 'not in')
272 last_created_at = @objects.last.created_at
275 @objects.each do |obj|
276 last_uuids << obj.uuid if obj.created_at.eql?(last_created_at)
279 next_page_filters += [['created_at', nextpage_operator, last_created_at]]
280 next_page_filters += [['uuid', 'not in', last_uuids]]
288 return render_not_found("object not found")
292 extra_attrs = { href: url_for(action: :show, id: @object) }
293 @object.textile_attributes.each do |textile_attr|
294 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
296 render json: @object.attributes.merge(extra_attrs)
299 if params['tab_pane']
300 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
301 elsif request.request_method.in? ['GET', 'HEAD']
304 redirect_to (params[:return_to] ||
305 polymorphic_url(@object,
306 anchor: params[:redirect_to_anchor]))
313 def redirect_to uri, *args
315 if not uri.is_a? String
316 uri = polymorphic_url(uri)
318 render json: {href: uri}
325 params[:limit] ||= 40
329 find_objects_for_index if !@objects
331 content: render_to_string(partial: "choose_rows.html",
333 next_page_href: next_page_href(partial: params[:partial])
338 find_objects_for_index if !@objects
339 render partial: 'choose', locals: {multiple: params[:multiple]}
346 return render_not_found("object not found")
351 @object = model_class.new
355 @updates ||= params[@object.resource_param_name.to_sym]
356 @updates.keys.each do |attr|
357 if @object.send(attr).is_a? Hash
358 if @updates[attr].is_a? String
359 @updates[attr] = Oj.load @updates[attr]
361 if params[:merge] || params["merge_#{attr}".to_sym]
362 # Merge provided Hash with current Hash, instead of
364 @updates[attr] = @object.send(attr).with_indifferent_access.
365 deep_merge(@updates[attr].with_indifferent_access)
369 if @object.update_attributes @updates
372 self.render_error status: 422
377 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
378 @new_resource_attrs ||= {}
379 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
380 @object ||= model_class.new @new_resource_attrs, params["options"]
385 render_error status: 422
389 # Clone the given object, merging any attribute values supplied as
390 # with a create action.
392 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
393 @new_resource_attrs ||= {}
394 @object = @object.dup
395 @object.update_attributes @new_resource_attrs
396 if not @new_resource_attrs[:name] and @object.respond_to? :name
397 if @object.name and @object.name != ''
398 @object.name = "Copy of #{@object.name}"
410 f.json { render json: @object }
412 redirect_to(params[:return_to] || :back)
417 self.render_error status: 422
422 Thread.current[:user]
426 controller_name.classify.constantize
429 def breadcrumb_page_name
430 (@breadcrumb_page_name ||
431 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
440 %w(Attributes Advanced)
444 @user_is_manager = false
447 if @object.uuid != current_user.andand.uuid
449 @share_links = Link.permissions_for(@object)
450 @user_is_manager = true
451 rescue ArvadosApiClient::AccessForbiddenException,
452 ArvadosApiClient::NotFoundException
458 if not params[:uuids].andand.any?
459 @errors = ["No user/group UUIDs specified to share with."]
460 return render_error(status: 422)
462 results = {"success" => [], "errors" => []}
463 params[:uuids].each do |shared_uuid|
465 Link.create(tail_uuid: shared_uuid, link_class: "permission",
466 name: "can_read", head_uuid: @object.uuid)
467 rescue ArvadosApiClient::ApiError => error
468 error_list = error.api_response.andand[:errors]
469 if error_list.andand.any?
470 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
472 error_code = error.api_status || "Bad status"
473 results["errors"] << "#{shared_uuid}: #{error_code} response"
476 results["success"] << shared_uuid
479 if results["errors"].empty?
480 results.delete("errors")
486 f.json { render(json: results, status: status) }
490 helper_method :is_starred
492 links = Link.where(tail_uuid: current_user.uuid,
493 head_uuid: @object.uuid,
496 return links.andand.any?
501 helper_method :strip_token_from_path
502 def strip_token_from_path(path)
503 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
506 def redirect_to_login
507 if request.xhr? or request.format.json?
508 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
509 render_error status: 401
510 elsif request.method.in? ['GET', 'HEAD']
511 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
513 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."
516 false # For convenience to return from callbacks
519 def using_specific_api_token(api_token, opts={})
521 [:arvados_api_token, :user].each do |key|
522 start_values[key] = Thread.current[key]
524 if opts.fetch(:load_user, true)
525 load_api_token(api_token)
527 Thread.current[:arvados_api_token] = api_token
528 Thread.current[:user] = nil
533 start_values.each_key { |key| Thread.current[key] = start_values[key] }
538 def accept_uuid_as_id_param
539 if params[:id] and params[:id].match /\D/
540 params[:uuid] = params.delete :id
544 def find_object_by_uuid
548 elsif params[:uuid].nil? or params[:uuid].empty?
550 elsif not params[:uuid].is_a?(String)
551 @object = model_class.where(uuid: params[:uuid]).first
552 elsif (model_class != Link and
553 resource_class_for_uuid(params[:uuid]) == Link)
554 @name_link = Link.find(params[:uuid])
555 @object = model_class.find(@name_link.head_uuid)
557 @object = model_class.find(params[:uuid])
558 load_preloaded_objects [@object]
560 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
561 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
564 render_not_found(error)
571 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
573 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
576 # Set up the thread with the given API token and associated user object.
577 def load_api_token(new_token)
578 Thread.current[:arvados_api_token] = new_token
580 Thread.current[:user] = nil
582 Thread.current[:user] = User.current
586 # If there's a valid api_token parameter, set up the session with that
587 # user's information. Return true if the method redirects the request
588 # (usually a post-login redirect); false otherwise.
589 def setup_user_session
590 return false unless params[:api_token]
591 Thread.current[:arvados_api_token] = params[:api_token]
594 rescue ArvadosApiClient::NotLoggedInException
595 false # We may redirect to login, or not, based on the current action.
597 session[:arvados_api_token] = params[:api_token]
598 # If we later have trouble contacting the API server, we still want
599 # to be able to render basic user information in the UI--see
600 # render_exception above. We store that in the session here. This is
601 # not intended to be used as a general-purpose cache. See #2891.
605 first_name: user.first_name,
606 last_name: user.last_name,
607 is_active: user.is_active,
608 is_admin: user.is_admin,
612 if !request.format.json? and request.method.in? ['GET', 'HEAD']
613 # Repeat this request with api_token in the (new) session
614 # cookie instead of the query string. This prevents API
615 # tokens from appearing in (and being inadvisedly copied
616 # and pasted from) browser Location bars.
617 redirect_to strip_token_from_path(request.fullpath)
623 Thread.current[:arvados_api_token] = nil
627 # Save the session API token in thread-local storage, and yield.
628 # This method also takes care of session setup if the request
629 # provides a valid api_token parameter.
630 # If a token is unavailable or expired, the block is still run, with
632 def set_thread_api_token
633 if Thread.current[:arvados_api_token]
634 yield # An API token has already been found - pass it through.
636 elsif setup_user_session
637 return # A new session was set up and received a response.
641 load_api_token(session[:arvados_api_token])
643 rescue ArvadosApiClient::NotLoggedInException
644 # If we got this error with a token, it must've expired.
645 # Retry the request without a token.
646 unless Thread.current[:arvados_api_token].nil?
651 # Remove token in case this Thread is used for anything else.
656 # Redirect to login/welcome if client provided expired API token (or
658 def require_thread_api_token
659 if Thread.current[:arvados_api_token]
661 elsif session[:arvados_api_token]
662 # Expired session. Clear it before refreshing login so that,
663 # if this login procedure fails, we end up showing the "please
664 # log in" page instead of getting stuck in a redirect loop.
665 session.delete :arvados_api_token
668 # If we redirect to the welcome page, the browser will handle
669 # the 302 by itself and the client code will end up rendering
670 # the "welcome" page in some content area where it doesn't make
671 # sense. Instead, we send 401 ("authenticate and try again" or
672 # "display error", depending on how smart the client side is).
673 @errors = ['You are not logged in.']
674 render_error status: 401
676 redirect_to welcome_users_path(return_to: request.fullpath)
680 def ensure_current_user_is_admin
682 @errors = ['Not logged in']
683 render_error status: 401
684 elsif not current_user.is_admin
685 @errors = ['Permission denied']
686 render_error status: 403
690 helper_method :unsigned_user_agreements
691 def unsigned_user_agreements
692 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
693 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
694 if not @signed_ua_uuids.index ua.uuid
695 Collection.find(ua.uuid)
700 def check_user_agreements
701 if current_user && !current_user.is_active
702 if not current_user.is_invited
703 return redirect_to inactive_users_path(return_to: request.fullpath)
705 if unsigned_user_agreements.empty?
706 # No agreements to sign. Perhaps we just need to ask?
707 current_user.activate
708 if !current_user.is_active
709 logger.warn "#{current_user.uuid.inspect}: " +
710 "No user agreements to sign, but activate failed!"
713 if !current_user.is_active
714 redirect_to user_agreements_path(return_to: request.fullpath)
720 def check_user_profile
721 return true if !current_user
722 if request.method.downcase != 'get' || params[:partial] ||
723 params[:tab_pane] || params[:action_method] ||
724 params[:action] == 'setup_popup'
728 if missing_required_profile?
729 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
734 helper_method :missing_required_profile?
735 def missing_required_profile?
736 missing_required = false
738 profile_config = Rails.configuration.user_profile_form_fields
739 if current_user && profile_config
740 current_user_profile = current_user.prefs[:profile]
741 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
743 if !current_user_profile ||
744 !current_user_profile[entry['key'].to_sym] ||
745 current_user_profile[entry['key'].to_sym].empty?
746 missing_required = true
757 return Rails.configuration.arvados_theme
760 @@notification_tests = []
762 @@notification_tests.push lambda { |controller, current_user|
763 return nil if Rails.configuration.shell_in_a_box_url
764 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
767 return lambda { |view|
768 view.render partial: 'notifications/ssh_key_notification'
772 @@notification_tests.push lambda { |controller, current_user|
773 Collection.limit(1).where(created_by: current_user.uuid).each do
776 return lambda { |view|
777 view.render partial: 'notifications/collections_notification'
781 @@notification_tests.push lambda { |controller, current_user|
782 if PipelineInstance.api_exists?(:index)
783 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
789 return lambda { |view|
790 view.render partial: 'notifications/pipelines_notification'
794 helper_method :user_notifications
795 def user_notifications
796 return [] if @errors or not current_user.andand.is_active or not Rails.configuration.show_user_notifications
797 @notifications ||= @@notification_tests.map do |t|
798 t.call(self, current_user)
802 helper_method :all_projects
804 @all_projects ||= Group.
805 filter([['group_class','=','project']]).order('name')
808 helper_method :my_projects
810 return @my_projects if @my_projects
813 all_projects.each do |g|
814 root_of[g.uuid] = g.owner_uuid
820 root_of = root_of.each_with_object({}) do |(child, parent), h|
822 h[child] = root_of[parent]
829 @my_projects = @my_projects.select do |g|
830 root_of[g.uuid] == current_user.uuid
834 helper_method :projects_shared_with_me
835 def projects_shared_with_me
836 my_project_uuids = my_projects.collect &:uuid
837 all_projects.reject { |x| x.uuid.in? my_project_uuids }
840 helper_method :recent_jobs_and_pipelines
841 def recent_jobs_and_pipelines
843 PipelineInstance.limit(10)).
845 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
849 helper_method :running_pipelines
850 def running_pipelines
851 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
854 pl.components.each do |k,v|
855 if v.is_a? Hash and v[:job]
856 jobs[v[:job][:uuid]] = {}
862 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
867 pl.components.each do |k,v|
868 if v.is_a? Hash and v[:job]
869 v[:job] = jobs[v[:job][:uuid]]
878 helper_method :recent_processes
879 def recent_processes lim
883 if PipelineInstance.api_exists?(:index)
884 cols = %w(uuid owner_uuid created_at modified_at pipeline_template_uuid name state started_at finished_at)
885 pipelines = PipelineInstance.select(cols).limit(lim).order(["created_at desc"])
886 pipelines.results.each { |pi| procs[pi] = pi.created_at }
889 crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
890 crs.results.each { |c| procs[c] = c.created_at }
892 Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
895 helper_method :recent_collections
896 def recent_collections lim
897 c = Collection.limit(lim).order(["modified_at desc"]).results
899 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
902 {collections: c, owners: own}
905 helper_method :my_starred_projects
906 def my_starred_projects user
907 return if @starred_projects
908 links = Link.filter([['tail_uuid', '=', user.uuid],
909 ['link_class', '=', 'star'],
910 ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
911 uuids = links.collect { |x| x.head_uuid }
912 starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
913 @starred_projects = starred_projects.results
916 # If there are more than 200 projects that are readable by the user,
917 # build the tree using only the top 200+ projects owned by the user,
918 # from the top three levels.
919 # That is: get toplevel projects under home, get subprojects of
920 # these projects, and so on until we hit the limit.
921 def my_wanted_projects(user, page_size=100)
922 return @my_wanted_projects if @my_wanted_projects
927 @too_many_projects = false
928 @reached_level_limit = false
929 while from_top.size <= page_size*2
930 current_level = Group.filter([['group_class','=','project'],
931 ['owner_uuid', 'in', uuids]])
932 .order('name').limit(page_size*2)
933 break if current_level.results.size == 0
934 @too_many_projects = true if current_level.items_available > current_level.results.size
935 from_top.concat current_level.results
936 uuids = current_level.results.collect(&:uuid)
939 @reached_level_limit = true
943 @my_wanted_projects = from_top
946 helper_method :my_wanted_projects_tree
947 def my_wanted_projects_tree(user, page_size=100)
948 build_my_wanted_projects_tree(user, page_size)
949 [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
952 def build_my_wanted_projects_tree(user, page_size=100)
953 return @my_wanted_projects_tree if @my_wanted_projects_tree
955 parent_of = {user.uuid => 'me'}
956 my_wanted_projects(user, page_size).each do |ob|
957 parent_of[ob.uuid] = ob.owner_uuid
959 children_of = {false => [], 'me' => [user]}
960 my_wanted_projects(user, page_size).each do |ob|
961 if ob.owner_uuid != user.uuid and
962 not parent_of.has_key? ob.owner_uuid
963 parent_of[ob.uuid] = false
965 children_of[parent_of[ob.uuid]] ||= []
966 children_of[parent_of[ob.uuid]] << ob
968 buildtree = lambda do |children_of, root_uuid=false|
970 children_of[root_uuid].andand.each do |ob|
971 tree[ob] = buildtree.call(children_of, ob.uuid)
975 sorted_paths = lambda do |tree, depth=0|
977 tree.keys.sort_by { |ob|
978 ob.is_a?(String) ? ob : ob.friendly_link_name
980 paths << {object: ob, depth: depth}
981 paths += sorted_paths.call tree[ob], depth+1
985 @my_wanted_projects_tree =
986 sorted_paths.call buildtree.call(children_of, 'me')
989 helper_method :get_object
991 if @get_object.nil? and @objects
992 @get_object = @objects.each_with_object({}) do |object, h|
993 h[object.uuid] = object
1000 helper_method :project_breadcrumbs
1001 def project_breadcrumbs
1003 current = @name_link || @object
1005 # Halt if a group ownership loop is detected. API should refuse
1006 # to produce this state, but it could still arise from a race
1007 # condition when group ownership changes between our find()
1009 break if crumbs.collect(&:uuid).include? current.uuid
1011 if current.is_a?(Group) and current.group_class == 'project'
1012 crumbs.prepend current
1014 if current.is_a? Link
1015 current = Group.find?(current.tail_uuid)
1017 current = Group.find?(current.owner_uuid)
1023 helper_method :current_project_uuid
1024 def current_project_uuid
1025 if @object.is_a? Group and @object.group_class == 'project'
1027 elsif @name_link.andand.tail_uuid
1028 @name_link.tail_uuid
1029 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1036 # helper method to get links for given object or uuid
1037 helper_method :links_for_object
1038 def links_for_object object_or_uuid
1039 raise ArgumentError, 'No input argument' unless object_or_uuid
1040 preload_links_for_objects([object_or_uuid])
1041 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1042 @all_links_for[uuid] ||= []
1045 # helper method to preload links for given objects and uuids
1046 helper_method :preload_links_for_objects
1047 def preload_links_for_objects objects_and_uuids
1048 @all_links_for ||= {}
1050 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1051 return @all_links_for if objects_and_uuids.empty?
1053 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1055 # if already preloaded for all of these uuids, return
1056 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1057 return @all_links_for
1061 @all_links_for[x] = []
1064 # TODO: make sure we get every page of results from API server
1065 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1066 @all_links_for[link.head_uuid] << link
1071 # helper method to get a certain number of objects of a specific type
1072 # this can be used to replace any uses of: "dataclass.limit(n)"
1073 helper_method :get_n_objects_of_class
1074 def get_n_objects_of_class dataclass, size
1075 @objects_map_for ||= {}
1077 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1078 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1080 # if the objects_map_for has a value for this dataclass, and the
1081 # size used to retrieve those objects is equal, return it
1082 size_key = "#{dataclass.name}_size"
1083 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1084 (@objects_map_for[size_key] == size)
1085 return @objects_map_for[dataclass.name]
1088 @objects_map_for[size_key] = size
1089 @objects_map_for[dataclass.name] = dataclass.limit(size)
1092 # helper method to get collections for the given uuid
1093 helper_method :collections_for_object
1094 def collections_for_object uuid
1095 raise ArgumentError, 'No input argument' unless uuid
1096 preload_collections_for_objects([uuid])
1097 @all_collections_for[uuid] ||= []
1100 # helper method to preload collections for the given uuids
1101 helper_method :preload_collections_for_objects
1102 def preload_collections_for_objects uuids
1103 @all_collections_for ||= {}
1105 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1106 return @all_collections_for if uuids.empty?
1108 # if already preloaded for all of these uuids, return
1109 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1110 return @all_collections_for
1114 @all_collections_for[x] = []
1117 # TODO: make sure we get every page of results from API server
1118 Collection.where(uuid: uuids).each do |collection|
1119 @all_collections_for[collection.uuid] << collection
1121 @all_collections_for
1124 # helper method to get log collections for the given log
1125 helper_method :log_collections_for_object
1126 def log_collections_for_object log
1127 raise ArgumentError, 'No input argument' unless log
1129 preload_log_collections_for_objects([log])
1132 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1133 if fixup && fixup.size>1
1137 @all_log_collections_for[uuid] ||= []
1140 # helper method to preload collections for the given uuids
1141 helper_method :preload_log_collections_for_objects
1142 def preload_log_collections_for_objects logs
1143 @all_log_collections_for ||= {}
1145 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1146 return @all_log_collections_for if logs.empty?
1150 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1151 if fixup && fixup.size>1
1158 # if already preloaded for all of these uuids, return
1159 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1160 return @all_log_collections_for
1164 @all_log_collections_for[x] = []
1167 # TODO: make sure we get every page of results from API server
1168 Collection.where(uuid: uuids).each do |collection|
1169 @all_log_collections_for[collection.uuid] << collection
1171 @all_log_collections_for
1174 # Helper method to get one collection for the given portable_data_hash
1175 # This is used to determine if a pdh is readable by the current_user
1176 helper_method :collection_for_pdh
1177 def collection_for_pdh pdh
1178 raise ArgumentError, 'No input argument' unless pdh
1179 preload_for_pdhs([pdh])
1180 @all_pdhs_for[pdh] ||= []
1183 # Helper method to preload one collection each for the given pdhs
1184 # This is used to determine if a pdh is readable by the current_user
1185 helper_method :preload_for_pdhs
1186 def preload_for_pdhs pdhs
1187 @all_pdhs_for ||= {}
1189 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1190 return @all_pdhs_for if pdhs.empty?
1192 # if already preloaded for all of these pdhs, return
1193 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1194 return @all_pdhs_for
1198 @all_pdhs_for[x] = []
1201 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1202 @all_pdhs_for[collection.portable_data_hash] << collection
1207 # helper method to get object of a given dataclass and uuid
1208 helper_method :object_for_dataclass
1209 def object_for_dataclass dataclass, uuid, by_attr=nil
1210 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1211 preload_objects_for_dataclass(dataclass, [uuid], by_attr)
1215 # helper method to preload objects for given dataclass and uuids
1216 helper_method :preload_objects_for_dataclass
1217 def preload_objects_for_dataclass dataclass, uuids, by_attr=nil
1220 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1221 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1223 return @objects_for if uuids.empty?
1225 # if already preloaded for all of these uuids, return
1226 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1230 # preset all uuids to nil
1232 @objects_for[x] = nil
1234 if by_attr and ![:uuid, :name].include?(by_attr)
1235 raise ArgumentError, "Preloading only using lookups by uuid or name are supported: #{by_attr}"
1236 elsif by_attr and by_attr == :name
1237 dataclass.where(name: uuids).each do |obj|
1238 @objects_for[obj.name] = obj
1241 key_prefix = "request_#{Thread.current.object_id}_#{dataclass.to_s}_"
1242 dataclass.where(uuid: uuids).each do |obj|
1243 @objects_for[obj.uuid] = obj
1244 if dataclass == Collection
1245 # The collecions#index defaults to "all attributes except manifest_text"
1246 # Hence, this object is not suitable for preloading the find() cache.
1248 Rails.cache.write(key_prefix + obj.uuid, obj.as_json)
1255 # helper method to load objects that are already preloaded
1256 helper_method :load_preloaded_objects
1257 def load_preloaded_objects objs
1260 @objects_for[obj.uuid] = obj
1264 # helper method to get the names of collection files selected
1265 helper_method :selected_collection_files
1266 def selected_collection_files params
1267 link_uuids, coll_ids = params["selection"].partition do |sel_s|
1268 ArvadosBase::resource_class_for_uuid(sel_s) == Link
1271 unless link_uuids.empty?
1272 Link.select([:head_uuid]).where(uuid: link_uuids).each do |link|
1273 if ArvadosBase::resource_class_for_uuid(link.head_uuid) == Collection
1274 coll_ids << link.head_uuid
1281 source_paths = Hash.new { |hash, key| hash[key] = [] }
1282 coll_ids.each do |coll_id|
1283 if m = CollectionsHelper.match(coll_id)
1286 source_paths[key] << m[4]
1287 elsif m = CollectionsHelper.match_uuid_with_optional_filepath(coll_id)
1290 source_paths[key] << m[4]
1295 Collection.where(portable_data_hash: pdhs.uniq).
1296 select([:uuid, :portable_data_hash]).each do |coll|
1297 unless source_paths[coll.portable_data_hash].empty?
1299 source_paths[coll.uuid] = source_paths.delete(coll.portable_data_hash)
1304 [uuids, source_paths]
1307 def wiselinks_layout
1311 def set_current_request_id
1312 # Request ID format: '<timestamp>-<9_digits_random_number>'
1313 current_request_id = "#{Time.new.to_i}-#{sprintf('%09d', rand(0..10**9-1))}"
1314 Thread.current[:current_request_id] = current_request_id