Merge branch 'master' into 3140-project-content-tabs
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3   include ApplicationHelper
4
5   respond_to :html, :json, :js
6   protect_from_forgery
7
8   ERROR_ACTIONS = [:render_error, :render_not_found]
9
10   around_filter :thread_clear
11   around_filter :set_thread_api_token
12   # Methods that don't require login should
13   #   skip_around_filter :require_thread_api_token
14   around_filter :require_thread_api_token, except: ERROR_ACTIONS
15   before_filter :check_user_agreements, except: ERROR_ACTIONS
16   before_filter :check_user_notifications, except: ERROR_ACTIONS
17   before_filter :find_object_by_uuid, except: [:index, :choose] + ERROR_ACTIONS
18   theme :select_theme
19
20   begin
21     rescue_from(ActiveRecord::RecordNotFound,
22                 ActionController::RoutingError,
23                 ActionController::UnknownController,
24                 AbstractController::ActionNotFound,
25                 with: :render_not_found)
26     rescue_from(Exception,
27                 ActionController::UrlGenerationError,
28                 with: :render_exception)
29   end
30
31   def unprocessable(message=nil)
32     @errors ||= []
33
34     @errors << message if message
35     render_error status: 422
36   end
37
38   def render_error(opts={})
39     opts[:status] ||= 500
40     respond_to do |f|
41       # json must come before html here, so it gets used as the
42       # default format when js is requested by the client. This lets
43       # ajax:error callback parse the response correctly, even though
44       # the browser can't.
45       f.json { render opts.merge(json: {success: false, errors: @errors}) }
46       f.html { render({action: 'error'}.merge(opts)) }
47     end
48   end
49
50   def render_exception(e)
51     logger.error e.inspect
52     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
53     err_opts = {status: 422}
54     if e.is_a?(ArvadosApiClient::ApiError)
55       err_opts.merge!(action: 'api_error', locals: {api_error: e})
56       @errors = e.api_response[:errors]
57     elsif @object.andand.errors.andand.full_messages.andand.any?
58       @errors = @object.errors.full_messages
59     else
60       @errors = [e.to_s]
61     end
62     # If the user has an active session, and the API server is available,
63     # make user information available on the error page.
64     begin
65       load_api_token(session[:arvados_api_token])
66     rescue ArvadosApiClient::ApiError
67       load_api_token(nil)
68     end
69     # Preload projects trees for the template.  If that fails, set empty
70     # trees so error page rendering can proceed.  (It's easier to rescue the
71     # exception here than in a template.)
72     begin
73       build_project_trees
74     rescue ArvadosApiClient::ApiError
75       @my_project_tree ||= []
76       @shared_project_tree ||= []
77     end
78     render_error(err_opts)
79   end
80
81   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
82     logger.error e.inspect
83     @errors = ["Path not found"]
84     set_thread_api_token do
85       self.render_error(action: '404', status: 404)
86     end
87   end
88
89   def find_objects_for_index
90     @limit ||= 200
91     if params[:limit]
92       @limit = params[:limit].to_i
93     end
94
95     @offset ||= 0
96     if params[:offset]
97       @offset = params[:offset].to_i
98     end
99
100     @filters ||= []
101     if params[:filters]
102       filters = params[:filters]
103       if filters.is_a? String
104         filters = Oj.load filters
105       end
106       @filters += filters
107     end
108
109     @objects ||= model_class
110     @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
111   end
112
113   def render_index
114     respond_to do |f|
115       f.json { render json: @objects }
116       f.html {
117         if params['tab_pane']
118           comparable = self.respond_to? :compare
119           render(partial: 'show_' + params['tab_pane'].downcase,
120                  locals: { comparable: comparable, objects: @objects })
121         else
122           render
123         end
124       }
125       f.js { render }
126     end
127   end
128
129   def index
130     find_objects_for_index if !@objects
131     render_index
132   end
133
134   helper_method :next_page_offset
135   def next_page_offset objects=nil
136     if !objects
137       objects = @objects
138     end
139     if objects.respond_to?(:result_offset) and
140         objects.respond_to?(:result_limit) and
141         objects.respond_to?(:items_available)
142       next_offset = objects.result_offset + objects.result_limit
143       if next_offset < objects.items_available
144         next_offset
145       else
146         nil
147       end
148     end
149   end
150
151   def show
152     if !@object
153       return render_not_found("object not found")
154     end
155     respond_to do |f|
156       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
157       f.html {
158         if params['tab_pane']
159           comparable = self.respond_to? :compare
160           render(partial: 'show_' + params['tab_pane'].downcase,
161                  locals: { comparable: comparable, objects: @objects })
162         elsif request.method.in? ['GET', 'HEAD']
163           render
164         else
165           redirect_to params[:return_to] || @object
166         end
167       }
168       f.js { render }
169     end
170   end
171
172   def choose
173     params[:limit] ||= 40
174     if !@objects
175       if params[:project_uuid] and !params[:project_uuid].empty?
176         # We want the chooser to show objects of the controllers's model_class
177         # type within a specific project specified by project_uuid, so fetch the
178         # project and request the contents of the project filtered on the
179         # controllers's model_class kind.
180         @objects = Group.find(params[:project_uuid]).contents({:filters => [['uuid', 'is_a', "arvados\##{ArvadosApiClient.class_kind(model_class)}"]]})
181       end
182       find_objects_for_index if !@objects
183     end
184     respond_to do |f|
185       if params[:partial]
186         f.json {
187           render json: {
188             content: render_to_string(partial: "choose_rows.html",
189                                       formats: [:html],
190                                       locals: {
191                                         multiple: params[:multiple]
192                                       }),
193             next_page_href: @next_page_href
194           }
195         }
196       end
197       f.js {
198         render partial: 'choose', locals: {multiple: params[:multiple]}
199       }
200     end
201   end
202
203   def render_content
204     if !@object
205       return render_not_found("object not found")
206     end
207   end
208
209   def new
210     @object = model_class.new
211   end
212
213   def update
214     @updates ||= params[@object.resource_param_name.to_sym]
215     @updates.keys.each do |attr|
216       if @object.send(attr).is_a? Hash
217         if @updates[attr].is_a? String
218           @updates[attr] = Oj.load @updates[attr]
219         end
220         if params[:merge] || params["merge_#{attr}".to_sym]
221           # Merge provided Hash with current Hash, instead of
222           # replacing.
223           @updates[attr] = @object.send(attr).with_indifferent_access.
224             deep_merge(@updates[attr].with_indifferent_access)
225         end
226       end
227     end
228     if @object.update_attributes @updates
229       show
230     else
231       self.render_error status: 422
232     end
233   end
234
235   def create
236     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
237     @new_resource_attrs ||= {}
238     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
239     @object ||= model_class.new @new_resource_attrs, params["options"]
240     if @object.save
241       respond_to do |f|
242         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
243         f.html {
244           redirect_to @object
245         }
246         f.js { render }
247       end
248     else
249       self.render_error status: 422
250     end
251   end
252
253   # Clone the given object, merging any attribute values supplied as
254   # with a create action.
255   def copy
256     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
257     @new_resource_attrs ||= {}
258     @object = @object.dup
259     @object.update_attributes @new_resource_attrs
260     if not @new_resource_attrs[:name] and @object.respond_to? :name
261       if @object.name and @object.name != ''
262         @object.name = "Copy of #{@object.name}"
263       else
264         @object.name = "Copy of unnamed #{@object.class_for_display.downcase}"
265       end
266     end
267     @object.save!
268     show
269   end
270
271   def destroy
272     if @object.destroy
273       respond_to do |f|
274         f.json { render json: @object }
275         f.html {
276           redirect_to(params[:return_to] || :back)
277         }
278         f.js { render }
279       end
280     else
281       self.render_error status: 422
282     end
283   end
284
285   def current_user
286     Thread.current[:user]
287   end
288
289   def model_class
290     controller_name.classify.constantize
291   end
292
293   def breadcrumb_page_name
294     (@breadcrumb_page_name ||
295      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
296      action_name)
297   end
298
299   def index_pane_list
300     %w(Recent)
301   end
302
303   def show_pane_list
304     %w(Attributes Advanced)
305   end
306
307   protected
308
309   def strip_token_from_path(path)
310     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
311   end
312
313   def redirect_to_login
314     respond_to do |f|
315       f.html {
316         if request.method.in? ['GET', 'HEAD']
317           redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
318         else
319           flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
320           redirect_to :back
321         end
322       }
323       f.json {
324         @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
325         self.render_error status: 422
326       }
327     end
328     false  # For convenience to return from callbacks
329   end
330
331   def using_specific_api_token(api_token)
332     start_values = {}
333     [:arvados_api_token, :user].each do |key|
334       start_values[key] = Thread.current[key]
335     end
336     load_api_token(api_token)
337     begin
338       yield
339     ensure
340       start_values.each_key { |key| Thread.current[key] = start_values[key] }
341     end
342   end
343
344   def find_object_by_uuid
345     if params[:id] and params[:id].match /\D/
346       params[:uuid] = params.delete :id
347     end
348     begin
349       if not model_class
350         @object = nil
351       elsif not params[:uuid].is_a?(String)
352         @object = model_class.where(uuid: params[:uuid]).first
353       elsif params[:uuid].empty?
354         @object = nil
355       elsif (model_class != Link and
356              resource_class_for_uuid(params[:uuid]) == Link)
357         @name_link = Link.find(params[:uuid])
358         @object = model_class.find(@name_link.head_uuid)
359       else
360         @object = model_class.find(params[:uuid])
361       end
362     rescue ArvadosApiClient::NotFoundException, RuntimeError => error
363       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
364         raise
365       end
366       render_not_found(error)
367       return false
368     end
369   end
370
371   def thread_clear
372     load_api_token(nil)
373     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
374     yield
375     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
376   end
377
378   # Set up the thread with the given API token and associated user object.
379   def load_api_token(new_token)
380     Thread.current[:arvados_api_token] = new_token
381     if new_token.nil?
382       Thread.current[:user] = nil
383     elsif (new_token == session[:arvados_api_token]) and
384         session[:user].andand[:is_active]
385       Thread.current[:user] = User.new(session[:user])
386     else
387       Thread.current[:user] = User.current
388     end
389   end
390
391   # If there's a valid api_token parameter, set up the session with that
392   # user's information.  Return true if the method redirects the request
393   # (usually a post-login redirect); false otherwise.
394   def setup_user_session
395     return false unless params[:api_token]
396     Thread.current[:arvados_api_token] = params[:api_token]
397     begin
398       user = User.current
399     rescue ArvadosApiClient::NotLoggedInException
400       false  # We may redirect to login, or not, based on the current action.
401     else
402       session[:arvados_api_token] = params[:api_token]
403       session[:user] = {
404         uuid: user.uuid,
405         email: user.email,
406         first_name: user.first_name,
407         last_name: user.last_name,
408         is_active: user.is_active,
409         is_admin: user.is_admin,
410         prefs: user.prefs
411       }
412       if !request.format.json? and request.method.in? ['GET', 'HEAD']
413         # Repeat this request with api_token in the (new) session
414         # cookie instead of the query string.  This prevents API
415         # tokens from appearing in (and being inadvisedly copied
416         # and pasted from) browser Location bars.
417         redirect_to strip_token_from_path(request.fullpath)
418         true
419       else
420         false
421       end
422     ensure
423       Thread.current[:arvados_api_token] = nil
424     end
425   end
426
427   # Save the session API token in thread-local storage, and yield.
428   # This method also takes care of session setup if the request
429   # provides a valid api_token parameter.
430   # If a token is unavailable or expired, the block is still run, with
431   # a nil token.
432   def set_thread_api_token
433     if Thread.current[:arvados_api_token]
434       yield   # An API token has already been found - pass it through.
435       return
436     elsif setup_user_session
437       return  # A new session was set up and received a response.
438     end
439
440     begin
441       load_api_token(session[:arvados_api_token])
442       yield
443     rescue ArvadosApiClient::NotLoggedInException
444       # If we got this error with a token, it must've expired.
445       # Retry the request without a token.
446       unless Thread.current[:arvados_api_token].nil?
447         load_api_token(nil)
448         yield
449       end
450     ensure
451       # Remove token in case this Thread is used for anything else.
452       load_api_token(nil)
453     end
454   end
455
456   # Reroute this request if an API token is unavailable.
457   def require_thread_api_token
458     if Thread.current[:arvados_api_token]
459       yield
460     elsif session[:arvados_api_token]
461       # Expired session. Clear it before refreshing login so that,
462       # if this login procedure fails, we end up showing the "please
463       # log in" page instead of getting stuck in a redirect loop.
464       session.delete :arvados_api_token
465       redirect_to_login
466     else
467       render 'users/welcome'
468     end
469   end
470
471   def ensure_current_user_is_admin
472     unless current_user and current_user.is_admin
473       @errors = ['Permission denied']
474       self.render_error status: 401
475     end
476   end
477
478   def check_user_agreements
479     if current_user && !current_user.is_active
480       if not current_user.is_invited
481         return render 'users/inactive'
482       end
483       signatures = UserAgreement.signatures
484       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
485       @required_user_agreements = UserAgreement.all.map do |ua|
486         if not @signed_ua_uuids.index ua.uuid
487           Collection.find(ua.uuid)
488         end
489       end.compact
490       if @required_user_agreements.empty?
491         # No agreements to sign. Perhaps we just need to ask?
492         current_user.activate
493         if !current_user.is_active
494           logger.warn "#{current_user.uuid.inspect}: " +
495             "No user agreements to sign, but activate failed!"
496         end
497       end
498       if !current_user.is_active
499         render 'user_agreements/index'
500       end
501     end
502     true
503   end
504
505   def select_theme
506     return Rails.configuration.arvados_theme
507   end
508
509   @@notification_tests = []
510
511   @@notification_tests.push lambda { |controller, current_user|
512     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
513       return nil
514     end
515     return lambda { |view|
516       view.render partial: 'notifications/ssh_key_notification'
517     }
518   }
519
520   #@@notification_tests.push lambda { |controller, current_user|
521   #  Job.limit(1).where(created_by: current_user.uuid).each do
522   #    return nil
523   #  end
524   #  return lambda { |view|
525   #    view.render partial: 'notifications/jobs_notification'
526   #  }
527   #}
528
529   @@notification_tests.push lambda { |controller, current_user|
530     Collection.limit(1).where(created_by: current_user.uuid).each do
531       return nil
532     end
533     return lambda { |view|
534       view.render partial: 'notifications/collections_notification'
535     }
536   }
537
538   @@notification_tests.push lambda { |controller, current_user|
539     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
540       return nil
541     end
542     return lambda { |view|
543       view.render partial: 'notifications/pipelines_notification'
544     }
545   }
546
547   def check_user_notifications
548     return if params['tab_pane']
549
550     @notification_count = 0
551     @notifications = []
552
553     if current_user
554       @showallalerts = false
555       @@notification_tests.each do |t|
556         a = t.call(self, current_user)
557         if a
558           @notification_count += 1
559           @notifications.push a
560         end
561       end
562     end
563
564     if @notification_count == 0
565       @notification_count = ''
566     end
567   end
568
569   helper_method :all_projects
570   def all_projects
571     @all_projects ||= Group.
572       filter([['group_class','in',['project','folder']]]).order('name')
573   end
574
575   helper_method :my_projects
576   def my_projects
577     return @my_projects if @my_projects
578     @my_projects = []
579     root_of = {}
580     all_projects.each do |g|
581       root_of[g.uuid] = g.owner_uuid
582       @my_projects << g
583     end
584     done = false
585     while not done
586       done = true
587       root_of = root_of.each_with_object({}) do |(child, parent), h|
588         if root_of[parent]
589           h[child] = root_of[parent]
590           done = false
591         else
592           h[child] = parent
593         end
594       end
595     end
596     @my_projects = @my_projects.select do |g|
597       root_of[g.uuid] == current_user.uuid
598     end
599   end
600
601   helper_method :projects_shared_with_me
602   def projects_shared_with_me
603     my_project_uuids = my_projects.collect &:uuid
604     all_projects.reject { |x| x.uuid.in? my_project_uuids }
605   end
606
607   helper_method :recent_jobs_and_pipelines
608   def recent_jobs_and_pipelines
609     (Job.limit(10) |
610      PipelineInstance.limit(10)).
611       sort_by do |x|
612       x.finished_at || x.started_at || x.created_at rescue x.created_at
613     end
614   end
615
616   helper_method :my_project_tree
617   def my_project_tree
618     build_project_trees
619     @my_project_tree
620   end
621
622   helper_method :shared_project_tree
623   def shared_project_tree
624     build_project_trees
625     @shared_project_tree
626   end
627
628   def build_project_trees
629     return if @my_project_tree and @shared_project_tree
630     parent_of = {current_user.uuid => 'me'}
631     all_projects.each do |ob|
632       parent_of[ob.uuid] = ob.owner_uuid
633     end
634     children_of = {false => [], 'me' => [current_user]}
635     all_projects.each do |ob|
636       if ob.owner_uuid != current_user.uuid and
637           not parent_of.has_key? ob.owner_uuid
638         parent_of[ob.uuid] = false
639       end
640       children_of[parent_of[ob.uuid]] ||= []
641       children_of[parent_of[ob.uuid]] << ob
642     end
643     buildtree = lambda do |children_of, root_uuid=false|
644       tree = {}
645       children_of[root_uuid].andand.each do |ob|
646         tree[ob] = buildtree.call(children_of, ob.uuid)
647       end
648       tree
649     end
650     sorted_paths = lambda do |tree, depth=0|
651       paths = []
652       tree.keys.sort_by { |ob|
653         ob.is_a?(String) ? ob : ob.friendly_link_name
654       }.each do |ob|
655         paths << {object: ob, depth: depth}
656         paths += sorted_paths.call tree[ob], depth+1
657       end
658       paths
659     end
660     @my_project_tree =
661       sorted_paths.call buildtree.call(children_of, 'me')
662     @shared_project_tree =
663       sorted_paths.call({'Shared with me' =>
664                           buildtree.call(children_of, false)})
665   end
666
667   helper_method :get_object
668   def get_object uuid
669     if @get_object.nil? and @objects
670       @get_object = @objects.each_with_object({}) do |object, h|
671         h[object.uuid] = object
672       end
673     end
674     @get_object ||= {}
675     @get_object[uuid]
676   end
677
678   helper_method :project_breadcrumbs
679   def project_breadcrumbs
680     crumbs = []
681     current = @name_link || @object
682     while current
683       if current.is_a?(Group) and current.group_class.in?(['project','folder'])
684         crumbs.prepend current
685       end
686       if current.is_a? Link
687         current = Group.find?(current.tail_uuid)
688       else
689         current = Group.find?(current.owner_uuid)
690       end
691     end
692     crumbs
693   end
694
695   helper_method :current_project_uuid
696   def current_project_uuid
697     if @object.is_a? Group and @object.group_class.in?(['project','folder'])
698       @object.uuid
699     elsif @name_link.andand.tail_uuid
700       @name_link.tail_uuid
701     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
702       @object.owner_uuid
703     else
704       nil
705     end
706   end
707
708   # helper method to get links for given object or uuid
709   helper_method :links_for_object
710   def links_for_object object_or_uuid
711     raise ArgumentError, 'No input argument' unless object_or_uuid
712     preload_links_for_objects([object_or_uuid])
713     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
714     @all_links_for[uuid] ||= []
715   end
716
717   # helper method to preload links for given objects and uuids
718   helper_method :preload_links_for_objects
719   def preload_links_for_objects objects_and_uuids
720     @all_links_for ||= {}
721
722     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
723     return @all_links_for if objects_and_uuids.empty?
724
725     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
726
727     # if already preloaded for all of these uuids, return
728     if not uuids.select { |x| @all_links_for[x].nil? }.any?
729       return @all_links_for
730     end
731
732     uuids.each do |x|
733       @all_links_for[x] = []
734     end
735
736     # TODO: make sure we get every page of results from API server
737     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
738       @all_links_for[link.head_uuid] << link
739     end
740     @all_links_for
741   end
742
743   # helper method to get a certain number of objects of a specific type
744   # this can be used to replace any uses of: "dataclass.limit(n)"
745   helper_method :get_n_objects_of_class
746   def get_n_objects_of_class dataclass, size
747     @objects_map_for ||= {}
748
749     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
750     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
751
752     # if the objects_map_for has a value for this dataclass, and the
753     # size used to retrieve those objects is equal, return it
754     size_key = "#{dataclass.name}_size"
755     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
756         (@objects_map_for[size_key] == size)
757       return @objects_map_for[dataclass.name]
758     end
759
760     @objects_map_for[size_key] = size
761     @objects_map_for[dataclass.name] = dataclass.limit(size)
762   end
763
764   # helper method to get collections for the given uuid
765   helper_method :collections_for_object
766   def collections_for_object uuid
767     raise ArgumentError, 'No input argument' unless uuid
768     preload_collections_for_objects([uuid])
769     @all_collections_for[uuid] ||= []
770   end
771
772   # helper method to preload collections for the given uuids
773   helper_method :preload_collections_for_objects
774   def preload_collections_for_objects uuids
775     @all_collections_for ||= {}
776
777     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
778     return @all_collections_for if uuids.empty?
779
780     # if already preloaded for all of these uuids, return
781     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
782       return @all_collections_for
783     end
784
785     uuids.each do |x|
786       @all_collections_for[x] = []
787     end
788
789     # TODO: make sure we get every page of results from API server
790     Collection.where(uuid: uuids).each do |collection|
791       @all_collections_for[collection.uuid] << collection
792     end
793     @all_collections_for
794   end
795
796   # helper method to get log collections for the given log
797   helper_method :log_collections_for_object
798   def log_collections_for_object log
799     raise ArgumentError, 'No input argument' unless log
800
801     preload_log_collections_for_objects([log])
802
803     uuid = log
804     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
805     if fixup && fixup.size>1
806       uuid = fixup[1]
807     end
808
809     @all_log_collections_for[uuid] ||= []
810   end
811
812   # helper method to preload collections for the given uuids
813   helper_method :preload_log_collections_for_objects
814   def preload_log_collections_for_objects logs
815     @all_log_collections_for ||= {}
816
817     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
818     return @all_log_collections_for if logs.empty?
819
820     uuids = []
821     logs.each do |log|
822       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
823       if fixup && fixup.size>1
824         uuids << fixup[1]
825       else
826         uuids << log
827       end
828     end
829
830     # if already preloaded for all of these uuids, return
831     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
832       return @all_log_collections_for
833     end
834
835     uuids.each do |x|
836       @all_log_collections_for[x] = []
837     end
838
839     # TODO: make sure we get every page of results from API server
840     Collection.where(uuid: uuids).each do |collection|
841       @all_log_collections_for[collection.uuid] << collection
842     end
843     @all_log_collections_for
844   end
845
846   # helper method to get object of a given dataclass and uuid
847   helper_method :object_for_dataclass
848   def object_for_dataclass dataclass, uuid
849     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
850     preload_objects_for_dataclass(dataclass, [uuid])
851     @objects_for[uuid]
852   end
853
854   # helper method to preload objects for given dataclass and uuids
855   helper_method :preload_objects_for_dataclass
856   def preload_objects_for_dataclass dataclass, uuids
857     @objects_for ||= {}
858
859     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
860     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
861
862     return @objects_for if uuids.empty?
863
864     # if already preloaded for all of these uuids, return
865     if not uuids.select { |x| @objects_for[x].nil? }.any?
866       return @objects_for
867     end
868
869     dataclass.where(uuid: uuids).each do |obj|
870       @objects_for[obj.uuid] = obj
871     end
872     @objects_for
873   end
874
875 end