|
| 1 | +# Copyright 2023 The Matrix.org Foundation C.I.C. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import logging |
| 16 | +from collections import Counter |
| 17 | +from typing import TYPE_CHECKING, Collection, List, Tuple |
| 18 | + |
| 19 | +from synapse.api.errors import SynapseError |
| 20 | +from synapse.storage.database import LoggingTransaction |
| 21 | +from synapse.storage.databases import Databases |
| 22 | +from synapse.storage.engines import PostgresEngine |
| 23 | + |
| 24 | +if TYPE_CHECKING: |
| 25 | + from synapse.server import HomeServer |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | + |
| 30 | +class StatsController: |
| 31 | + """High level interface for getting statistics.""" |
| 32 | + |
| 33 | + def __init__(self, hs: "HomeServer", stores: Databases): |
| 34 | + self.stores = stores |
| 35 | + |
| 36 | + async def get_room_db_size_estimate(self) -> List[Tuple[str, int]]: |
| 37 | + """Get an estimate of the largest rooms and how much database space they |
| 38 | + use, in bytes. |
| 39 | +
|
| 40 | + Only works against PostgreSQL. |
| 41 | +
|
| 42 | + Note: this uses the postgres statistics so is a very rough estimate. |
| 43 | + """ |
| 44 | + |
| 45 | + # Note: We look at both tables on the main and state databases. |
| 46 | + if not isinstance(self.stores.main.database_engine, PostgresEngine): |
| 47 | + raise SynapseError(400, "Endpoint requires using PostgreSQL") |
| 48 | + |
| 49 | + if not isinstance(self.stores.state.database_engine, PostgresEngine): |
| 50 | + raise SynapseError(400, "Endpoint requires using PostgreSQL") |
| 51 | + |
| 52 | + # For each "large" table, we go through and get the largest rooms |
| 53 | + # and an estimate of how much space they take. We can then sum the |
| 54 | + # results and return the top 10. |
| 55 | + # |
| 56 | + # This isn't the most accurate, but given all of these are estimates |
| 57 | + # anyway its good enough. |
| 58 | + room_estimates: Counter[str] = Counter() |
| 59 | + |
| 60 | + # Return size of the table on disk, including indexes and TOAST. |
| 61 | + table_sql = """ |
| 62 | + SELECT pg_total_relation_size(?) |
| 63 | + """ |
| 64 | + |
| 65 | + # Get an estimate for the largest rooms and their frequency. |
| 66 | + # |
| 67 | + # Note: the cast here is a hack to cast from `anyarray` to an actual |
| 68 | + # type. This ensures that psycopg2 passes us a back a a Python list. |
| 69 | + column_sql = """ |
| 70 | + SELECT |
| 71 | + most_common_vals::TEXT::TEXT[], most_common_freqs::TEXT::NUMERIC[] |
| 72 | + FROM pg_stats |
| 73 | + WHERE tablename = ? and attname = 'room_id' |
| 74 | + """ |
| 75 | + |
| 76 | + def get_room_db_size_estimate_txn( |
| 77 | + txn: LoggingTransaction, |
| 78 | + tables: Collection[str], |
| 79 | + ) -> None: |
| 80 | + for table in tables: |
| 81 | + txn.execute(table_sql, (table,)) |
| 82 | + row = txn.fetchone() |
| 83 | + assert row is not None |
| 84 | + (table_size,) = row |
| 85 | + |
| 86 | + txn.execute(column_sql, (table,)) |
| 87 | + row = txn.fetchone() |
| 88 | + assert row is not None |
| 89 | + vals, freqs = row |
| 90 | + |
| 91 | + for room_id, freq in zip(vals, freqs): |
| 92 | + room_estimates[room_id] += int(freq * table_size) |
| 93 | + |
| 94 | + await self.stores.main.db_pool.runInteraction( |
| 95 | + "get_room_db_size_estimate_main", |
| 96 | + get_room_db_size_estimate_txn, |
| 97 | + ( |
| 98 | + "event_json", |
| 99 | + "events", |
| 100 | + "event_search", |
| 101 | + "event_edges", |
| 102 | + "event_push_actions", |
| 103 | + "stream_ordering_to_exterm", |
| 104 | + ), |
| 105 | + ) |
| 106 | + |
| 107 | + await self.stores.state.db_pool.runInteraction( |
| 108 | + "get_room_db_size_estimate_state", |
| 109 | + get_room_db_size_estimate_txn, |
| 110 | + ("state_groups_state",), |
| 111 | + ) |
| 112 | + |
| 113 | + return room_estimates.most_common(10) |
0 commit comments