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