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 prepend_before_filter :set_current_request_id, except: ERROR_ACTIONS
11 around_filter :thread_clear
12 around_filter :set_thread_api_token
13 # Methods that don't require login should
14 # skip_around_filter :require_thread_api_token
15 around_filter :require_thread_api_token, except: ERROR_ACTIONS
16 before_filter :set_cache_buster
17 before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
18 before_filter :check_user_agreements, except: ERROR_ACTIONS
19 before_filter :check_user_profile, except: ERROR_ACTIONS
20 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
21 before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS
25 rescue_from(ActiveRecord::RecordNotFound,
26 ActionController::RoutingError,
27 ActionController::UnknownController,
28 AbstractController::ActionNotFound,
29 with: :render_not_found)
30 rescue_from(Exception,
31 ActionController::UrlGenerationError,
32 with: :render_exception)
36 response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
37 response.headers["Pragma"] = "no-cache"
38 response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
41 def unprocessable(message=nil)
44 @errors << message if message
45 render_error status: 422
48 def render_error(opts={})
49 # Helpers can rely on the presence of @errors to know they're
50 # being used in an error page.
54 # json must come before html here, so it gets used as the
55 # default format when js is requested by the client. This lets
56 # ajax:error callback parse the response correctly, even though
58 f.json { render opts.merge(json: {success: false, errors: @errors}) }
59 f.html { render({action: 'error'}.merge(opts)) }
63 def render_exception(e)
64 logger.error e.inspect
65 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
66 err_opts = {status: 422}
67 if e.is_a?(ArvadosApiClient::ApiError)
68 err_opts.merge!(action: 'api_error', locals: {api_error: e})
69 @errors = e.api_response[:errors]
70 elsif @object.andand.errors.andand.full_messages.andand.any?
71 @errors = @object.errors.full_messages
75 # Make user information available on the error page, falling back to the
76 # session cache if the API server is unavailable.
78 load_api_token(session[:arvados_api_token])
79 rescue ArvadosApiClient::ApiError
80 unless session[:user].nil?
82 Thread.current[:user] = User.new(session[:user])
83 rescue ArvadosApiClient::ApiError
84 # This can happen if User's columns are unavailable. Nothing to do.
88 # Preload projects trees for the template. If that's not doable, set empty
89 # trees so error page rendering can proceed. (It's easier to rescue the
90 # exception here than in a template.)
91 unless current_user.nil?
93 my_starred_projects current_user
94 build_my_wanted_projects_tree current_user
95 rescue ArvadosApiClient::ApiError
96 # Fall back to the default-setting code later.
99 @starred_projects ||= []
100 @my_wanted_projects_tree ||= []
101 render_error(err_opts)
104 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
105 logger.error e.inspect
106 @errors = ["Path not found"]
107 set_thread_api_token do
108 self.render_error(action: '404', status: 404)
114 # The order can be left empty to allow it to default.
115 # Or it can be a comma separated list of real database column names, one per model.
116 # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
117 # (e.g. "collections.name" or "collections.name desc").
118 # If a column name is specified, that table will be sorted by that column.
119 # If there are objects from different models that will be shown (such as in Pipelines and processes tab),
120 # 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")
121 # Currently only one sort column name and direction can be specified for each model.
122 def load_filters_and_paging_params
123 if params[:order].blank?
124 @order = 'created_at desc'
125 elsif params[:order].is_a? Array
126 @order = params[:order]
129 @order = JSON.load(params[:order])
131 @order = params[:order].split(',')
134 @order = [@order] unless @order.is_a? Array
138 @limit = params[:limit].to_i
143 @offset = params[:offset].to_i
148 filters = params[:filters]
149 if filters.is_a? String
150 filters = Oj.load filters
151 elsif filters.is_a? Array
152 filters = filters.collect do |filter|
153 if filter.is_a? String
154 # Accept filters[]=["foo","=","bar"]
157 # Accept filters=[["foo","=","bar"]]
162 # After this, params[:filters] can be trusted to be an array of arrays:
163 params[:filters] = filters
168 def find_objects_for_index
169 @objects ||= model_class
170 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
171 @objects.fetch_multiple_pages(false)
178 @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json)
180 content: render_to_string(partial: "show_#{params[:partial]}",
182 next_page_href: @next_page_href
185 render json: @objects
190 render_pane params[:tab_pane]
199 helper_method :render_pane
200 def render_pane tab_pane, opts={}
202 partial: 'show_' + tab_pane.downcase,
204 comparable: self.respond_to?(:compare),
207 }.merge(opts[:locals] || {})
210 render_to_string render_opts
217 find_objects_for_index if !@objects
221 helper_method :next_page_offset
222 def next_page_offset objects=nil
226 if objects.respond_to?(:result_offset) and
227 objects.respond_to?(:result_limit) and
228 objects.respond_to?(:items_available)
229 next_offset = objects.result_offset + objects.result_limit
230 if next_offset < objects.items_available
238 helper_method :next_page_href
239 def next_page_href with_params={}
241 url_for with_params.merge(offset: next_page_offset)
245 helper_method :next_page_filters
246 def next_page_filters nextpage_operator
247 next_page_filters = @filters.reject do |attr, op, val|
248 (attr == 'created_at' and op == nextpage_operator) or
249 (attr == 'uuid' and op == 'not in')
253 last_created_at = @objects.last.created_at
256 @objects.each do |obj|
257 last_uuids << obj.uuid if obj.created_at.eql?(last_created_at)
260 next_page_filters += [['created_at', nextpage_operator, last_created_at]]
261 next_page_filters += [['uuid', 'not in', last_uuids]]
269 return render_not_found("object not found")
273 extra_attrs = { href: url_for(action: :show, id: @object) }
274 @object.textile_attributes.each do |textile_attr|
275 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
277 render json: @object.attributes.merge(extra_attrs)
280 if params['tab_pane']
281 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
282 elsif request.request_method.in? ['GET', 'HEAD']
285 redirect_to (params[:return_to] ||
286 polymorphic_url(@object,
287 anchor: params[:redirect_to_anchor]))
294 def redirect_to uri, *args
296 if not uri.is_a? String
297 uri = polymorphic_url(uri)
299 render json: {href: uri}
306 params[:limit] ||= 40
310 find_objects_for_index if !@objects
312 content: render_to_string(partial: "choose_rows.html",
314 next_page_href: next_page_href(partial: params[:partial])
319 find_objects_for_index if !@objects
320 render partial: 'choose', locals: {multiple: params[:multiple]}
327 return render_not_found("object not found")
332 @object = model_class.new
336 @updates ||= params[@object.resource_param_name.to_sym]
337 @updates.keys.each do |attr|
338 if @object.send(attr).is_a? Hash
339 if @updates[attr].is_a? String
340 @updates[attr] = Oj.load @updates[attr]
342 if params[:merge] || params["merge_#{attr}".to_sym]
343 # Merge provided Hash with current Hash, instead of
345 @updates[attr] = @object.send(attr).with_indifferent_access.
346 deep_merge(@updates[attr].with_indifferent_access)
350 if @object.update_attributes @updates
353 self.render_error status: 422
358 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
359 @new_resource_attrs ||= {}
360 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
361 @object ||= model_class.new @new_resource_attrs, params["options"]
366 render_error status: 422
370 # Clone the given object, merging any attribute values supplied as
371 # with a create action.
373 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
374 @new_resource_attrs ||= {}
375 @object = @object.dup
376 @object.update_attributes @new_resource_attrs
377 if not @new_resource_attrs[:name] and @object.respond_to? :name
378 if @object.name and @object.name != ''
379 @object.name = "Copy of #{@object.name}"
391 f.json { render json: @object }
393 redirect_to(params[:return_to] || :back)
398 self.render_error status: 422
403 Thread.current[:user]
407 controller_name.classify.constantize
410 def breadcrumb_page_name
411 (@breadcrumb_page_name ||
412 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
421 %w(Attributes Advanced)
425 @user_is_manager = false
428 if @object.uuid != current_user.andand.uuid
430 @share_links = Link.permissions_for(@object)
431 @user_is_manager = true
432 rescue ArvadosApiClient::AccessForbiddenException,
433 ArvadosApiClient::NotFoundException
439 if not params[:uuids].andand.any?
440 @errors = ["No user/group UUIDs specified to share with."]
441 return render_error(status: 422)
443 results = {"success" => [], "errors" => []}
444 params[:uuids].each do |shared_uuid|
446 Link.create(tail_uuid: shared_uuid, link_class: "permission",
447 name: "can_read", head_uuid: @object.uuid)
448 rescue ArvadosApiClient::ApiError => error
449 error_list = error.api_response.andand[:errors]
450 if error_list.andand.any?
451 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
453 error_code = error.api_status || "Bad status"
454 results["errors"] << "#{shared_uuid}: #{error_code} response"
457 results["success"] << shared_uuid
460 if results["errors"].empty?
461 results.delete("errors")
467 f.json { render(json: results, status: status) }
471 helper_method :is_starred
473 links = Link.where(tail_uuid: current_user.uuid,
474 head_uuid: @object.uuid,
477 return links.andand.any?
482 helper_method :strip_token_from_path
483 def strip_token_from_path(path)
484 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
487 def redirect_to_login
488 if request.xhr? or request.format.json?
489 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
490 render_error status: 401
491 elsif request.method.in? ['GET', 'HEAD']
492 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
494 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."
497 false # For convenience to return from callbacks
500 def using_specific_api_token(api_token, opts={})
502 [:arvados_api_token, :user].each do |key|
503 start_values[key] = Thread.current[key]
505 if opts.fetch(:load_user, true)
506 load_api_token(api_token)
508 Thread.current[:arvados_api_token] = api_token
509 Thread.current[:user] = nil
514 start_values.each_key { |key| Thread.current[key] = start_values[key] }
519 def accept_uuid_as_id_param
520 if params[:id] and params[:id].match /\D/
521 params[:uuid] = params.delete :id
525 def find_object_by_uuid
529 elsif not params[:uuid].is_a?(String)
530 @object = model_class.where(uuid: params[:uuid]).first
531 elsif params[:uuid].empty?
533 elsif (model_class != Link and
534 resource_class_for_uuid(params[:uuid]) == Link)
535 @name_link = Link.find(params[:uuid])
536 @object = model_class.find(@name_link.head_uuid)
538 @object = model_class.find(params[:uuid])
540 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
541 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
544 render_not_found(error)
551 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
553 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
556 # Set up the thread with the given API token and associated user object.
557 def load_api_token(new_token)
558 Thread.current[:arvados_api_token] = new_token
560 Thread.current[:user] = nil
562 Thread.current[:user] = User.current
566 # If there's a valid api_token parameter, set up the session with that
567 # user's information. Return true if the method redirects the request
568 # (usually a post-login redirect); false otherwise.
569 def setup_user_session
570 return false unless params[:api_token]
571 Thread.current[:arvados_api_token] = params[:api_token]
574 rescue ArvadosApiClient::NotLoggedInException
575 false # We may redirect to login, or not, based on the current action.
577 session[:arvados_api_token] = params[:api_token]
578 # If we later have trouble contacting the API server, we still want
579 # to be able to render basic user information in the UI--see
580 # render_exception above. We store that in the session here. This is
581 # not intended to be used as a general-purpose cache. See #2891.
585 first_name: user.first_name,
586 last_name: user.last_name,
587 is_active: user.is_active,
588 is_admin: user.is_admin,
592 if !request.format.json? and request.method.in? ['GET', 'HEAD']
593 # Repeat this request with api_token in the (new) session
594 # cookie instead of the query string. This prevents API
595 # tokens from appearing in (and being inadvisedly copied
596 # and pasted from) browser Location bars.
597 redirect_to strip_token_from_path(request.fullpath)
603 Thread.current[:arvados_api_token] = nil
607 # Save the session API token in thread-local storage, and yield.
608 # This method also takes care of session setup if the request
609 # provides a valid api_token parameter.
610 # If a token is unavailable or expired, the block is still run, with
612 def set_thread_api_token
613 if Thread.current[:arvados_api_token]
614 yield # An API token has already been found - pass it through.
616 elsif setup_user_session
617 return # A new session was set up and received a response.
621 load_api_token(session[:arvados_api_token])
623 rescue ArvadosApiClient::NotLoggedInException
624 # If we got this error with a token, it must've expired.
625 # Retry the request without a token.
626 unless Thread.current[:arvados_api_token].nil?
631 # Remove token in case this Thread is used for anything else.
636 # Redirect to login/welcome if client provided expired API token (or
638 def require_thread_api_token
639 if Thread.current[:arvados_api_token]
641 elsif session[:arvados_api_token]
642 # Expired session. Clear it before refreshing login so that,
643 # if this login procedure fails, we end up showing the "please
644 # log in" page instead of getting stuck in a redirect loop.
645 session.delete :arvados_api_token
648 # If we redirect to the welcome page, the browser will handle
649 # the 302 by itself and the client code will end up rendering
650 # the "welcome" page in some content area where it doesn't make
651 # sense. Instead, we send 401 ("authenticate and try again" or
652 # "display error", depending on how smart the client side is).
653 @errors = ['You are not logged in.']
654 render_error status: 401
656 redirect_to welcome_users_path(return_to: request.fullpath)
660 def ensure_current_user_is_admin
662 @errors = ['Not logged in']
663 render_error status: 401
664 elsif not current_user.is_admin
665 @errors = ['Permission denied']
666 render_error status: 403
670 helper_method :unsigned_user_agreements
671 def unsigned_user_agreements
672 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
673 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
674 if not @signed_ua_uuids.index ua.uuid
675 Collection.find(ua.uuid)
680 def check_user_agreements
681 if current_user && !current_user.is_active
682 if not current_user.is_invited
683 return redirect_to inactive_users_path(return_to: request.fullpath)
685 if unsigned_user_agreements.empty?
686 # No agreements to sign. Perhaps we just need to ask?
687 current_user.activate
688 if !current_user.is_active
689 logger.warn "#{current_user.uuid.inspect}: " +
690 "No user agreements to sign, but activate failed!"
693 if !current_user.is_active
694 redirect_to user_agreements_path(return_to: request.fullpath)
700 def check_user_profile
701 return true if !current_user
702 if request.method.downcase != 'get' || params[:partial] ||
703 params[:tab_pane] || params[:action_method] ||
704 params[:action] == 'setup_popup'
708 if missing_required_profile?
709 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
714 helper_method :missing_required_profile?
715 def missing_required_profile?
716 missing_required = false
718 profile_config = Rails.configuration.user_profile_form_fields
719 if current_user && profile_config
720 current_user_profile = current_user.prefs[:profile]
721 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
723 if !current_user_profile ||
724 !current_user_profile[entry['key'].to_sym] ||
725 current_user_profile[entry['key'].to_sym].empty?
726 missing_required = true
737 return Rails.configuration.arvados_theme
740 @@notification_tests = []
742 @@notification_tests.push lambda { |controller, current_user|
743 return nil if Rails.configuration.shell_in_a_box_url
744 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
747 return lambda { |view|
748 view.render partial: 'notifications/ssh_key_notification'
752 @@notification_tests.push lambda { |controller, current_user|
753 Collection.limit(1).where(created_by: current_user.uuid).each do
756 return lambda { |view|
757 view.render partial: 'notifications/collections_notification'
761 @@notification_tests.push lambda { |controller, current_user|
762 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
765 return lambda { |view|
766 view.render partial: 'notifications/pipelines_notification'
770 helper_method :user_notifications
771 def user_notifications
772 return [] if @errors or not current_user.andand.is_active or not Rails.configuration.show_user_notifications_in_dashboard
773 @notifications ||= @@notification_tests.map do |t|
774 t.call(self, current_user)
778 helper_method :all_projects
780 @all_projects ||= Group.
781 filter([['group_class','=','project']]).order('name')
784 helper_method :my_projects
786 return @my_projects if @my_projects
789 all_projects.each do |g|
790 root_of[g.uuid] = g.owner_uuid
796 root_of = root_of.each_with_object({}) do |(child, parent), h|
798 h[child] = root_of[parent]
805 @my_projects = @my_projects.select do |g|
806 root_of[g.uuid] == current_user.uuid
810 helper_method :projects_shared_with_me
811 def projects_shared_with_me
812 my_project_uuids = my_projects.collect &:uuid
813 all_projects.reject { |x| x.uuid.in? my_project_uuids }
816 helper_method :recent_jobs_and_pipelines
817 def recent_jobs_and_pipelines
819 PipelineInstance.limit(10)).
821 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
825 helper_method :running_pipelines
826 def running_pipelines
827 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
830 pl.components.each do |k,v|
831 if v.is_a? Hash and v[:job]
832 jobs[v[:job][:uuid]] = {}
838 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
843 pl.components.each do |k,v|
844 if v.is_a? Hash and v[:job]
845 v[:job] = jobs[v[:job][:uuid]]
854 helper_method :recent_processes
855 def recent_processes lim
858 cols = %w(uuid owner_uuid created_at modified_at pipeline_template_uuid name state started_at finished_at)
859 pipelines = PipelineInstance.select(cols).limit(lim).order(["created_at desc"])
861 crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
863 pipelines.results.each { |pi| procs[pi] = pi.created_at }
864 crs.results.each { |c| procs[c] = c.created_at }
866 Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
869 helper_method :recent_collections
870 def recent_collections lim
871 c = Collection.limit(lim).order(["modified_at desc"]).results
873 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
876 {collections: c, owners: own}
879 helper_method :my_starred_projects
880 def my_starred_projects user
881 return if @starred_projects
882 links = Link.filter([['tail_uuid', '=', user.uuid],
883 ['link_class', '=', 'star'],
884 ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
885 uuids = links.collect { |x| x.head_uuid }
886 starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
887 @starred_projects = starred_projects.results
890 # If there are more than 200 projects that are readable by the user,
891 # build the tree using only the top 200+ projects owned by the user,
892 # from the top three levels.
893 # That is: get toplevel projects under home, get subprojects of
894 # these projects, and so on until we hit the limit.
895 def my_wanted_projects user, page_size=100
896 return @my_wanted_projects if @my_wanted_projects
901 @too_many_projects = false
902 @reached_level_limit = false
903 while from_top.size <= page_size*2
904 current_level = Group.filter([['group_class','=','project'],
905 ['owner_uuid', 'in', uuids]])
906 .order('name').limit(page_size*2)
907 break if current_level.results.size == 0
908 @too_many_projects = true if current_level.items_available > current_level.results.size
909 from_top.concat current_level.results
910 uuids = current_level.results.collect { |x| x.uuid }
913 @reached_level_limit = true
917 @my_wanted_projects = from_top
920 helper_method :my_wanted_projects_tree
921 def my_wanted_projects_tree user, page_size=100
922 build_my_wanted_projects_tree user, page_size
923 [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
926 def build_my_wanted_projects_tree user, page_size=100
927 return @my_wanted_projects_tree if @my_wanted_projects_tree
929 parent_of = {user.uuid => 'me'}
930 my_wanted_projects(user, page_size).each do |ob|
931 parent_of[ob.uuid] = ob.owner_uuid
933 children_of = {false => [], 'me' => [user]}
934 my_wanted_projects(user, page_size).each do |ob|
935 if ob.owner_uuid != user.uuid and
936 not parent_of.has_key? ob.owner_uuid
937 parent_of[ob.uuid] = false
939 children_of[parent_of[ob.uuid]] ||= []
940 children_of[parent_of[ob.uuid]] << ob
942 buildtree = lambda do |children_of, root_uuid=false|
944 children_of[root_uuid].andand.each do |ob|
945 tree[ob] = buildtree.call(children_of, ob.uuid)
949 sorted_paths = lambda do |tree, depth=0|
951 tree.keys.sort_by { |ob|
952 ob.is_a?(String) ? ob : ob.friendly_link_name
954 paths << {object: ob, depth: depth}
955 paths += sorted_paths.call tree[ob], depth+1
959 @my_wanted_projects_tree =
960 sorted_paths.call buildtree.call(children_of, 'me')
963 helper_method :get_object
965 if @get_object.nil? and @objects
966 @get_object = @objects.each_with_object({}) do |object, h|
967 h[object.uuid] = object
974 helper_method :project_breadcrumbs
975 def project_breadcrumbs
977 current = @name_link || @object
979 # Halt if a group ownership loop is detected. API should refuse
980 # to produce this state, but it could still arise from a race
981 # condition when group ownership changes between our find()
983 break if crumbs.collect(&:uuid).include? current.uuid
985 if current.is_a?(Group) and current.group_class == 'project'
986 crumbs.prepend current
988 if current.is_a? Link
989 current = Group.find?(current.tail_uuid)
991 current = Group.find?(current.owner_uuid)
997 helper_method :current_project_uuid
998 def current_project_uuid
999 if @object.is_a? Group and @object.group_class == 'project'
1001 elsif @name_link.andand.tail_uuid
1002 @name_link.tail_uuid
1003 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1010 # helper method to get links for given object or uuid
1011 helper_method :links_for_object
1012 def links_for_object object_or_uuid
1013 raise ArgumentError, 'No input argument' unless object_or_uuid
1014 preload_links_for_objects([object_or_uuid])
1015 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1016 @all_links_for[uuid] ||= []
1019 # helper method to preload links for given objects and uuids
1020 helper_method :preload_links_for_objects
1021 def preload_links_for_objects objects_and_uuids
1022 @all_links_for ||= {}
1024 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1025 return @all_links_for if objects_and_uuids.empty?
1027 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1029 # if already preloaded for all of these uuids, return
1030 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1031 return @all_links_for
1035 @all_links_for[x] = []
1038 # TODO: make sure we get every page of results from API server
1039 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1040 @all_links_for[link.head_uuid] << link
1045 # helper method to get a certain number of objects of a specific type
1046 # this can be used to replace any uses of: "dataclass.limit(n)"
1047 helper_method :get_n_objects_of_class
1048 def get_n_objects_of_class dataclass, size
1049 @objects_map_for ||= {}
1051 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1052 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1054 # if the objects_map_for has a value for this dataclass, and the
1055 # size used to retrieve those objects is equal, return it
1056 size_key = "#{dataclass.name}_size"
1057 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1058 (@objects_map_for[size_key] == size)
1059 return @objects_map_for[dataclass.name]
1062 @objects_map_for[size_key] = size
1063 @objects_map_for[dataclass.name] = dataclass.limit(size)
1066 # helper method to get collections for the given uuid
1067 helper_method :collections_for_object
1068 def collections_for_object uuid
1069 raise ArgumentError, 'No input argument' unless uuid
1070 preload_collections_for_objects([uuid])
1071 @all_collections_for[uuid] ||= []
1074 # helper method to preload collections for the given uuids
1075 helper_method :preload_collections_for_objects
1076 def preload_collections_for_objects uuids
1077 @all_collections_for ||= {}
1079 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1080 return @all_collections_for if uuids.empty?
1082 # if already preloaded for all of these uuids, return
1083 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1084 return @all_collections_for
1088 @all_collections_for[x] = []
1091 # TODO: make sure we get every page of results from API server
1092 Collection.where(uuid: uuids).each do |collection|
1093 @all_collections_for[collection.uuid] << collection
1095 @all_collections_for
1098 # helper method to get log collections for the given log
1099 helper_method :log_collections_for_object
1100 def log_collections_for_object log
1101 raise ArgumentError, 'No input argument' unless log
1103 preload_log_collections_for_objects([log])
1106 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1107 if fixup && fixup.size>1
1111 @all_log_collections_for[uuid] ||= []
1114 # helper method to preload collections for the given uuids
1115 helper_method :preload_log_collections_for_objects
1116 def preload_log_collections_for_objects logs
1117 @all_log_collections_for ||= {}
1119 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1120 return @all_log_collections_for if logs.empty?
1124 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1125 if fixup && fixup.size>1
1132 # if already preloaded for all of these uuids, return
1133 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1134 return @all_log_collections_for
1138 @all_log_collections_for[x] = []
1141 # TODO: make sure we get every page of results from API server
1142 Collection.where(uuid: uuids).each do |collection|
1143 @all_log_collections_for[collection.uuid] << collection
1145 @all_log_collections_for
1148 # Helper method to get one collection for the given portable_data_hash
1149 # This is used to determine if a pdh is readable by the current_user
1150 helper_method :collection_for_pdh
1151 def collection_for_pdh pdh
1152 raise ArgumentError, 'No input argument' unless pdh
1153 preload_for_pdhs([pdh])
1154 @all_pdhs_for[pdh] ||= []
1157 # Helper method to preload one collection each for the given pdhs
1158 # This is used to determine if a pdh is readable by the current_user
1159 helper_method :preload_for_pdhs
1160 def preload_for_pdhs pdhs
1161 @all_pdhs_for ||= {}
1163 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1164 return @all_pdhs_for if pdhs.empty?
1166 # if already preloaded for all of these pdhs, return
1167 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1168 return @all_pdhs_for
1172 @all_pdhs_for[x] = []
1175 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1176 @all_pdhs_for[collection.portable_data_hash] << collection
1181 # helper method to get object of a given dataclass and uuid
1182 helper_method :object_for_dataclass
1183 def object_for_dataclass dataclass, uuid
1184 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1185 preload_objects_for_dataclass(dataclass, [uuid])
1189 # helper method to preload objects for given dataclass and uuids
1190 helper_method :preload_objects_for_dataclass
1191 def preload_objects_for_dataclass dataclass, uuids
1194 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1195 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1197 return @objects_for if uuids.empty?
1199 # if already preloaded for all of these uuids, return
1200 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1204 # preset all uuids to nil
1206 @objects_for[x] = nil
1208 dataclass.where(uuid: uuids).each do |obj|
1209 @objects_for[obj.uuid] = obj
1214 def wiselinks_layout
1218 def set_current_request_id
1219 # Request ID format: '<timestamp>-<9_digits_random_number>'
1220 current_request_id = "#{Time.new.to_i}-#{sprintf('%09d', rand(0..10**9-1))}"
1221 Thread.current[:current_request_id] = current_request_id