5ecab0f94ddeb85c77a26e36efd3a714d942efec
[arvados.git] / services / api / script / permission-updater.rb
1 #!/usr/bin/env ruby
2
3 dispatch_argv = []
4 ARGV.reject! do |arg|
5   dispatch_argv.push(arg) if /^--/ =~ arg
6 end
7
8 ENV["RAILS_ENV"] = ARGV[0] || ENV["RAILS_ENV"] || "development"
9 require File.dirname(__FILE__) + '/../config/boot'
10 require File.dirname(__FILE__) + '/../config/environment'
11
12 User.all.each do |u|
13   u.calculate_group_permissions
14 end
15
16 ActiveRecord::Base.connection_pool.with_connection do |connection|
17   conn = connection.instance_variable_get(:@connection)
18   begin
19     conn.async_exec "LISTEN invalidate_permissions_cache"
20     while true
21       # wait_for_notify will block until there is a change
22       # notification from Postgres about the logs table, then push
23       # the notification into the EventMachine channel.  Each
24       # websocket connection subscribes to the other end of the
25       # channel and calls #push_events to actually dispatch the
26       # events to the client.
27       conn.wait_for_notify do |channel, pid, payload|
28         Rails.logger.info "Begin updating permission cache"
29         User.all.each do |u|
30           u.calculate_group_permissions
31         end
32         Rails.logger.info "Permission cache updated"
33       end
34     end
35   ensure
36     # Don't want the connection to still be listening once we return
37     # it to the pool - could result in weird behavior for the next
38     # thread to check it out.
39     conn.async_exec "UNLISTEN *"
40   end
41 end