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