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