Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 30e9adf

Browse files
authored
Merge pull request #6487 from matrix-org/erikj/pass_in_db
Pass in Database object to data stores.
2 parents e1544b0 + 65b37f6 commit 30e9adf

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+242
-244
lines changed

.buildkite/postgres-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Configuration file used for testing the 'synapse_port_db' script.
22
# Tells the script to connect to the postgresql database that will be available in the
33
# CI's Docker setup at the point where this file is considered.
4-
server_name: "test"
4+
server_name: "localhost:8800"
55

66
signing_key_path: "/src/.buildkite/test.signing.key"
77

.buildkite/sqlite-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Configuration file used for testing the 'synapse_port_db' script.
22
# Tells the 'update_database' script to connect to the test SQLite database to upgrade its
33
# schema and run background updates on it.
4-
server_name: "test"
4+
server_name: "localhost:8800"
55

66
signing_key_path: "/src/.buildkite/test.signing.key"
77

changelog.d/6487.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pass in `Database` object to data stores.

scripts/synapse_port_db

Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ from synapse.storage.data_stores.main.stats import StatsStore
5555
from synapse.storage.data_stores.main.user_directory import (
5656
UserDirectoryBackgroundUpdateStore,
5757
)
58+
from synapse.storage.database import Database
5859
from synapse.storage.engines import create_engine
5960
from synapse.storage.prepare_database import prepare_database
6061
from synapse.util import Clock
@@ -139,39 +140,6 @@ class Store(
139140
UserDirectoryBackgroundUpdateStore,
140141
StatsStore,
141142
):
142-
def __init__(self, db_conn, hs):
143-
super().__init__(db_conn, hs)
144-
self.db_pool = hs.get_db_pool()
145-
146-
@defer.inlineCallbacks
147-
def runInteraction(self, desc, func, *args, **kwargs):
148-
def r(conn):
149-
try:
150-
i = 0
151-
N = 5
152-
while True:
153-
try:
154-
txn = conn.cursor()
155-
return func(
156-
LoggingTransaction(txn, desc, self.database_engine, [], []),
157-
*args,
158-
**kwargs
159-
)
160-
except self.database_engine.module.DatabaseError as e:
161-
if self.database_engine.is_deadlock(e):
162-
logger.warning("[TXN DEADLOCK] {%s} %d/%d", desc, i, N)
163-
if i < N:
164-
i += 1
165-
conn.rollback()
166-
continue
167-
raise
168-
except Exception as e:
169-
logger.debug("[TXN FAIL] {%s} %s", desc, e)
170-
raise
171-
172-
with PreserveLoggingContext():
173-
return (yield self.db_pool.runWithConnection(r))
174-
175143
def execute(self, f, *args, **kwargs):
176144
return self.db.runInteraction(f.__name__, f, *args, **kwargs)
177145

@@ -512,7 +480,7 @@ class Porter(object):
512480

513481
hs = MockHomeserver(self.hs_config, engine, conn, db_pool)
514482

515-
store = Store(conn, hs)
483+
store = Store(Database(hs), conn, hs)
516484

517485
yield store.db.runInteraction(
518486
"%s_engine.check_database" % config["name"], engine.check_database,

synapse/app/federation_sender.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
from synapse.replication.tcp.client import ReplicationClientHandler
4141
from synapse.replication.tcp.streams._base import ReceiptsStream
4242
from synapse.server import HomeServer
43+
from synapse.storage.database import Database
4344
from synapse.storage.engines import create_engine
4445
from synapse.types import ReadReceipt
4546
from synapse.util.async_helpers import Linearizer
@@ -59,8 +60,8 @@ class FederationSenderSlaveStore(
5960
SlavedDeviceStore,
6061
SlavedPresenceStore,
6162
):
62-
def __init__(self, db_conn, hs):
63-
super(FederationSenderSlaveStore, self).__init__(db_conn, hs)
63+
def __init__(self, database: Database, db_conn, hs):
64+
super(FederationSenderSlaveStore, self).__init__(database, db_conn, hs)
6465

6566
# We pull out the current federation stream position now so that we
6667
# always have a known value for the federation position in memory so

synapse/app/homeserver.py

Lines changed: 6 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,9 @@
6868
from synapse.rest.media.v0.content_repository import ContentRepoResource
6969
from synapse.rest.well_known import WellKnownResource
7070
from synapse.server import HomeServer
71-
from synapse.storage import DataStore, are_all_users_on_domain
71+
from synapse.storage import DataStore
7272
from synapse.storage.engines import IncorrectDatabaseSetup, create_engine
73-
from synapse.storage.prepare_database import UpgradeDatabaseException, prepare_database
73+
from synapse.storage.prepare_database import UpgradeDatabaseException
7474
from synapse.util.caches import CACHE_SIZE_FACTOR
7575
from synapse.util.httpresourcetree import create_resource_tree
7676
from synapse.util.manhole import manhole
@@ -294,22 +294,6 @@ def start_listening(self, listeners):
294294
else:
295295
logger.warning("Unrecognized listener type: %s", listener["type"])
296296

297-
def run_startup_checks(self, db_conn, database_engine):
298-
all_users_native = are_all_users_on_domain(
299-
db_conn.cursor(), database_engine, self.hostname
300-
)
301-
if not all_users_native:
302-
quit_with_error(
303-
"Found users in database not native to %s!\n"
304-
"You cannot changed a synapse server_name after it's been configured"
305-
% (self.hostname,)
306-
)
307-
308-
try:
309-
database_engine.check_database(db_conn.cursor())
310-
except IncorrectDatabaseSetup as e:
311-
quit_with_error(str(e))
312-
313297

314298
# Gauges to expose monthly active user control metrics
315299
current_mau_gauge = Gauge("synapse_admin_mau:current", "Current MAU")
@@ -357,16 +341,12 @@ def setup(config_options):
357341

358342
synapse.config.logger.setup_logging(hs, config, use_worker_options=False)
359343

360-
logger.info("Preparing database: %s...", config.database_config["name"])
344+
logger.info("Setting up server")
361345

362346
try:
363-
with hs.get_db_conn(run_new_connection=False) as db_conn:
364-
prepare_database(db_conn, database_engine, config=config)
365-
database_engine.on_new_connection(db_conn)
366-
367-
hs.run_startup_checks(db_conn, database_engine)
368-
369-
db_conn.commit()
347+
hs.setup()
348+
except IncorrectDatabaseSetup as e:
349+
quit_with_error(str(e))
370350
except UpgradeDatabaseException:
371351
sys.stderr.write(
372352
"\nFailed to upgrade database.\n"
@@ -375,9 +355,6 @@ def setup(config_options):
375355
)
376356
sys.exit(1)
377357

378-
logger.info("Database prepared in %s.", config.database_config["name"])
379-
380-
hs.setup()
381358
hs.setup_master()
382359

383360
@defer.inlineCallbacks

synapse/app/user_dir.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
from synapse.rest.client.v2_alpha import user_directory
4444
from synapse.server import HomeServer
4545
from synapse.storage.data_stores.main.user_directory import UserDirectoryStore
46+
from synapse.storage.database import Database
4647
from synapse.storage.engines import create_engine
4748
from synapse.util.caches.stream_change_cache import StreamChangeCache
4849
from synapse.util.httpresourcetree import create_resource_tree
@@ -60,8 +61,8 @@ class UserDirectorySlaveStore(
6061
UserDirectoryStore,
6162
BaseSlavedStore,
6263
):
63-
def __init__(self, db_conn, hs):
64-
super(UserDirectorySlaveStore, self).__init__(db_conn, hs)
64+
def __init__(self, database: Database, db_conn, hs):
65+
super(UserDirectorySlaveStore, self).__init__(database, db_conn, hs)
6566

6667
events_max = self._stream_id_gen.get_current_token()
6768
curr_state_delta_prefill, min_curr_state_delta_id = self.db.get_cache_dict(

synapse/replication/slave/storage/_base.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from synapse.storage._base import SQLBaseStore
2222
from synapse.storage.data_stores.main.cache import CURRENT_STATE_CACHE_NAME
23+
from synapse.storage.database import Database
2324
from synapse.storage.engines import PostgresEngine
2425

2526
from ._slaved_id_tracker import SlavedIdTracker
@@ -35,8 +36,8 @@ def __func__(inp):
3536

3637

3738
class BaseSlavedStore(SQLBaseStore):
38-
def __init__(self, db_conn, hs):
39-
super(BaseSlavedStore, self).__init__(db_conn, hs)
39+
def __init__(self, database: Database, db_conn, hs):
40+
super(BaseSlavedStore, self).__init__(database, db_conn, hs)
4041
if isinstance(self.database_engine, PostgresEngine):
4142
self._cache_id_gen = SlavedIdTracker(
4243
db_conn, "cache_invalidation_stream", "stream_id"

synapse/replication/slave/storage/account_data.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,16 @@
1818
from synapse.replication.slave.storage._slaved_id_tracker import SlavedIdTracker
1919
from synapse.storage.data_stores.main.account_data import AccountDataWorkerStore
2020
from synapse.storage.data_stores.main.tags import TagsWorkerStore
21+
from synapse.storage.database import Database
2122

2223

2324
class SlavedAccountDataStore(TagsWorkerStore, AccountDataWorkerStore, BaseSlavedStore):
24-
def __init__(self, db_conn, hs):
25+
def __init__(self, database: Database, db_conn, hs):
2526
self._account_data_id_gen = SlavedIdTracker(
2627
db_conn, "account_data_max_stream_id", "stream_id"
2728
)
2829

29-
super(SlavedAccountDataStore, self).__init__(db_conn, hs)
30+
super(SlavedAccountDataStore, self).__init__(database, db_conn, hs)
3031

3132
def get_max_account_data_stream_id(self):
3233
return self._account_data_id_gen.get_current_token()

synapse/replication/slave/storage/client_ips.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,15 +14,16 @@
1414
# limitations under the License.
1515

1616
from synapse.storage.data_stores.main.client_ips import LAST_SEEN_GRANULARITY
17+
from synapse.storage.database import Database
1718
from synapse.util.caches import CACHE_SIZE_FACTOR
1819
from synapse.util.caches.descriptors import Cache
1920

2021
from ._base import BaseSlavedStore
2122

2223

2324
class SlavedClientIpStore(BaseSlavedStore):
24-
def __init__(self, db_conn, hs):
25-
super(SlavedClientIpStore, self).__init__(db_conn, hs)
25+
def __init__(self, database: Database, db_conn, hs):
26+
super(SlavedClientIpStore, self).__init__(database, db_conn, hs)
2627

2728
self.client_ip_last_seen = Cache(
2829
name="client_ip_last_seen", keylen=4, max_entries=50000 * CACHE_SIZE_FACTOR

0 commit comments

Comments
 (0)