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 :ensure_arvados_api_exists, only: [:index, :show]
17 before_filter :set_cache_buster
18 before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
19 before_filter :check_user_agreements, except: ERROR_ACTIONS
20 before_filter :check_user_profile, except: ERROR_ACTIONS
21 before_filter :load_filters_and_paging_params, except: ERROR_ACTIONS
22 before_filter :find_object_by_uuid, except: [:create, :index, :choose] + ERROR_ACTIONS
26 rescue_from(ActiveRecord::RecordNotFound,
27 ActionController::RoutingError,
28 ActionController::UnknownController,
29 AbstractController::ActionNotFound,
30 with: :render_not_found)
31 rescue_from(Exception,
32 ActionController::UrlGenerationError,
33 with: :render_exception)
37 response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"
38 response.headers["Pragma"] = "no-cache"
39 response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"
42 def unprocessable(message=nil)
45 @errors << message if message
46 render_error status: 422
49 def render_error(opts={})
50 # Helpers can rely on the presence of @errors to know they're
51 # being used in an error page.
55 # json must come before html here, so it gets used as the
56 # default format when js is requested by the client. This lets
57 # ajax:error callback parse the response correctly, even though
59 f.json { render opts.merge(json: {success: false, errors: @errors}) }
60 f.html { render({action: 'error'}.merge(opts)) }
64 def render_exception(e)
65 logger.error e.inspect
66 logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
67 err_opts = {status: 422}
68 if e.is_a?(ArvadosApiClient::ApiError)
69 err_opts.merge!(action: 'api_error', locals: {api_error: e})
70 @errors = e.api_response[:errors]
71 elsif @object.andand.errors.andand.full_messages.andand.any?
72 @errors = @object.errors.full_messages
76 # Make user information available on the error page, falling back to the
77 # session cache if the API server is unavailable.
79 load_api_token(session[:arvados_api_token])
80 rescue ArvadosApiClient::ApiError
81 unless session[:user].nil?
83 Thread.current[:user] = User.new(session[:user])
84 rescue ArvadosApiClient::ApiError
85 # This can happen if User's columns are unavailable. Nothing to do.
89 # Preload projects trees for the template. If that's not doable, set empty
90 # trees so error page rendering can proceed. (It's easier to rescue the
91 # exception here than in a template.)
92 unless current_user.nil?
94 my_starred_projects current_user
95 build_my_wanted_projects_tree current_user
96 rescue ArvadosApiClient::ApiError
97 # Fall back to the default-setting code later.
100 @starred_projects ||= []
101 @my_wanted_projects_tree ||= []
102 render_error(err_opts)
105 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
106 logger.error e.inspect
107 @errors = ["Path not found"]
108 set_thread_api_token do
109 self.render_error(action: '404', status: 404)
115 # The order can be left empty to allow it to default.
116 # Or it can be a comma separated list of real database column names, one per model.
117 # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
118 # (e.g. "collections.name" or "collections.name desc").
119 # If a column name is specified, that table will be sorted by that column.
120 # If there are objects from different models that will be shown (such as in Pipelines and processes tab),
121 # 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")
122 # Currently only one sort column name and direction can be specified for each model.
123 def load_filters_and_paging_params
124 if params[:order].blank?
125 @order = 'created_at desc'
126 elsif params[:order].is_a? Array
127 @order = params[:order]
130 @order = JSON.load(params[:order])
132 @order = params[:order].split(',')
135 @order = [@order] unless @order.is_a? Array
139 @limit = params[:limit].to_i
144 @offset = params[:offset].to_i
149 filters = params[:filters]
150 if filters.is_a? String
151 filters = Oj.load filters
152 elsif filters.is_a? Array
153 filters = filters.collect do |filter|
154 if filter.is_a? String
155 # Accept filters[]=["foo","=","bar"]
158 # Accept filters=[["foo","=","bar"]]
163 # After this, params[:filters] can be trusted to be an array of arrays:
164 params[:filters] = filters
169 def find_objects_for_index
170 @objects ||= model_class
171 @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
172 @objects.fetch_multiple_pages(false)
179 @next_page_href = next_page_href(partial: params[:partial], filters: @filters.to_json)
181 content: render_to_string(partial: "show_#{params[:partial]}",
183 next_page_href: @next_page_href
186 render json: @objects
191 render_pane params[:tab_pane]
200 helper_method :render_pane
201 def render_pane tab_pane, opts={}
203 partial: 'show_' + tab_pane.downcase,
205 comparable: self.respond_to?(:compare),
208 }.merge(opts[:locals] || {})
211 render_to_string render_opts
217 def ensure_arvados_api_exists
218 if model_class.is_a?(Class) && model_class < ArvadosBase && !model_class.api_exists?(params['action'].to_sym)
219 @errors = ["#{params['action']} method is not supported for #{params['controller']}"]
220 return render_error(status: 404)
225 find_objects_for_index if !@objects
229 helper_method :next_page_offset
230 def next_page_offset objects=nil
234 if objects.respond_to?(:result_offset) and
235 objects.respond_to?(:result_limit) and
236 objects.respond_to?(:items_available)
237 next_offset = objects.result_offset + objects.result_limit
238 if next_offset < objects.items_available
246 helper_method :next_page_href
247 def next_page_href with_params={}
249 url_for with_params.merge(offset: next_page_offset)
253 helper_method :next_page_filters
254 def next_page_filters nextpage_operator
255 next_page_filters = @filters.reject do |attr, op, val|
256 (attr == 'created_at' and op == nextpage_operator) or
257 (attr == 'uuid' and op == 'not in')
261 last_created_at = @objects.last.created_at
264 @objects.each do |obj|
265 last_uuids << obj.uuid if obj.created_at.eql?(last_created_at)
268 next_page_filters += [['created_at', nextpage_operator, last_created_at]]
269 next_page_filters += [['uuid', 'not in', last_uuids]]
277 return render_not_found("object not found")
281 extra_attrs = { href: url_for(action: :show, id: @object) }
282 @object.textile_attributes.each do |textile_attr|
283 extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
285 render json: @object.attributes.merge(extra_attrs)
288 if params['tab_pane']
289 render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
290 elsif request.request_method.in? ['GET', 'HEAD']
293 redirect_to (params[:return_to] ||
294 polymorphic_url(@object,
295 anchor: params[:redirect_to_anchor]))
302 def redirect_to uri, *args
304 if not uri.is_a? String
305 uri = polymorphic_url(uri)
307 render json: {href: uri}
314 params[:limit] ||= 40
318 find_objects_for_index if !@objects
320 content: render_to_string(partial: "choose_rows.html",
322 next_page_href: next_page_href(partial: params[:partial])
327 find_objects_for_index if !@objects
328 render partial: 'choose', locals: {multiple: params[:multiple]}
335 return render_not_found("object not found")
340 @object = model_class.new
344 @updates ||= params[@object.resource_param_name.to_sym]
345 @updates.keys.each do |attr|
346 if @object.send(attr).is_a? Hash
347 if @updates[attr].is_a? String
348 @updates[attr] = Oj.load @updates[attr]
350 if params[:merge] || params["merge_#{attr}".to_sym]
351 # Merge provided Hash with current Hash, instead of
353 @updates[attr] = @object.send(attr).with_indifferent_access.
354 deep_merge(@updates[attr].with_indifferent_access)
358 if @object.update_attributes @updates
361 self.render_error status: 422
366 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
367 @new_resource_attrs ||= {}
368 @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
369 @object ||= model_class.new @new_resource_attrs, params["options"]
374 render_error status: 422
378 # Clone the given object, merging any attribute values supplied as
379 # with a create action.
381 @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
382 @new_resource_attrs ||= {}
383 @object = @object.dup
384 @object.update_attributes @new_resource_attrs
385 if not @new_resource_attrs[:name] and @object.respond_to? :name
386 if @object.name and @object.name != ''
387 @object.name = "Copy of #{@object.name}"
399 f.json { render json: @object }
401 redirect_to(params[:return_to] || :back)
406 self.render_error status: 422
411 Thread.current[:user]
415 controller_name.classify.constantize
418 def breadcrumb_page_name
419 (@breadcrumb_page_name ||
420 (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
429 %w(Attributes Advanced)
433 @user_is_manager = false
436 if @object.uuid != current_user.andand.uuid
438 @share_links = Link.permissions_for(@object)
439 @user_is_manager = true
440 rescue ArvadosApiClient::AccessForbiddenException,
441 ArvadosApiClient::NotFoundException
447 if not params[:uuids].andand.any?
448 @errors = ["No user/group UUIDs specified to share with."]
449 return render_error(status: 422)
451 results = {"success" => [], "errors" => []}
452 params[:uuids].each do |shared_uuid|
454 Link.create(tail_uuid: shared_uuid, link_class: "permission",
455 name: "can_read", head_uuid: @object.uuid)
456 rescue ArvadosApiClient::ApiError => error
457 error_list = error.api_response.andand[:errors]
458 if error_list.andand.any?
459 results["errors"] += error_list.map { |e| "#{shared_uuid}: #{e}" }
461 error_code = error.api_status || "Bad status"
462 results["errors"] << "#{shared_uuid}: #{error_code} response"
465 results["success"] << shared_uuid
468 if results["errors"].empty?
469 results.delete("errors")
475 f.json { render(json: results, status: status) }
479 helper_method :is_starred
481 links = Link.where(tail_uuid: current_user.uuid,
482 head_uuid: @object.uuid,
485 return links.andand.any?
490 helper_method :strip_token_from_path
491 def strip_token_from_path(path)
492 path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
495 def redirect_to_login
496 if request.xhr? or request.format.json?
497 @errors = ['You are not logged in. Most likely your session has timed out and you need to log in again.']
498 render_error status: 401
499 elsif request.method.in? ['GET', 'HEAD']
500 redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
502 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."
505 false # For convenience to return from callbacks
508 def using_specific_api_token(api_token, opts={})
510 [:arvados_api_token, :user].each do |key|
511 start_values[key] = Thread.current[key]
513 if opts.fetch(:load_user, true)
514 load_api_token(api_token)
516 Thread.current[:arvados_api_token] = api_token
517 Thread.current[:user] = nil
522 start_values.each_key { |key| Thread.current[key] = start_values[key] }
527 def accept_uuid_as_id_param
528 if params[:id] and params[:id].match /\D/
529 params[:uuid] = params.delete :id
533 def find_object_by_uuid
537 elsif params[:uuid].nil? or params[:uuid].empty?
539 elsif not params[:uuid].is_a?(String)
540 @object = model_class.where(uuid: params[:uuid]).first
541 elsif (model_class != Link and
542 resource_class_for_uuid(params[:uuid]) == Link)
543 @name_link = Link.find(params[:uuid])
544 @object = model_class.find(@name_link.head_uuid)
546 @object = model_class.find(params[:uuid])
547 load_preloaded_objects [@object]
549 rescue ArvadosApiClient::NotFoundException, ArvadosApiClient::NotLoggedInException, RuntimeError => error
550 if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
553 render_not_found(error)
560 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
562 Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
565 # Set up the thread with the given API token and associated user object.
566 def load_api_token(new_token)
567 Thread.current[:arvados_api_token] = new_token
569 Thread.current[:user] = nil
571 Thread.current[:user] = User.current
575 # If there's a valid api_token parameter, set up the session with that
576 # user's information. Return true if the method redirects the request
577 # (usually a post-login redirect); false otherwise.
578 def setup_user_session
579 return false unless params[:api_token]
580 Thread.current[:arvados_api_token] = params[:api_token]
583 rescue ArvadosApiClient::NotLoggedInException
584 false # We may redirect to login, or not, based on the current action.
586 session[:arvados_api_token] = params[:api_token]
587 # If we later have trouble contacting the API server, we still want
588 # to be able to render basic user information in the UI--see
589 # render_exception above. We store that in the session here. This is
590 # not intended to be used as a general-purpose cache. See #2891.
594 first_name: user.first_name,
595 last_name: user.last_name,
596 is_active: user.is_active,
597 is_admin: user.is_admin,
601 if !request.format.json? and request.method.in? ['GET', 'HEAD']
602 # Repeat this request with api_token in the (new) session
603 # cookie instead of the query string. This prevents API
604 # tokens from appearing in (and being inadvisedly copied
605 # and pasted from) browser Location bars.
606 redirect_to strip_token_from_path(request.fullpath)
612 Thread.current[:arvados_api_token] = nil
616 # Save the session API token in thread-local storage, and yield.
617 # This method also takes care of session setup if the request
618 # provides a valid api_token parameter.
619 # If a token is unavailable or expired, the block is still run, with
621 def set_thread_api_token
622 if Thread.current[:arvados_api_token]
623 yield # An API token has already been found - pass it through.
625 elsif setup_user_session
626 return # A new session was set up and received a response.
630 load_api_token(session[:arvados_api_token])
632 rescue ArvadosApiClient::NotLoggedInException
633 # If we got this error with a token, it must've expired.
634 # Retry the request without a token.
635 unless Thread.current[:arvados_api_token].nil?
640 # Remove token in case this Thread is used for anything else.
645 # Redirect to login/welcome if client provided expired API token (or
647 def require_thread_api_token
648 if Thread.current[:arvados_api_token]
650 elsif session[:arvados_api_token]
651 # Expired session. Clear it before refreshing login so that,
652 # if this login procedure fails, we end up showing the "please
653 # log in" page instead of getting stuck in a redirect loop.
654 session.delete :arvados_api_token
657 # If we redirect to the welcome page, the browser will handle
658 # the 302 by itself and the client code will end up rendering
659 # the "welcome" page in some content area where it doesn't make
660 # sense. Instead, we send 401 ("authenticate and try again" or
661 # "display error", depending on how smart the client side is).
662 @errors = ['You are not logged in.']
663 render_error status: 401
665 redirect_to welcome_users_path(return_to: request.fullpath)
669 def ensure_current_user_is_admin
671 @errors = ['Not logged in']
672 render_error status: 401
673 elsif not current_user.is_admin
674 @errors = ['Permission denied']
675 render_error status: 403
679 helper_method :unsigned_user_agreements
680 def unsigned_user_agreements
681 @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
682 @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
683 if not @signed_ua_uuids.index ua.uuid
684 Collection.find(ua.uuid)
689 def check_user_agreements
690 if current_user && !current_user.is_active
691 if not current_user.is_invited
692 return redirect_to inactive_users_path(return_to: request.fullpath)
694 if unsigned_user_agreements.empty?
695 # No agreements to sign. Perhaps we just need to ask?
696 current_user.activate
697 if !current_user.is_active
698 logger.warn "#{current_user.uuid.inspect}: " +
699 "No user agreements to sign, but activate failed!"
702 if !current_user.is_active
703 redirect_to user_agreements_path(return_to: request.fullpath)
709 def check_user_profile
710 return true if !current_user
711 if request.method.downcase != 'get' || params[:partial] ||
712 params[:tab_pane] || params[:action_method] ||
713 params[:action] == 'setup_popup'
717 if missing_required_profile?
718 redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
723 helper_method :missing_required_profile?
724 def missing_required_profile?
725 missing_required = false
727 profile_config = Rails.configuration.user_profile_form_fields
728 if current_user && profile_config
729 current_user_profile = current_user.prefs[:profile]
730 profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
732 if !current_user_profile ||
733 !current_user_profile[entry['key'].to_sym] ||
734 current_user_profile[entry['key'].to_sym].empty?
735 missing_required = true
746 return Rails.configuration.arvados_theme
749 @@notification_tests = []
751 @@notification_tests.push lambda { |controller, current_user|
752 return nil if Rails.configuration.shell_in_a_box_url
753 AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
756 return lambda { |view|
757 view.render partial: 'notifications/ssh_key_notification'
761 @@notification_tests.push lambda { |controller, current_user|
762 Collection.limit(1).where(created_by: current_user.uuid).each do
765 return lambda { |view|
766 view.render partial: 'notifications/collections_notification'
770 @@notification_tests.push lambda { |controller, current_user|
771 if PipelineInstance.api_exists?(:index)
772 PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
778 return lambda { |view|
779 view.render partial: 'notifications/pipelines_notification'
783 helper_method :user_notifications
784 def user_notifications
785 return [] if @errors or not current_user.andand.is_active or not Rails.configuration.show_user_notifications
786 @notifications ||= @@notification_tests.map do |t|
787 t.call(self, current_user)
791 helper_method :all_projects
793 @all_projects ||= Group.
794 filter([['group_class','=','project']]).order('name')
797 helper_method :my_projects
799 return @my_projects if @my_projects
802 all_projects.each do |g|
803 root_of[g.uuid] = g.owner_uuid
809 root_of = root_of.each_with_object({}) do |(child, parent), h|
811 h[child] = root_of[parent]
818 @my_projects = @my_projects.select do |g|
819 root_of[g.uuid] == current_user.uuid
823 helper_method :projects_shared_with_me
824 def projects_shared_with_me
825 my_project_uuids = my_projects.collect &:uuid
826 all_projects.reject { |x| x.uuid.in? my_project_uuids }
829 helper_method :recent_jobs_and_pipelines
830 def recent_jobs_and_pipelines
832 PipelineInstance.limit(10)).
834 (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
838 helper_method :running_pipelines
839 def running_pipelines
840 pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
843 pl.components.each do |k,v|
844 if v.is_a? Hash and v[:job]
845 jobs[v[:job][:uuid]] = {}
851 Job.filter([["uuid", "in", jobs.keys]]).each do |j|
856 pl.components.each do |k,v|
857 if v.is_a? Hash and v[:job]
858 v[:job] = jobs[v[:job][:uuid]]
867 helper_method :recent_processes
868 def recent_processes lim
872 if PipelineInstance.api_exists?(:index)
873 cols = %w(uuid owner_uuid created_at modified_at pipeline_template_uuid name state started_at finished_at)
874 pipelines = PipelineInstance.select(cols).limit(lim).order(["created_at desc"])
875 pipelines.results.each { |pi| procs[pi] = pi.created_at }
878 crs = ContainerRequest.limit(lim).order(["created_at desc"]).filter([["requesting_container_uuid", "=", nil]])
879 crs.results.each { |c| procs[c] = c.created_at }
881 Hash[procs.sort_by {|key, value| value}].keys.reverse.first(lim)
884 helper_method :recent_collections
885 def recent_collections lim
886 c = Collection.limit(lim).order(["modified_at desc"]).results
888 Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
891 {collections: c, owners: own}
894 helper_method :my_starred_projects
895 def my_starred_projects user
896 return if @starred_projects
897 links = Link.filter([['tail_uuid', '=', user.uuid],
898 ['link_class', '=', 'star'],
899 ['head_uuid', 'is_a', 'arvados#group']]).select(%w(head_uuid))
900 uuids = links.collect { |x| x.head_uuid }
901 starred_projects = Group.filter([['uuid', 'in', uuids]]).order('name')
902 @starred_projects = starred_projects.results
905 # If there are more than 200 projects that are readable by the user,
906 # build the tree using only the top 200+ projects owned by the user,
907 # from the top three levels.
908 # That is: get toplevel projects under home, get subprojects of
909 # these projects, and so on until we hit the limit.
910 def my_wanted_projects user, page_size=100
911 return @my_wanted_projects if @my_wanted_projects
916 @too_many_projects = false
917 @reached_level_limit = false
918 while from_top.size <= page_size*2
919 current_level = Group.filter([['group_class','=','project'],
920 ['owner_uuid', 'in', uuids]])
921 .order('name').limit(page_size*2)
922 break if current_level.results.size == 0
923 @too_many_projects = true if current_level.items_available > current_level.results.size
924 from_top.concat current_level.results
925 uuids = current_level.results.collect { |x| x.uuid }
928 @reached_level_limit = true
932 @my_wanted_projects = from_top
935 helper_method :my_wanted_projects_tree
936 def my_wanted_projects_tree user, page_size=100
937 build_my_wanted_projects_tree user, page_size
938 [@my_wanted_projects_tree, @too_many_projects, @reached_level_limit]
941 def build_my_wanted_projects_tree user, page_size=100
942 return @my_wanted_projects_tree if @my_wanted_projects_tree
944 parent_of = {user.uuid => 'me'}
945 my_wanted_projects(user, page_size).each do |ob|
946 parent_of[ob.uuid] = ob.owner_uuid
948 children_of = {false => [], 'me' => [user]}
949 my_wanted_projects(user, page_size).each do |ob|
950 if ob.owner_uuid != user.uuid and
951 not parent_of.has_key? ob.owner_uuid
952 parent_of[ob.uuid] = false
954 children_of[parent_of[ob.uuid]] ||= []
955 children_of[parent_of[ob.uuid]] << ob
957 buildtree = lambda do |children_of, root_uuid=false|
959 children_of[root_uuid].andand.each do |ob|
960 tree[ob] = buildtree.call(children_of, ob.uuid)
964 sorted_paths = lambda do |tree, depth=0|
966 tree.keys.sort_by { |ob|
967 ob.is_a?(String) ? ob : ob.friendly_link_name
969 paths << {object: ob, depth: depth}
970 paths += sorted_paths.call tree[ob], depth+1
974 @my_wanted_projects_tree =
975 sorted_paths.call buildtree.call(children_of, 'me')
978 helper_method :get_object
980 if @get_object.nil? and @objects
981 @get_object = @objects.each_with_object({}) do |object, h|
982 h[object.uuid] = object
989 helper_method :project_breadcrumbs
990 def project_breadcrumbs
992 current = @name_link || @object
994 # Halt if a group ownership loop is detected. API should refuse
995 # to produce this state, but it could still arise from a race
996 # condition when group ownership changes between our find()
998 break if crumbs.collect(&:uuid).include? current.uuid
1000 if current.is_a?(Group) and current.group_class == 'project'
1001 crumbs.prepend current
1003 if current.is_a? Link
1004 current = Group.find?(current.tail_uuid)
1006 current = Group.find?(current.owner_uuid)
1012 helper_method :current_project_uuid
1013 def current_project_uuid
1014 if @object.is_a? Group and @object.group_class == 'project'
1016 elsif @name_link.andand.tail_uuid
1017 @name_link.tail_uuid
1018 elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
1025 # helper method to get links for given object or uuid
1026 helper_method :links_for_object
1027 def links_for_object object_or_uuid
1028 raise ArgumentError, 'No input argument' unless object_or_uuid
1029 preload_links_for_objects([object_or_uuid])
1030 uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
1031 @all_links_for[uuid] ||= []
1034 # helper method to preload links for given objects and uuids
1035 helper_method :preload_links_for_objects
1036 def preload_links_for_objects objects_and_uuids
1037 @all_links_for ||= {}
1039 raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
1040 return @all_links_for if objects_and_uuids.empty?
1042 uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
1044 # if already preloaded for all of these uuids, return
1045 if not uuids.select { |x| @all_links_for[x].nil? }.any?
1046 return @all_links_for
1050 @all_links_for[x] = []
1053 # TODO: make sure we get every page of results from API server
1054 Link.filter([['head_uuid', 'in', uuids]]).each do |link|
1055 @all_links_for[link.head_uuid] << link
1060 # helper method to get a certain number of objects of a specific type
1061 # this can be used to replace any uses of: "dataclass.limit(n)"
1062 helper_method :get_n_objects_of_class
1063 def get_n_objects_of_class dataclass, size
1064 @objects_map_for ||= {}
1066 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
1067 raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
1069 # if the objects_map_for has a value for this dataclass, and the
1070 # size used to retrieve those objects is equal, return it
1071 size_key = "#{dataclass.name}_size"
1072 if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
1073 (@objects_map_for[size_key] == size)
1074 return @objects_map_for[dataclass.name]
1077 @objects_map_for[size_key] = size
1078 @objects_map_for[dataclass.name] = dataclass.limit(size)
1081 # helper method to get collections for the given uuid
1082 helper_method :collections_for_object
1083 def collections_for_object uuid
1084 raise ArgumentError, 'No input argument' unless uuid
1085 preload_collections_for_objects([uuid])
1086 @all_collections_for[uuid] ||= []
1089 # helper method to preload collections for the given uuids
1090 helper_method :preload_collections_for_objects
1091 def preload_collections_for_objects uuids
1092 @all_collections_for ||= {}
1094 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1095 return @all_collections_for if uuids.empty?
1097 # if already preloaded for all of these uuids, return
1098 if not uuids.select { |x| @all_collections_for[x].nil? }.any?
1099 return @all_collections_for
1103 @all_collections_for[x] = []
1106 # TODO: make sure we get every page of results from API server
1107 Collection.where(uuid: uuids).each do |collection|
1108 @all_collections_for[collection.uuid] << collection
1110 @all_collections_for
1113 # helper method to get log collections for the given log
1114 helper_method :log_collections_for_object
1115 def log_collections_for_object log
1116 raise ArgumentError, 'No input argument' unless log
1118 preload_log_collections_for_objects([log])
1121 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1122 if fixup && fixup.size>1
1126 @all_log_collections_for[uuid] ||= []
1129 # helper method to preload collections for the given uuids
1130 helper_method :preload_log_collections_for_objects
1131 def preload_log_collections_for_objects logs
1132 @all_log_collections_for ||= {}
1134 raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
1135 return @all_log_collections_for if logs.empty?
1139 fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
1140 if fixup && fixup.size>1
1147 # if already preloaded for all of these uuids, return
1148 if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1149 return @all_log_collections_for
1153 @all_log_collections_for[x] = []
1156 # TODO: make sure we get every page of results from API server
1157 Collection.where(uuid: uuids).each do |collection|
1158 @all_log_collections_for[collection.uuid] << collection
1160 @all_log_collections_for
1163 # Helper method to get one collection for the given portable_data_hash
1164 # This is used to determine if a pdh is readable by the current_user
1165 helper_method :collection_for_pdh
1166 def collection_for_pdh pdh
1167 raise ArgumentError, 'No input argument' unless pdh
1168 preload_for_pdhs([pdh])
1169 @all_pdhs_for[pdh] ||= []
1172 # Helper method to preload one collection each for the given pdhs
1173 # This is used to determine if a pdh is readable by the current_user
1174 helper_method :preload_for_pdhs
1175 def preload_for_pdhs pdhs
1176 @all_pdhs_for ||= {}
1178 raise ArgumentError, 'Argument is not an array' unless pdhs.is_a? Array
1179 return @all_pdhs_for if pdhs.empty?
1181 # if already preloaded for all of these pdhs, return
1182 if not pdhs.select { |x| @all_pdhs_for[x].nil? }.any?
1183 return @all_pdhs_for
1187 @all_pdhs_for[x] = []
1190 Collection.select(%w(portable_data_hash)).where(portable_data_hash: pdhs).distinct().each do |collection|
1191 @all_pdhs_for[collection.portable_data_hash] << collection
1196 # helper method to get object of a given dataclass and uuid
1197 helper_method :object_for_dataclass
1198 def object_for_dataclass dataclass, uuid, by_attr=nil
1199 raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1200 preload_objects_for_dataclass(dataclass, [uuid], by_attr)
1204 # helper method to preload objects for given dataclass and uuids
1205 helper_method :preload_objects_for_dataclass
1206 def preload_objects_for_dataclass dataclass, uuids, by_attr=nil
1209 raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1210 raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1212 return @objects_for if uuids.empty?
1214 # if already preloaded for all of these uuids, return
1215 if not uuids.select { |x| !@objects_for.include?(x) }.any?
1219 # preset all uuids to nil
1221 @objects_for[x] = nil
1223 if by_attr and ![:uuid, :name].include?(by_attr)
1224 raise ArgumentError, "Preloading only using lookups by uuid or name are supported: #{by_attr}"
1225 elsif by_attr and by_attr == :name
1226 dataclass.where(name: uuids).each do |obj|
1227 @objects_for[obj.name] = obj
1230 dataclass.where(uuid: uuids).each do |obj|
1231 @objects_for[obj.uuid] = obj
1237 # helper method to load objects that are already preloaded
1238 helper_method :load_preloaded_objects
1239 def load_preloaded_objects objs
1242 @objects_for[obj.uuid] = obj
1246 def wiselinks_layout
1250 def set_current_request_id
1251 # Request ID format: '<timestamp>-<9_digits_random_number>'
1252 current_request_id = "#{Time.new.to_i}-#{sprintf('%09d', rand(0..10**9-1))}"
1253 Thread.current[:current_request_id] = current_request_id