4024: add search filter to pipeline instances page.
[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 :set_cache_buster
16   before_filter :accept_uuid_as_id_param, except: ERROR_ACTIONS
17   before_filter :check_user_agreements, except: ERROR_ACTIONS
18   before_filter :check_user_profile, except: ERROR_ACTIONS
19   before_filter :check_user_notifications, 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
22   theme :select_theme
23
24   begin
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)
33   end
34
35   def set_cache_buster
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"
39   end
40
41   def unprocessable(message=nil)
42     @errors ||= []
43
44     @errors << message if message
45     render_error status: 422
46   end
47
48   def render_error(opts={})
49     opts[:status] ||= 500
50     respond_to do |f|
51       # json must come before html here, so it gets used as the
52       # default format when js is requested by the client. This lets
53       # ajax:error callback parse the response correctly, even though
54       # the browser can't.
55       f.json { render opts.merge(json: {success: false, errors: @errors}) }
56       f.html { render({action: 'error'}.merge(opts)) }
57     end
58   end
59
60   def render_exception(e)
61     logger.error e.inspect
62     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
63     err_opts = {status: 422}
64     if e.is_a?(ArvadosApiClient::ApiError)
65       err_opts.merge!(action: 'api_error', locals: {api_error: e})
66       @errors = e.api_response[:errors]
67     elsif @object.andand.errors.andand.full_messages.andand.any?
68       @errors = @object.errors.full_messages
69     else
70       @errors = [e.to_s]
71     end
72     # Make user information available on the error page, falling back to the
73     # session cache if the API server is unavailable.
74     begin
75       load_api_token(session[:arvados_api_token])
76     rescue ArvadosApiClient::ApiError
77       unless session[:user].nil?
78         begin
79           Thread.current[:user] = User.new(session[:user])
80         rescue ArvadosApiClient::ApiError
81           # This can happen if User's columns are unavailable.  Nothing to do.
82         end
83       end
84     end
85     # Preload projects trees for the template.  If that's not doable, set empty
86     # trees so error page rendering can proceed.  (It's easier to rescue the
87     # exception here than in a template.)
88     unless current_user.nil?
89       begin
90         build_project_trees
91       rescue ArvadosApiClient::ApiError
92         # Fall back to the default-setting code later.
93       end
94     end
95     @my_project_tree ||= []
96     @shared_project_tree ||= []
97     render_error(err_opts)
98   end
99
100   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
101     logger.error e.inspect
102     @errors = ["Path not found"]
103     set_thread_api_token do
104       self.render_error(action: '404', status: 404)
105     end
106   end
107
108   # params[:order]:
109   #
110   # The order can be left empty to allow it to default.
111   # Or it can be a comma separated list of real database column names, one per model.
112   # Column names should always be qualified by a table name and a direction is optional, defaulting to asc
113   # (e.g. "collections.name" or "collections.name desc").
114   # If a column name is specified, that table will be sorted by that column.
115   # If there are objects from different models that will be shown (such as in Jobs and Pipelines tab),
116   # 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")
117   # Currently only one sort column name and direction can be specified for each model.
118   def load_filters_and_paging_params
119     if params[:order].blank?
120       @order = 'created_at desc'
121     elsif params[:order].is_a? Array
122       @order = params[:order]
123     else
124       begin
125         @order = JSON.load(params[:order])
126       rescue
127         @order = params[:order].split(',')
128       end
129     end
130     @order = [@order] unless @order.is_a? Array
131
132     @limit ||= 200
133     if params[:limit]
134       @limit = params[:limit].to_i
135     end
136
137     @offset ||= 0
138     if params[:offset]
139       @offset = params[:offset].to_i
140     end
141
142     @filters ||= []
143     if params[:filters]
144       filters = params[:filters]
145       if filters.is_a? String
146         filters = Oj.load filters
147       elsif filters.is_a? Array
148         filters = filters.collect do |filter|
149           if filter.is_a? String
150             # Accept filters[]=["foo","=","bar"]
151             Oj.load filter
152           else
153             # Accept filters=[["foo","=","bar"]]
154             filter
155           end
156         end
157       end
158       # After this, params[:filters] can be trusted to be an array of arrays:
159       params[:filters] = filters
160       @filters += filters
161     end
162   end
163
164   def find_objects_for_index
165     @objects ||= model_class
166     @objects = @objects.filter(@filters).limit(@limit).offset(@offset)
167   end
168
169   def render_index
170     if params[:partial]
171       respond_to do |f|
172         f.json {
173           @next_page_href = next_page_href(partial: params[:partial])
174           render json: {
175             content: render_to_string(partial: "show_#{params[:partial]}.html", formats: [:html]),
176                                       next_page_href: @next_page_href
177
178           }
179         }
180       end
181     else
182       respond_to do |f|
183         f.json { render json: @objects }
184         f.html {
185           if params[:tab_pane]
186             render_pane params[:tab_pane]
187           else
188             render
189           end
190         }
191         f.js { render }
192       end
193     end
194   end
195
196   helper_method :render_pane
197   def render_pane tab_pane, opts={}
198     render_opts = {
199       partial: 'show_' + tab_pane.downcase,
200       locals: {
201         comparable: self.respond_to?(:compare),
202         objects: @objects,
203         tab_pane: tab_pane
204       }.merge(opts[:locals] || {})
205     }
206     if opts[:to_string]
207       render_to_string render_opts
208     else
209       render render_opts
210     end
211   end
212
213   def index
214     find_objects_for_index if !@objects
215     render_index
216   end
217
218   helper_method :next_page_offset
219   def next_page_offset objects=nil
220     if !objects
221       objects = @objects
222     end
223     if objects.respond_to?(:result_offset) and
224         objects.respond_to?(:result_limit) and
225         objects.respond_to?(:items_available)
226       next_offset = objects.result_offset + objects.result_limit
227       if next_offset < objects.items_available
228         next_offset
229       else
230         nil
231       end
232     end
233   end
234
235   helper_method :next_page_href
236   def next_page_href with_params={}
237     if next_page_offset
238       url_for with_params.merge(offset: next_page_offset)
239     end
240   end
241
242   def show
243     if !@object
244       return render_not_found("object not found")
245     end
246     respond_to do |f|
247       f.json do
248         extra_attrs = { href: url_for(action: :show, id: @object) }
249         @object.textile_attributes.each do |textile_attr|
250           extra_attrs.merge!({ "#{textile_attr}Textile" => view_context.render_markup(@object.attributes[textile_attr]) })
251         end
252         render json: @object.attributes.merge(extra_attrs)
253       end
254       f.html {
255         if params['tab_pane']
256           render_pane(if params['tab_pane'].is_a? Hash then params['tab_pane']["name"] else params['tab_pane'] end)
257         elsif request.method.in? ['GET', 'HEAD']
258           render
259         else
260           redirect_to params[:return_to] || @object
261         end
262       }
263       f.js { render }
264     end
265   end
266
267   def choose
268     params[:limit] ||= 40
269     respond_to do |f|
270       if params[:partial]
271         f.json {
272           find_objects_for_index if !@objects
273           render json: {
274             content: render_to_string(partial: "choose_rows.html",
275                                       formats: [:html]),
276             next_page_href: next_page_href(partial: params[:partial])
277           }
278         }
279       end
280       f.js {
281         find_objects_for_index if !@objects
282         render partial: 'choose', locals: {multiple: params[:multiple]}
283       }
284     end
285   end
286
287   def render_content
288     if !@object
289       return render_not_found("object not found")
290     end
291   end
292
293   def new
294     @object = model_class.new
295   end
296
297   def update
298     @updates ||= params[@object.resource_param_name.to_sym]
299     @updates.keys.each do |attr|
300       if @object.send(attr).is_a? Hash
301         if @updates[attr].is_a? String
302           @updates[attr] = Oj.load @updates[attr]
303         end
304         if params[:merge] || params["merge_#{attr}".to_sym]
305           # Merge provided Hash with current Hash, instead of
306           # replacing.
307           @updates[attr] = @object.send(attr).with_indifferent_access.
308             deep_merge(@updates[attr].with_indifferent_access)
309         end
310       end
311     end
312     if @object.update_attributes @updates
313       show
314     else
315       self.render_error status: 422
316     end
317   end
318
319   def create
320     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
321     @new_resource_attrs ||= {}
322     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
323     @object ||= model_class.new @new_resource_attrs, params["options"]
324     if @object.save
325       respond_to do |f|
326         f.json { render json: @object.attributes.merge(href: url_for(action: :show, id: @object)) }
327         f.html {
328           redirect_to @object
329         }
330         f.js { render }
331       end
332     else
333       self.render_error status: 422
334     end
335   end
336
337   # Clone the given object, merging any attribute values supplied as
338   # with a create action.
339   def copy
340     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
341     @new_resource_attrs ||= {}
342     @object = @object.dup
343     @object.update_attributes @new_resource_attrs
344     if not @new_resource_attrs[:name] and @object.respond_to? :name
345       if @object.name and @object.name != ''
346         @object.name = "Copy of #{@object.name}"
347       else
348         @object.name = ""
349       end
350     end
351     @object.save!
352     show
353   end
354
355   def destroy
356     if @object.destroy
357       respond_to do |f|
358         f.json { render json: @object }
359         f.html {
360           redirect_to(params[:return_to] || :back)
361         }
362         f.js { render }
363       end
364     else
365       self.render_error status: 422
366     end
367   end
368
369   def current_user
370     Thread.current[:user]
371   end
372
373   def model_class
374     controller_name.classify.constantize
375   end
376
377   def breadcrumb_page_name
378     (@breadcrumb_page_name ||
379      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
380      action_name)
381   end
382
383   def index_pane_list
384     %w(Recent)
385   end
386
387   def show_pane_list
388     %w(Attributes Advanced)
389   end
390
391   protected
392
393   def strip_token_from_path(path)
394     path.sub(/([\?&;])api_token=[^&;]*[&;]?/, '\1')
395   end
396
397   def redirect_to_login
398     respond_to do |f|
399       f.html {
400         if request.method.in? ['GET', 'HEAD']
401           redirect_to arvados_api_client.arvados_login_url(return_to: strip_token_from_path(request.url))
402         else
403           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."
404           redirect_to :back
405         end
406       }
407       f.json {
408         @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.']
409         self.render_error status: 422
410       }
411     end
412     false  # For convenience to return from callbacks
413   end
414
415   def using_specific_api_token(api_token, opts={})
416     start_values = {}
417     [:arvados_api_token, :user].each do |key|
418       start_values[key] = Thread.current[key]
419     end
420     if opts.fetch(:load_user, true)
421       load_api_token(api_token)
422     else
423       Thread.current[:arvados_api_token] = api_token
424       Thread.current[:user] = nil
425     end
426     begin
427       yield
428     ensure
429       start_values.each_key { |key| Thread.current[key] = start_values[key] }
430     end
431   end
432
433
434   def accept_uuid_as_id_param
435     if params[:id] and params[:id].match /\D/
436       params[:uuid] = params.delete :id
437     end
438   end
439
440   def find_object_by_uuid
441     begin
442       if not model_class
443         @object = nil
444       elsif not params[:uuid].is_a?(String)
445         @object = model_class.where(uuid: params[:uuid]).first
446       elsif params[:uuid].empty?
447         @object = nil
448       elsif (model_class != Link and
449              resource_class_for_uuid(params[:uuid]) == Link)
450         @name_link = Link.find(params[:uuid])
451         @object = model_class.find(@name_link.head_uuid)
452       else
453         @object = model_class.find(params[:uuid])
454       end
455     rescue ArvadosApiClient::NotFoundException, RuntimeError => error
456       if error.is_a?(RuntimeError) and (error.message !~ /^argument to find\(/)
457         raise
458       end
459       render_not_found(error)
460       return false
461     end
462   end
463
464   def thread_clear
465     load_api_token(nil)
466     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
467     yield
468     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
469   end
470
471   # Set up the thread with the given API token and associated user object.
472   def load_api_token(new_token)
473     Thread.current[:arvados_api_token] = new_token
474     if new_token.nil?
475       Thread.current[:user] = nil
476     else
477       Thread.current[:user] = User.current
478     end
479   end
480
481   # If there's a valid api_token parameter, set up the session with that
482   # user's information.  Return true if the method redirects the request
483   # (usually a post-login redirect); false otherwise.
484   def setup_user_session
485     return false unless params[:api_token]
486     Thread.current[:arvados_api_token] = params[:api_token]
487     begin
488       user = User.current
489     rescue ArvadosApiClient::NotLoggedInException
490       false  # We may redirect to login, or not, based on the current action.
491     else
492       session[:arvados_api_token] = params[:api_token]
493       # If we later have trouble contacting the API server, we still want
494       # to be able to render basic user information in the UI--see
495       # render_exception above.  We store that in the session here.  This is
496       # not intended to be used as a general-purpose cache.  See #2891.
497       session[:user] = {
498         uuid: user.uuid,
499         email: user.email,
500         first_name: user.first_name,
501         last_name: user.last_name,
502         is_active: user.is_active,
503         is_admin: user.is_admin,
504         prefs: user.prefs
505       }
506
507       if !request.format.json? and request.method.in? ['GET', 'HEAD']
508         # Repeat this request with api_token in the (new) session
509         # cookie instead of the query string.  This prevents API
510         # tokens from appearing in (and being inadvisedly copied
511         # and pasted from) browser Location bars.
512         redirect_to strip_token_from_path(request.fullpath)
513         true
514       else
515         false
516       end
517     ensure
518       Thread.current[:arvados_api_token] = nil
519     end
520   end
521
522   # Save the session API token in thread-local storage, and yield.
523   # This method also takes care of session setup if the request
524   # provides a valid api_token parameter.
525   # If a token is unavailable or expired, the block is still run, with
526   # a nil token.
527   def set_thread_api_token
528     if Thread.current[:arvados_api_token]
529       yield   # An API token has already been found - pass it through.
530       return
531     elsif setup_user_session
532       return  # A new session was set up and received a response.
533     end
534
535     begin
536       load_api_token(session[:arvados_api_token])
537       yield
538     rescue ArvadosApiClient::NotLoggedInException
539       # If we got this error with a token, it must've expired.
540       # Retry the request without a token.
541       unless Thread.current[:arvados_api_token].nil?
542         load_api_token(nil)
543         yield
544       end
545     ensure
546       # Remove token in case this Thread is used for anything else.
547       load_api_token(nil)
548     end
549   end
550
551   # Redirect to login/welcome if client provided expired API token (or none at all)
552   def require_thread_api_token
553     if Thread.current[:arvados_api_token]
554       yield
555     elsif session[:arvados_api_token]
556       # Expired session. Clear it before refreshing login so that,
557       # if this login procedure fails, we end up showing the "please
558       # log in" page instead of getting stuck in a redirect loop.
559       session.delete :arvados_api_token
560       redirect_to_login
561     else
562       redirect_to welcome_users_path(return_to: request.fullpath)
563     end
564   end
565
566   def ensure_current_user_is_admin
567     unless current_user and current_user.is_admin
568       @errors = ['Permission denied']
569       self.render_error status: 401
570     end
571   end
572
573   helper_method :unsigned_user_agreements
574   def unsigned_user_agreements
575     @signed_ua_uuids ||= UserAgreement.signatures.map &:head_uuid
576     @unsigned_user_agreements ||= UserAgreement.all.map do |ua|
577       if not @signed_ua_uuids.index ua.uuid
578         Collection.find(ua.uuid)
579       end
580     end.compact
581   end
582
583   def check_user_agreements
584     if current_user && !current_user.is_active
585       if not current_user.is_invited
586         return redirect_to inactive_users_path(return_to: request.fullpath)
587       end
588       if unsigned_user_agreements.empty?
589         # No agreements to sign. Perhaps we just need to ask?
590         current_user.activate
591         if !current_user.is_active
592           logger.warn "#{current_user.uuid.inspect}: " +
593             "No user agreements to sign, but activate failed!"
594         end
595       end
596       if !current_user.is_active
597         redirect_to user_agreements_path(return_to: request.fullpath)
598       end
599     end
600     true
601   end
602
603   def check_user_profile
604     if request.method.downcase != 'get' || params[:partial] ||
605        params[:tab_pane] || params[:action_method] ||
606        params[:action] == 'setup_popup'
607       return true
608     end
609
610     if missing_required_profile?
611       redirect_to profile_user_path(current_user.uuid, return_to: request.fullpath)
612     end
613     true
614   end
615
616   helper_method :missing_required_profile?
617   def missing_required_profile?
618     missing_required = false
619
620     profile_config = Rails.configuration.user_profile_form_fields
621     if current_user && profile_config
622       current_user_profile = current_user.prefs[:profile]
623       profile_config.kind_of?(Array) && profile_config.andand.each do |entry|
624         if entry['required']
625           if !current_user_profile ||
626              !current_user_profile[entry['key'].to_sym] ||
627              current_user_profile[entry['key'].to_sym].empty?
628             missing_required = true
629             break
630           end
631         end
632       end
633     end
634
635     missing_required
636   end
637
638   def select_theme
639     return Rails.configuration.arvados_theme
640   end
641
642   @@notification_tests = []
643
644   @@notification_tests.push lambda { |controller, current_user|
645     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
646       return nil
647     end
648     return lambda { |view|
649       view.render partial: 'notifications/ssh_key_notification'
650     }
651   }
652
653   @@notification_tests.push lambda { |controller, current_user|
654     Collection.limit(1).where(created_by: current_user.uuid).each do
655       return nil
656     end
657     return lambda { |view|
658       view.render partial: 'notifications/collections_notification'
659     }
660   }
661
662   @@notification_tests.push lambda { |controller, current_user|
663     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
664       return nil
665     end
666     return lambda { |view|
667       view.render partial: 'notifications/pipelines_notification'
668     }
669   }
670
671   def check_user_notifications
672     return if params['tab_pane']
673
674     @notification_count = 0
675     @notifications = []
676
677     if current_user.andand.is_active
678       @showallalerts = false
679       @@notification_tests.each do |t|
680         a = t.call(self, current_user)
681         if a
682           @notification_count += 1
683           @notifications.push a
684         end
685       end
686     end
687
688     if @notification_count == 0
689       @notification_count = ''
690     end
691   end
692
693   helper_method :all_projects
694   def all_projects
695     @all_projects ||= Group.
696       filter([['group_class','=','project']]).order('name')
697   end
698
699   helper_method :my_projects
700   def my_projects
701     return @my_projects if @my_projects
702     @my_projects = []
703     root_of = {}
704     all_projects.each do |g|
705       root_of[g.uuid] = g.owner_uuid
706       @my_projects << g
707     end
708     done = false
709     while not done
710       done = true
711       root_of = root_of.each_with_object({}) do |(child, parent), h|
712         if root_of[parent]
713           h[child] = root_of[parent]
714           done = false
715         else
716           h[child] = parent
717         end
718       end
719     end
720     @my_projects = @my_projects.select do |g|
721       root_of[g.uuid] == current_user.uuid
722     end
723   end
724
725   helper_method :projects_shared_with_me
726   def projects_shared_with_me
727     my_project_uuids = my_projects.collect &:uuid
728     all_projects.reject { |x| x.uuid.in? my_project_uuids }
729   end
730
731   helper_method :recent_jobs_and_pipelines
732   def recent_jobs_and_pipelines
733     (Job.limit(10) |
734      PipelineInstance.limit(10)).
735       sort_by do |x|
736       (x.finished_at || x.started_at rescue nil) || x.modified_at || x.created_at
737     end.reverse
738   end
739
740   helper_method :running_pipelines
741   def running_pipelines
742     pi = PipelineInstance.order(["started_at asc", "created_at asc"]).filter([["state", "in", ["RunningOnServer", "RunningOnClient"]]])
743     jobs = {}
744     pi.each do |pl|
745       pl.components.each do |k,v|
746         if v.is_a? Hash and v[:job]
747           jobs[v[:job][:uuid]] = {}
748         end
749       end
750     end
751
752     if jobs.keys.any?
753       Job.filter([["uuid", "in", jobs.keys]]).each do |j|
754         jobs[j[:uuid]] = j
755       end
756
757       pi.each do |pl|
758         pl.components.each do |k,v|
759           if v.is_a? Hash and v[:job]
760             v[:job] = jobs[v[:job][:uuid]]
761           end
762         end
763       end
764     end
765
766     pi
767   end
768
769   helper_method :finished_pipelines
770   def finished_pipelines lim
771     PipelineInstance.limit(lim).order(["finished_at desc"]).filter([["state", "in", ["Complete", "Failed", "Paused"]], ["finished_at", "!=", nil]])
772   end
773
774   helper_method :recent_collections
775   def recent_collections lim
776     c = Collection.limit(lim).order(["modified_at desc"]).filter([["owner_uuid", "is_a", "arvados#group"]])
777     own = {}
778     Group.filter([["uuid", "in", c.map(&:owner_uuid)]]).each do |g|
779       own[g[:uuid]] = g
780     end
781     {collections: c, owners: own}
782   end
783
784   helper_method :my_project_tree
785   def my_project_tree
786     build_project_trees
787     @my_project_tree
788   end
789
790   helper_method :shared_project_tree
791   def shared_project_tree
792     build_project_trees
793     @shared_project_tree
794   end
795
796   def build_project_trees
797     return if @my_project_tree and @shared_project_tree
798     parent_of = {current_user.uuid => 'me'}
799     all_projects.each do |ob|
800       parent_of[ob.uuid] = ob.owner_uuid
801     end
802     children_of = {false => [], 'me' => [current_user]}
803     all_projects.each do |ob|
804       if ob.owner_uuid != current_user.uuid and
805           not parent_of.has_key? ob.owner_uuid
806         parent_of[ob.uuid] = false
807       end
808       children_of[parent_of[ob.uuid]] ||= []
809       children_of[parent_of[ob.uuid]] << ob
810     end
811     buildtree = lambda do |children_of, root_uuid=false|
812       tree = {}
813       children_of[root_uuid].andand.each do |ob|
814         tree[ob] = buildtree.call(children_of, ob.uuid)
815       end
816       tree
817     end
818     sorted_paths = lambda do |tree, depth=0|
819       paths = []
820       tree.keys.sort_by { |ob|
821         ob.is_a?(String) ? ob : ob.friendly_link_name
822       }.each do |ob|
823         paths << {object: ob, depth: depth}
824         paths += sorted_paths.call tree[ob], depth+1
825       end
826       paths
827     end
828     @my_project_tree =
829       sorted_paths.call buildtree.call(children_of, 'me')
830     @shared_project_tree =
831       sorted_paths.call({'Projects shared with me' =>
832                           buildtree.call(children_of, false)})
833   end
834
835   helper_method :get_object
836   def get_object uuid
837     if @get_object.nil? and @objects
838       @get_object = @objects.each_with_object({}) do |object, h|
839         h[object.uuid] = object
840       end
841     end
842     @get_object ||= {}
843     @get_object[uuid]
844   end
845
846   helper_method :project_breadcrumbs
847   def project_breadcrumbs
848     crumbs = []
849     current = @name_link || @object
850     while current
851       # Halt if a group ownership loop is detected. API should refuse
852       # to produce this state, but it could still arise from a race
853       # condition when group ownership changes between our find()
854       # queries.
855       break if crumbs.collect(&:uuid).include? current.uuid
856
857       if current.is_a?(Group) and current.group_class == 'project'
858         crumbs.prepend current
859       end
860       if current.is_a? Link
861         current = Group.find?(current.tail_uuid)
862       else
863         current = Group.find?(current.owner_uuid)
864       end
865     end
866     crumbs
867   end
868
869   helper_method :current_project_uuid
870   def current_project_uuid
871     if @object.is_a? Group and @object.group_class == 'project'
872       @object.uuid
873     elsif @name_link.andand.tail_uuid
874       @name_link.tail_uuid
875     elsif @object and resource_class_for_uuid(@object.owner_uuid) == Group
876       @object.owner_uuid
877     else
878       nil
879     end
880   end
881
882   # helper method to get links for given object or uuid
883   helper_method :links_for_object
884   def links_for_object object_or_uuid
885     raise ArgumentError, 'No input argument' unless object_or_uuid
886     preload_links_for_objects([object_or_uuid])
887     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
888     @all_links_for[uuid] ||= []
889   end
890
891   # helper method to preload links for given objects and uuids
892   helper_method :preload_links_for_objects
893   def preload_links_for_objects objects_and_uuids
894     @all_links_for ||= {}
895
896     raise ArgumentError, 'Argument is not an array' unless objects_and_uuids.is_a? Array
897     return @all_links_for if objects_and_uuids.empty?
898
899     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
900
901     # if already preloaded for all of these uuids, return
902     if not uuids.select { |x| @all_links_for[x].nil? }.any?
903       return @all_links_for
904     end
905
906     uuids.each do |x|
907       @all_links_for[x] = []
908     end
909
910     # TODO: make sure we get every page of results from API server
911     Link.filter([['head_uuid', 'in', uuids]]).each do |link|
912       @all_links_for[link.head_uuid] << link
913     end
914     @all_links_for
915   end
916
917   # helper method to get a certain number of objects of a specific type
918   # this can be used to replace any uses of: "dataclass.limit(n)"
919   helper_method :get_n_objects_of_class
920   def get_n_objects_of_class dataclass, size
921     @objects_map_for ||= {}
922
923     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class and dataclass < ArvadosBase
924     raise ArgumentError, 'Argument is not a valid limit size' unless (size && size>0)
925
926     # if the objects_map_for has a value for this dataclass, and the
927     # size used to retrieve those objects is equal, return it
928     size_key = "#{dataclass.name}_size"
929     if @objects_map_for[dataclass.name] && @objects_map_for[size_key] &&
930         (@objects_map_for[size_key] == size)
931       return @objects_map_for[dataclass.name]
932     end
933
934     @objects_map_for[size_key] = size
935     @objects_map_for[dataclass.name] = dataclass.limit(size)
936   end
937
938   # helper method to get collections for the given uuid
939   helper_method :collections_for_object
940   def collections_for_object uuid
941     raise ArgumentError, 'No input argument' unless uuid
942     preload_collections_for_objects([uuid])
943     @all_collections_for[uuid] ||= []
944   end
945
946   # helper method to preload collections for the given uuids
947   helper_method :preload_collections_for_objects
948   def preload_collections_for_objects uuids
949     @all_collections_for ||= {}
950
951     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
952     return @all_collections_for if uuids.empty?
953
954     # if already preloaded for all of these uuids, return
955     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
956       return @all_collections_for
957     end
958
959     uuids.each do |x|
960       @all_collections_for[x] = []
961     end
962
963     # TODO: make sure we get every page of results from API server
964     Collection.where(uuid: uuids).each do |collection|
965       @all_collections_for[collection.uuid] << collection
966     end
967     @all_collections_for
968   end
969
970   # helper method to get log collections for the given log
971   helper_method :log_collections_for_object
972   def log_collections_for_object log
973     raise ArgumentError, 'No input argument' unless log
974
975     preload_log_collections_for_objects([log])
976
977     uuid = log
978     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
979     if fixup && fixup.size>1
980       uuid = fixup[1]
981     end
982
983     @all_log_collections_for[uuid] ||= []
984   end
985
986   # helper method to preload collections for the given uuids
987   helper_method :preload_log_collections_for_objects
988   def preload_log_collections_for_objects logs
989     @all_log_collections_for ||= {}
990
991     raise ArgumentError, 'Argument is not an array' unless logs.is_a? Array
992     return @all_log_collections_for if logs.empty?
993
994     uuids = []
995     logs.each do |log|
996       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
997       if fixup && fixup.size>1
998         uuids << fixup[1]
999       else
1000         uuids << log
1001       end
1002     end
1003
1004     # if already preloaded for all of these uuids, return
1005     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
1006       return @all_log_collections_for
1007     end
1008
1009     uuids.each do |x|
1010       @all_log_collections_for[x] = []
1011     end
1012
1013     # TODO: make sure we get every page of results from API server
1014     Collection.where(uuid: uuids).each do |collection|
1015       @all_log_collections_for[collection.uuid] << collection
1016     end
1017     @all_log_collections_for
1018   end
1019
1020   # helper method to get object of a given dataclass and uuid
1021   helper_method :object_for_dataclass
1022   def object_for_dataclass dataclass, uuid
1023     raise ArgumentError, 'No input argument dataclass' unless (dataclass && uuid)
1024     preload_objects_for_dataclass(dataclass, [uuid])
1025     @objects_for[uuid]
1026   end
1027
1028   # helper method to preload objects for given dataclass and uuids
1029   helper_method :preload_objects_for_dataclass
1030   def preload_objects_for_dataclass dataclass, uuids
1031     @objects_for ||= {}
1032
1033     raise ArgumentError, 'Argument is not a data class' unless dataclass.is_a? Class
1034     raise ArgumentError, 'Argument is not an array' unless uuids.is_a? Array
1035
1036     return @objects_for if uuids.empty?
1037
1038     # if already preloaded for all of these uuids, return
1039     if not uuids.select { |x| @objects_for[x].nil? }.any?
1040       return @objects_for
1041     end
1042
1043     dataclass.where(uuid: uuids).each do |obj|
1044       @objects_for[obj.uuid] = obj
1045     end
1046     @objects_for
1047   end
1048
1049   def wiselinks_layout
1050     'body'
1051   end
1052 end