c0d5c1b694391326fcc9594cb1d5e5a778f743b2
[arvados.git] / services / api / lib / refresh_permission_view.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 PERMISSION_VIEW = "materialized_permissions"
6 TRASHED_GROUPS = "trashed_groups"
7
8 def refresh_permission_view
9   ActiveRecord::Base.transaction do
10     ActiveRecord::Base.connection.execute("LOCK TABLE #{PERMISSION_VIEW}")
11     ActiveRecord::Base.connection.execute("DELETE FROM #{PERMISSION_VIEW}")
12     ActiveRecord::Base.connection.execute %{
13 INSERT INTO #{PERMISSION_VIEW}
14 select users.uuid, g.target_uuid, g.val, g.traverse_owned
15 from users, lateral search_permission_graph(users.uuid, 3) as g where g.val > 0
16 },
17                                           "refresh_permission_view.do"
18   end
19 end
20
21 def refresh_trashed
22     ActiveRecord::Base.connection.execute("LOCK TABLE #{TRASHED_GROUPS}")
23   ActiveRecord::Base.connection.execute("DELETE FROM #{TRASHED_GROUPS}")
24   ActiveRecord::Base.connection.execute("INSERT INTO #{TRASHED_GROUPS} select * from compute_trashed()")
25 end
26
27 def update_permissions perm_origin_uuid, starting_uuid, perm_level, check=false
28   #
29   # Update a subset of the permission table affected by adding or
30   # removing a particular permission relationship (ownership or a
31   # permission link).
32   #
33   # perm_origin_uuid: This is the object that 'gets' the permission.
34   # It is the owner_uuid or tail_uuid.
35   #
36   # starting_uuid: The object we are computing permission for (or head_uuid)
37   #
38   # perm_level: The level of permission that perm_origin_uuid gets for starting_uuid.
39   #
40   # perm_level is a number from 0-3
41   #   can_read=1
42   #   can_write=2
43   #   can_manage=3
44   #   or call with perm_level=0 to revoke permissions
45   #
46   # check: for testing/debugging only, compare the result of the
47   # incremental update against a full table recompute.  Throws an
48   # error if the contents are not identical (ie they produce different
49   # permission results)
50
51   # Theory of operation
52   #
53   # Give a change in a specific permission relationship, we recompute
54   # the set of permissions (for all users) that could possibly be
55   # affected by that relationship.  For example, if a project is
56   # shared with another user, we recompute all permissions for all
57   # projects in the hierarchy.  This returns a set of updated
58   # permissions, which we stash in a temporary table.
59   #
60   # Then, for each user_uuid/target_uuid in the updated permissions
61   # result set we insert/update a permission row in
62   # materialized_permissions, and delete any rows that exist in
63   # materialized_permissions that are not in the result set or have
64   # perm_level=0.
65   #
66   # see db/migrate/20200501150153_permission_table.rb for details on
67   # how the permissions are computed.
68
69   # "Conflicts with the ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE, SHARE
70   # ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE lock modes. This
71   # mode protects a table against concurrent data changes."
72   ActiveRecord::Base.connection.execute "LOCK TABLE #{PERMISSION_VIEW} in SHARE MODE"
73
74   # Workaround for
75   # BUG #15160: planner overestimates number of rows in join when there are more than 200 rows coming from CTE
76   # https://www.postgresql.org/message-id/152395805004.19366.3107109716821067806@wrigleys.postgresql.org
77   #
78   # For a crucial join in the compute_permission_subgraph() query, the
79   # planner mis-estimates the number of rows in a Common Table
80   # Expression (CTE, this is a subquery in a WITH clause) and as a
81   # result it chooses the wrong join order.  The join starts with the
82   # permissions table because it mistakenly thinks
83   # count(materalized_permissions) < count(new computed permissions)
84   # when actually it is the other way around.
85   #
86   # Because of the incorrect join order, it choose the wrong join
87   # strategy (merge join, which works best when two tables are roughly
88   # the same size).  As a workaround, we can tell it not to use that
89   # join strategy, this causes it to pick hash join instead, which
90   # turns out to be a bit better.  However, because the join order is
91   # still wrong, we don't get the full benefit of the index.
92   #
93   # This is very unfortunate because it makes the query performance
94   # dependent on the size of the materalized_permissions table, when
95   # the goal of this design was to make permission updates scale-free
96   # and only depend on the number of permissions affected and not the
97   # total table size.  In several hours of researching I wasn't able
98   # to find a way to force the correct join order, so I'm calling it
99   # here and I have to move on.
100   #
101   # This is apparently addressed in Postgres 12, but I developed &
102   # tested this on Postgres 9.6, so in the future we should reevaluate
103   # the performance & query plan on Postgres 12.
104   #
105   # https://git.furworks.de/opensourcemirror/postgresql/commit/a314c34079cf06d05265623dd7c056f8fa9d577f
106   #
107   # Disable merge join for just this query (also local for this transaction), then reenable it.
108   ActiveRecord::Base.connection.exec_query "SET LOCAL enable_mergejoin to false;"
109
110   temptable_perms = "temp_perms_#{rand(2**64).to_s(10)}"
111   ActiveRecord::Base.connection.exec_query %{
112 create temporary table #{temptable_perms} on commit drop
113 as select * from compute_permission_subgraph($1, $2, $3)
114 },
115                                            'update_permissions.select',
116                                            [[nil, perm_origin_uuid],
117                                             [nil, starting_uuid],
118                                             [nil, perm_level]]
119
120   ActiveRecord::Base.connection.exec_query "SET LOCAL enable_mergejoin to true;"
121
122   ActiveRecord::Base.connection.exec_delete %{
123 delete from #{PERMISSION_VIEW} where
124   target_uuid in (select target_uuid from #{temptable_perms}) and
125   not exists (select 1 from #{temptable_perms}
126               where target_uuid=#{PERMISSION_VIEW}.target_uuid and
127                     user_uuid=#{PERMISSION_VIEW}.user_uuid and
128                     val>0)
129 },
130                                         "update_permissions.delete"
131
132   ActiveRecord::Base.connection.exec_query %{
133 insert into #{PERMISSION_VIEW} (user_uuid, target_uuid, perm_level, traverse_owned)
134   select user_uuid, target_uuid, val as perm_level, traverse_owned from #{temptable_perms} where val>0
135 on conflict (user_uuid, target_uuid) do update set perm_level=EXCLUDED.perm_level, traverse_owned=EXCLUDED.traverse_owned;
136 },
137                                            "update_permissions.insert"
138
139   if check and perm_level>0
140     check_permissions_against_full_refresh
141   end
142 end
143
144
145 def check_permissions_against_full_refresh
146   #
147   # For debugging, this checks contents of the
148   # incrementally-updated 'materialized_permission' against a
149   # from-scratch permission refresh.
150   #
151
152   q1 = ActiveRecord::Base.connection.exec_query %{
153 select user_uuid, target_uuid, perm_level, traverse_owned from #{PERMISSION_VIEW}
154 order by user_uuid, target_uuid
155 }, "check_permissions_against_full_refresh.permission_table"
156
157   q2 = ActiveRecord::Base.connection.exec_query %{
158 select users.uuid as user_uuid, g.target_uuid, g.val as perm_level, g.traverse_owned
159 from users, lateral search_permission_graph(users.uuid, 3) as g where g.val > 0
160 order by users.uuid, target_uuid
161 }, "check_permissions_against_full_refresh.full_recompute"
162
163   if q1.count != q2.count
164     puts "Didn't match incremental+: #{q1.count} != full refresh-: #{q2.count}"
165   end
166
167   if q1.count > q2.count
168     q1.each_with_index do |r, i|
169       if r != q2[i]
170         puts "+#{r}\n-#{q2[i]}"
171         raise "Didn't match"
172       end
173     end
174   else
175     q2.each_with_index do |r, i|
176       if r != q1[i]
177         puts "+#{q1[i]}\n-#{r}"
178         raise "Didn't match"
179       end
180     end
181   end
182 end