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