Merge branch 'master' into 2871-preload-objects
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include ArvadosApiClientHelper
3
4   respond_to :html, :json, :js
5   protect_from_forgery
6
7   ERROR_ACTIONS = [:render_error, :render_not_found]
8
9   around_filter :thread_clear
10   around_filter :thread_with_mandatory_api_token, except: ERROR_ACTIONS
11   around_filter :thread_with_optional_api_token
12   before_filter :check_user_agreements, except: ERROR_ACTIONS
13   before_filter :check_user_notifications, except: ERROR_ACTIONS
14   before_filter :find_object_by_uuid, except: [:index] + ERROR_ACTIONS
15   theme :select_theme
16
17   begin
18     rescue_from Exception,
19     :with => :render_exception
20     rescue_from ActiveRecord::RecordNotFound,
21     :with => :render_not_found
22     rescue_from ActionController::RoutingError,
23     :with => :render_not_found
24     rescue_from ActionController::UnknownController,
25     :with => :render_not_found
26     rescue_from ::AbstractController::ActionNotFound,
27     :with => :render_not_found
28   end
29
30   def unprocessable(message=nil)
31     @errors ||= []
32
33     @errors << message if message
34     render_error status: 422
35   end
36
37   def render_error(opts)
38     opts = {status: 500}.merge opts
39     respond_to do |f|
40       # json must come before html here, so it gets used as the
41       # default format when js is requested by the client. This lets
42       # ajax:error callback parse the response correctly, even though
43       # the browser can't.
44       f.json { render opts.merge(json: {success: false, errors: @errors}) }
45       f.html { render opts.merge(controller: 'application', action: 'error') }
46     end
47   end
48
49   def render_exception(e)
50     logger.error e.inspect
51     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
52     if @object.andand.errors.andand.full_messages.andand.any?
53       @errors = @object.errors.full_messages
54     else
55       @errors = [e.to_s]
56     end
57     self.render_error status: 422
58   end
59
60   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
61     logger.error e.inspect
62     @errors = ["Path not found"]
63     self.render_error status: 404
64   end
65
66   def index
67     @limit ||= 200
68     if params[:limit]
69       @limit = params[:limit].to_i
70     end
71
72     @offset ||= 0
73     if params[:offset]
74       @offset = params[:offset].to_i
75     end
76
77     @filters ||= []
78     if params[:filters]
79       filters = params[:filters]
80       if filters.is_a? String
81         filters = Oj.load filters
82       end
83       @filters += filters
84     end
85
86     @objects ||= model_class
87     @objects = @objects.filter(@filters).limit(@limit).offset(@offset).all
88     respond_to do |f|
89       f.json { render json: @objects }
90       f.html { render }
91       f.js { render }
92     end
93   end
94
95   def show
96     if !@object
97       return render_not_found("object not found")
98     end
99     respond_to do |f|
100       f.json { render json: @object.attributes.merge(href: url_for(@object)) }
101       f.html {
102         if request.method == 'GET'
103           render
104         else
105           redirect_to params[:return_to] || @object
106         end
107       }
108       f.js { render }
109     end
110   end
111
112   def render_content
113     if !@object
114       return render_not_found("object not found")
115     end
116   end
117
118   def new
119     @object = model_class.new
120   end
121
122   def update
123     @updates ||= params[@object.class.to_s.underscore.singularize.to_sym]
124     @updates.keys.each do |attr|
125       if @object.send(attr).is_a? Hash
126         if @updates[attr].is_a? String
127           @updates[attr] = Oj.load @updates[attr]
128         end
129         if params[:merge] || params["merge_#{attr}".to_sym]
130           # Merge provided Hash with current Hash, instead of
131           # replacing.
132           @updates[attr] = @object.send(attr).with_indifferent_access.
133             deep_merge(@updates[attr].with_indifferent_access)
134         end
135       end
136     end
137     if @object.update_attributes @updates
138       show
139     else
140       self.render_error status: 422
141     end
142   end
143
144   def create
145     @new_resource_attrs ||= params[model_class.to_s.underscore.singularize]
146     @new_resource_attrs ||= {}
147     @new_resource_attrs.reject! { |k,v| k.to_s == 'uuid' }
148     @object ||= model_class.new @new_resource_attrs, params["options"]
149     if @object.save
150       respond_to do |f|
151         f.json { render json: @object.attributes.merge(href: url_for(@object)) }
152         f.html {
153           redirect_to @object
154         }
155         f.js { render }
156       end
157     else
158       self.render_error status: 422
159     end
160   end
161
162   def destroy
163     if @object.destroy
164       respond_to do |f|
165         f.json { render json: @object }
166         f.html {
167           redirect_to(params[:return_to] || :back)
168         }
169         f.js { render }
170       end
171     else
172       self.render_error status: 422
173     end
174   end
175
176   def current_user
177     if Thread.current[:arvados_api_token]
178       Thread.current[:user] ||= User.current
179     else
180       logger.error "No API token in Thread"
181       return nil
182     end
183   end
184
185   def model_class
186     controller_name.classify.constantize
187   end
188
189   def breadcrumb_page_name
190     (@breadcrumb_page_name ||
191      (@object.friendly_link_name if @object.respond_to? :friendly_link_name) ||
192      action_name)
193   end
194
195   def index_pane_list
196     %w(Recent)
197   end
198
199   def show_pane_list
200     %w(Attributes Metadata JSON API)
201   end
202
203   protected
204
205   def redirect_to_login
206     respond_to do |f|
207       f.html {
208         if request.method == 'GET'
209           redirect_to arvados_api_client.arvados_login_url(return_to: request.url)
210         else
211           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."
212           redirect_to :back
213         end
214       }
215       f.json {
216         @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.']
217         self.render_error status: 422
218       }
219     end
220     false  # For convenience to return from callbacks
221   end
222
223   def using_specific_api_token(api_token)
224     start_values = {}
225     [:arvados_api_token, :user].each do |key|
226       start_values[key] = Thread.current[key]
227     end
228     Thread.current[:arvados_api_token] = api_token
229     Thread.current[:user] = nil
230     begin
231       yield
232     ensure
233       start_values.each_key { |key| Thread.current[key] = start_values[key] }
234     end
235   end
236
237   def find_object_by_uuid
238     if params[:id] and params[:id].match /\D/
239       params[:uuid] = params.delete :id
240     end
241     if not model_class
242       @object = nil
243     elsif params[:uuid].is_a? String
244       if params[:uuid].empty?
245         @object = nil
246       else
247         @object = model_class.find(params[:uuid])
248       end
249     else
250       @object = model_class.where(uuid: params[:uuid]).first
251     end
252   end
253
254   def thread_clear
255     Thread.current[:arvados_api_token] = nil
256     Thread.current[:user] = nil
257     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
258     yield
259     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
260   end
261
262   def thread_with_api_token(login_optional = false)
263     begin
264       try_redirect_to_login = true
265       if params[:api_token]
266         try_redirect_to_login = false
267         Thread.current[:arvados_api_token] = params[:api_token]
268         # Before copying the token into session[], do a simple API
269         # call to verify its authenticity.
270         if verify_api_token
271           session[:arvados_api_token] = params[:api_token]
272           if !request.format.json? and request.method == 'GET'
273             # Repeat this request with api_token in the (new) session
274             # cookie instead of the query string.  This prevents API
275             # tokens from appearing in (and being inadvisedly copied
276             # and pasted from) browser Location bars.
277             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
278           else
279             yield
280           end
281         else
282           @errors = ['Invalid API token']
283           self.render_error status: 401
284         end
285       elsif session[:arvados_api_token]
286         # In this case, the token must have already verified at some
287         # point, but it might have been revoked since.  We'll try
288         # using it, and catch the exception if it doesn't work.
289         try_redirect_to_login = false
290         Thread.current[:arvados_api_token] = session[:arvados_api_token]
291         begin
292           yield
293         rescue ArvadosApiClient::NotLoggedInException
294           try_redirect_to_login = true
295         end
296       else
297         logger.debug "No token received, session is #{session.inspect}"
298       end
299       if try_redirect_to_login
300         unless login_optional
301           redirect_to_login
302         else
303           # login is optional for this route so go on to the regular controller
304           Thread.current[:arvados_api_token] = nil
305           yield
306         end
307       end
308     ensure
309       # Remove token in case this Thread is used for anything else.
310       Thread.current[:arvados_api_token] = nil
311     end
312   end
313
314   def thread_with_mandatory_api_token
315     thread_with_api_token do
316       yield
317     end
318   end
319
320   # This runs after thread_with_mandatory_api_token in the filter chain.
321   def thread_with_optional_api_token
322     if Thread.current[:arvados_api_token]
323       # We are already inside thread_with_mandatory_api_token.
324       yield
325     else
326       # We skipped thread_with_mandatory_api_token. Use the optional version.
327       thread_with_api_token(true) do
328         yield
329       end
330     end
331   end
332
333   def verify_api_token
334     begin
335       Link.where(uuid: 'just-verifying-my-api-token')
336       true
337     rescue ArvadosApiClient::NotLoggedInException
338       false
339     end
340   end
341
342   def ensure_current_user_is_admin
343     unless current_user and current_user.is_admin
344       @errors = ['Permission denied']
345       self.render_error status: 401
346     end
347   end
348
349   def check_user_agreements
350     if current_user && !current_user.is_active && current_user.is_invited
351       signatures = UserAgreement.signatures
352       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
353       @required_user_agreements = UserAgreement.all.map do |ua|
354         if not @signed_ua_uuids.index ua.uuid
355           Collection.find(ua.uuid)
356         end
357       end.compact
358       if @required_user_agreements.empty?
359         # No agreements to sign. Perhaps we just need to ask?
360         current_user.activate
361         if !current_user.is_active
362           logger.warn "#{current_user.uuid.inspect}: " +
363             "No user agreements to sign, but activate failed!"
364         end
365       end
366       if !current_user.is_active
367         render 'user_agreements/index'
368       end
369     end
370     true
371   end
372
373   def select_theme
374     return Rails.configuration.arvados_theme
375   end
376
377   @@notification_tests = []
378
379   @@notification_tests.push lambda { |controller, current_user|
380     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
381       return nil
382     end
383     return lambda { |view|
384       view.render partial: 'notifications/ssh_key_notification'
385     }
386   }
387
388   #@@notification_tests.push lambda { |controller, current_user|
389   #  Job.limit(1).where(created_by: current_user.uuid).each do
390   #    return nil
391   #  end
392   #  return lambda { |view|
393   #    view.render partial: 'notifications/jobs_notification'
394   #  }
395   #}
396
397   @@notification_tests.push lambda { |controller, current_user|
398     Collection.limit(1).where(created_by: current_user.uuid).each do
399       return nil
400     end
401     return lambda { |view|
402       view.render partial: 'notifications/collections_notification'
403     }
404   }
405
406   @@notification_tests.push lambda { |controller, current_user|
407     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
408       return nil
409     end
410     return lambda { |view|
411       view.render partial: 'notifications/pipelines_notification'
412     }
413   }
414
415   def check_user_notifications
416     @notification_count = 0
417     @notifications = []
418
419     if current_user
420       @showallalerts = false
421       @@notification_tests.each do |t|
422         a = t.call(self, current_user)
423         if a
424           @notification_count += 1
425           @notifications.push a
426         end
427       end
428     end
429
430     if @notification_count == 0
431       @notification_count = ''
432     end
433   end
434
435   helper_method :my_folders
436   def my_folders
437     return @my_folders if @my_folders
438     @my_folders = []
439     root_of = {}
440     Group.filter([['group_class','=','folder']]).each do |g|
441       root_of[g.uuid] = g.owner_uuid
442       @my_folders << g
443     end
444     done = false
445     while not done
446       done = true
447       root_of = root_of.each_with_object({}) do |(child, parent), h|
448         if root_of[parent]
449           h[child] = root_of[parent]
450           done = false
451         else
452           h[child] = parent
453         end
454       end
455     end
456     @my_folders = @my_folders.select do |g|
457       root_of[g.uuid] == current_user.uuid
458     end
459   end
460
461   # helper method to get links for given object or uuid
462   helper_method :links_for_object
463   def links_for_object object_or_uuid
464     uuid = object_or_uuid.is_a?(String) ? object_or_uuid : object_or_uuid.uuid
465     preload_links_for_objects([object_or_uuid])
466     @all_links_for[uuid]
467   end
468
469   # helper method to preload links for given objects and uuids
470   helper_method :preload_links_for_objects
471   def preload_links_for_objects objects_and_uuids
472     uuids = objects_and_uuids.collect { |x| x.is_a?(String) ? x : x.uuid }
473     @all_links_for ||= {}
474
475     # if already preloaded for all of these uuids, return
476     if not uuids.select { |x| @all_links_for[x].nil? }.any?
477       return
478     end
479
480     uuids.each do |x|
481       @all_links_for[x] = []
482     end
483     # TODO: make sure we get every page of results from API server
484     Link.filter([['head_uuid','in',uuids]]).each do |link|
485       @all_links_for[link.head_uuid] << link
486     end
487   end
488
489   # helper method to get a certain number of objects of a specific type
490   # this can be used to replace any uses of: "dataclass.limit(n)"
491   helper_method :get_n_objects_of_class
492   def get_n_objects_of_class dataclass, size
493     # if the objects_map_for has a value for this dataclass, and the size used
494     # to retrieve those objects is greater than or equal to size, return it
495     size_key = "#{dataclass}_size"
496     if @objects_map_for && @objects_map_for[dataclass] && @objects_map_for[size_key] &&
497         (@objects_map_for[size_key] >= size)
498       return @objects_map_for[dataclass]
499     end
500
501     @objects_map_for = {}
502     @objects_map_for[dataclass] = dataclass.limit(size)
503     @objects_map_for[size_key] = size
504
505     return @objects_map_for[dataclass]
506   end
507
508   # helper method to get collections for the given uuid
509   helper_method :collections_for_object
510   def collections_for_object uuid
511     preload_collections_for_objects([uuid])
512     @all_collections_for[uuid]
513   end
514
515   # helper method to preload collections for the given uuids
516   helper_method :preload_collections_for_objects
517   def preload_collections_for_objects uuids
518     @all_collections_for ||= {}
519
520     # if already preloaded for all of these uuids, return
521     if not uuids.select { |x| @all_collections_for[x].nil? }.any?
522       return
523     end
524
525     uuids.each do |x|
526       @all_collections_for[x] = []
527     end
528
529     # TODO: make sure we get every page of results from API server
530     Collection.where(uuid: uuids).each do |collection|
531       @all_collections_for[collection.uuid] << collection
532     end
533   end
534
535   # helper method to get log collections for the given log
536   helper_method :log_collections_for_object
537   def log_collections_for_object log
538     fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
539     uuid = fixup[1]
540     preload_log_collections_for_objects([uuid])
541     @all_log_collections_for[uuid]
542   end
543
544   # helper method to preload collections for the given uuids
545   helper_method :preload_log_collections_for_objects
546   def preload_log_collections_for_objects logs
547     uuids = []
548     logs.each do |log|
549       fixup = /([a-f0-9]{32}\+\d+)(\+?.*)/.match(log)
550       uuids << fixup[1]
551     end
552
553     # if already preloaded for all of these uuids, return
554     @all_log_collections_for ||= {}
555     if not uuids.select { |x| @all_log_collections_for[x].nil? }.any?
556       return
557     end
558
559     uuids.each do |x|
560       @all_log_collections_for[x] = []
561     end
562
563     # TODO: make sure we get every page of results from API server
564     Collection.where(uuid: uuids).each do |collection|
565       @all_log_collections_for[collection.uuid] << collection
566     end
567   end
568
569   # helper method to get object of a given dataclass and uuid
570   helper_method :object_for_dataclass
571   def object_for_dataclass dataclass, uuid
572     preload_objects_for_dataclass(dataclass, [uuid])
573     @objects_for[uuid]
574   end
575
576   # helper method to preload objects for given dataclass and uuids
577   helper_method :preload_objects_for_dataclass
578   def preload_objects_for_dataclass dataclass, uuids
579     @objects_for ||= {}
580
581     # if already preloaded for all of these uuids, return
582     if not uuids.select { |x| @objects_for[x].nil? }.any?
583       return
584     end
585
586     dataclass.where(uuid: uuids).each do |obj|
587       @objects_for[obj.uuid] = obj
588     end
589   end
590
591 end