You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1439 lines
49 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. # Copyright 2018 New Vector Ltd
  4. # Copyright 2019 The Matrix.org Foundation C.I.C.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. import argparse
  18. import curses
  19. import logging
  20. import os
  21. import sys
  22. import time
  23. import traceback
  24. from types import TracebackType
  25. from typing import (
  26. Any,
  27. Awaitable,
  28. Callable,
  29. Dict,
  30. Generator,
  31. Iterable,
  32. List,
  33. NoReturn,
  34. Optional,
  35. Set,
  36. Tuple,
  37. Type,
  38. TypeVar,
  39. cast,
  40. )
  41. import yaml
  42. from typing_extensions import TypedDict
  43. from twisted.internet import defer, reactor as reactor_
  44. from synapse.config.database import DatabaseConnectionConfig
  45. from synapse.config.homeserver import HomeServerConfig
  46. from synapse.logging.context import (
  47. LoggingContext,
  48. make_deferred_yieldable,
  49. run_in_background,
  50. )
  51. from synapse.notifier import ReplicationNotifier
  52. from synapse.storage.database import DatabasePool, LoggingTransaction, make_conn
  53. from synapse.storage.databases.main import FilteringWorkerStore, PushRuleStore
  54. from synapse.storage.databases.main.account_data import AccountDataWorkerStore
  55. from synapse.storage.databases.main.client_ips import ClientIpBackgroundUpdateStore
  56. from synapse.storage.databases.main.deviceinbox import DeviceInboxBackgroundUpdateStore
  57. from synapse.storage.databases.main.devices import DeviceBackgroundUpdateStore
  58. from synapse.storage.databases.main.e2e_room_keys import EndToEndRoomKeyBackgroundStore
  59. from synapse.storage.databases.main.end_to_end_keys import EndToEndKeyBackgroundStore
  60. from synapse.storage.databases.main.event_federation import EventFederationWorkerStore
  61. from synapse.storage.databases.main.event_push_actions import EventPushActionsStore
  62. from synapse.storage.databases.main.events_bg_updates import (
  63. EventsBackgroundUpdatesStore,
  64. )
  65. from synapse.storage.databases.main.media_repository import (
  66. MediaRepositoryBackgroundUpdateStore,
  67. )
  68. from synapse.storage.databases.main.presence import PresenceBackgroundUpdateStore
  69. from synapse.storage.databases.main.profile import ProfileWorkerStore
  70. from synapse.storage.databases.main.pusher import (
  71. PusherBackgroundUpdatesStore,
  72. PusherWorkerStore,
  73. )
  74. from synapse.storage.databases.main.receipts import ReceiptsBackgroundUpdateStore
  75. from synapse.storage.databases.main.registration import (
  76. RegistrationBackgroundUpdateStore,
  77. find_max_generated_user_id_localpart,
  78. )
  79. from synapse.storage.databases.main.relations import RelationsWorkerStore
  80. from synapse.storage.databases.main.room import RoomBackgroundUpdateStore
  81. from synapse.storage.databases.main.roommember import RoomMemberBackgroundUpdateStore
  82. from synapse.storage.databases.main.search import SearchBackgroundUpdateStore
  83. from synapse.storage.databases.main.state import MainStateBackgroundUpdateStore
  84. from synapse.storage.databases.main.stats import StatsStore
  85. from synapse.storage.databases.main.user_directory import (
  86. UserDirectoryBackgroundUpdateStore,
  87. )
  88. from synapse.storage.databases.state.bg_updates import StateBackgroundUpdateStore
  89. from synapse.storage.engines import create_engine
  90. from synapse.storage.prepare_database import prepare_database
  91. from synapse.types import ISynapseReactor
  92. from synapse.util import SYNAPSE_VERSION, Clock
  93. # Cast safety: Twisted does some naughty magic which replaces the
  94. # twisted.internet.reactor module with a Reactor instance at runtime.
  95. reactor = cast(ISynapseReactor, reactor_)
  96. logger = logging.getLogger("synapse_port_db")
  97. # SQLite doesn't have a dedicated boolean type (it stores True/False as 1/0). This means
  98. # portdb will read sqlite bools as integers, then try to insert them into postgres
  99. # boolean columns---which fails. Lacking some Python-parseable metaschema, we must
  100. # specify which integer columns should be inserted as booleans into postgres.
  101. BOOLEAN_COLUMNS = {
  102. "access_tokens": ["used"],
  103. "account_validity": ["email_sent"],
  104. "device_lists_changes_in_room": ["converted_to_destinations"],
  105. "device_lists_outbound_pokes": ["sent"],
  106. "devices": ["hidden"],
  107. "e2e_fallback_keys_json": ["used"],
  108. "e2e_room_keys": ["is_verified"],
  109. "event_edges": ["is_state"],
  110. "events": ["processed", "outlier", "contains_url"],
  111. "local_media_repository": ["safe_from_quarantine"],
  112. "presence_list": ["accepted"],
  113. "presence_stream": ["currently_active"],
  114. "public_room_list_stream": ["visibility"],
  115. "pushers": ["enabled"],
  116. "redactions": ["have_censored"],
  117. "room_stats_state": ["is_federatable"],
  118. "rooms": ["is_public", "has_auth_chain_index"],
  119. "users": ["shadow_banned", "approved", "locked"],
  120. "un_partial_stated_event_stream": ["rejection_status_changed"],
  121. "users_who_share_rooms": ["share_private"],
  122. "per_user_experimental_features": ["enabled"],
  123. }
  124. # These tables are never deleted from in normal operation [*], so we can resume porting
  125. # over rows from a previous attempt rather than starting from scratch.
  126. #
  127. # [*]: We do delete from many of these tables when purging a room, and
  128. # presumably when purging old events. So we might e.g.
  129. #
  130. # 1. Run portdb and port half of some table.
  131. # 2. Stop portdb.
  132. # 3. Purge something, deleting some of the rows we've ported over.
  133. # 4. Restart portdb. The rows deleted from sqlite are still present in postgres.
  134. #
  135. # But this isn't the end of the world: we should be able to repeat the purge
  136. # on the postgres DB when porting completes.
  137. APPEND_ONLY_TABLES = [
  138. "cache_invalidation_stream_by_instance",
  139. "event_auth",
  140. "event_edges",
  141. "event_json",
  142. "event_reference_hashes",
  143. "event_search",
  144. "event_to_state_groups",
  145. "events",
  146. "ex_outlier_stream",
  147. "local_media_repository",
  148. "local_media_repository_thumbnails",
  149. "presence_stream",
  150. "public_room_list_stream",
  151. "push_rules_stream",
  152. "received_transactions",
  153. "redactions",
  154. "rejections",
  155. "remote_media_cache",
  156. "remote_media_cache_thumbnails",
  157. "room_memberships",
  158. "room_names",
  159. "rooms",
  160. "sent_transactions",
  161. "state_events",
  162. "state_group_edges",
  163. "state_groups",
  164. "state_groups_state",
  165. "stream_ordering_to_exterm",
  166. "topics",
  167. "transaction_id_to_pdu",
  168. "un_partial_stated_event_stream",
  169. "users",
  170. ]
  171. IGNORED_TABLES = {
  172. # We don't port these tables, as they're a faff and we can regenerate
  173. # them anyway.
  174. "user_directory",
  175. "user_directory_search",
  176. "user_directory_search_content",
  177. "user_directory_search_docsize",
  178. "user_directory_search_segdir",
  179. "user_directory_search_segments",
  180. "user_directory_search_stat",
  181. "user_directory_search_pos",
  182. "users_who_share_private_rooms",
  183. "users_in_public_room",
  184. # UI auth sessions have foreign keys so additional care needs to be taken,
  185. # the sessions are transient anyway, so ignore them.
  186. "ui_auth_sessions",
  187. "ui_auth_sessions_credentials",
  188. "ui_auth_sessions_ips",
  189. # Ignore the worker locks table, as a) there shouldn't be any acquired locks
  190. # after porting, and b) the circular foreign key constraints make it hard to
  191. # port.
  192. "worker_read_write_locks_mode",
  193. "worker_read_write_locks",
  194. }
  195. # Error returned by the run function. Used at the top-level part of the script to
  196. # handle errors and return codes.
  197. end_error: Optional[str] = None
  198. # The exec_info for the error, if any. If error is defined but not exec_info the script
  199. # will show only the error message without the stacktrace, if exec_info is defined but
  200. # not the error then the script will show nothing outside of what's printed in the run
  201. # function. If both are defined, the script will print both the error and the stacktrace.
  202. end_error_exec_info: Optional[
  203. Tuple[Type[BaseException], BaseException, TracebackType]
  204. ] = None
  205. R = TypeVar("R")
  206. class Store(
  207. EventPushActionsStore,
  208. ClientIpBackgroundUpdateStore,
  209. DeviceInboxBackgroundUpdateStore,
  210. DeviceBackgroundUpdateStore,
  211. EventsBackgroundUpdatesStore,
  212. MediaRepositoryBackgroundUpdateStore,
  213. RegistrationBackgroundUpdateStore,
  214. RoomBackgroundUpdateStore,
  215. RoomMemberBackgroundUpdateStore,
  216. SearchBackgroundUpdateStore,
  217. StateBackgroundUpdateStore,
  218. MainStateBackgroundUpdateStore,
  219. UserDirectoryBackgroundUpdateStore,
  220. EndToEndKeyBackgroundStore,
  221. EndToEndRoomKeyBackgroundStore,
  222. StatsStore,
  223. AccountDataWorkerStore,
  224. FilteringWorkerStore,
  225. ProfileWorkerStore,
  226. PushRuleStore,
  227. PusherWorkerStore,
  228. PusherBackgroundUpdatesStore,
  229. PresenceBackgroundUpdateStore,
  230. ReceiptsBackgroundUpdateStore,
  231. RelationsWorkerStore,
  232. EventFederationWorkerStore,
  233. ):
  234. def execute(self, f: Callable[..., R], *args: Any, **kwargs: Any) -> Awaitable[R]:
  235. return self.db_pool.runInteraction(f.__name__, f, *args, **kwargs)
  236. def execute_sql(self, sql: str, *args: object) -> Awaitable[List[Tuple]]:
  237. def r(txn: LoggingTransaction) -> List[Tuple]:
  238. txn.execute(sql, args)
  239. return txn.fetchall()
  240. return self.db_pool.runInteraction("execute_sql", r)
  241. def insert_many_txn(
  242. self, txn: LoggingTransaction, table: str, headers: List[str], rows: List[Tuple]
  243. ) -> None:
  244. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  245. table,
  246. ", ".join(k for k in headers),
  247. ", ".join("%s" for _ in headers),
  248. )
  249. try:
  250. txn.executemany(sql, rows)
  251. except Exception:
  252. logger.exception("Failed to insert: %s", table)
  253. raise
  254. # Note: the parent method is an `async def`.
  255. def set_room_is_public(self, room_id: str, is_public: bool) -> NoReturn:
  256. raise Exception(
  257. "Attempt to set room_is_public during port_db: database not empty?"
  258. )
  259. class MockHomeserver:
  260. def __init__(self, config: HomeServerConfig):
  261. self.clock = Clock(reactor)
  262. self.config = config
  263. self.hostname = config.server.server_name
  264. self.version_string = SYNAPSE_VERSION
  265. def get_clock(self) -> Clock:
  266. return self.clock
  267. def get_reactor(self) -> ISynapseReactor:
  268. return reactor
  269. def get_instance_name(self) -> str:
  270. return "master"
  271. def should_send_federation(self) -> bool:
  272. return False
  273. def get_replication_notifier(self) -> ReplicationNotifier:
  274. return ReplicationNotifier()
  275. class Porter:
  276. def __init__(
  277. self,
  278. sqlite_config: Dict[str, Any],
  279. progress: "Progress",
  280. batch_size: int,
  281. hs_config: HomeServerConfig,
  282. ):
  283. self.sqlite_config = sqlite_config
  284. self.progress = progress
  285. self.batch_size = batch_size
  286. self.hs_config = hs_config
  287. async def setup_table(self, table: str) -> Tuple[str, int, int, int, int]:
  288. if table in APPEND_ONLY_TABLES:
  289. # It's safe to just carry on inserting.
  290. row = await self.postgres_store.db_pool.simple_select_one(
  291. table="port_from_sqlite3",
  292. keyvalues={"table_name": table},
  293. retcols=("forward_rowid", "backward_rowid"),
  294. allow_none=True,
  295. )
  296. total_to_port = None
  297. if row is None:
  298. if table == "sent_transactions":
  299. (
  300. forward_chunk,
  301. already_ported,
  302. total_to_port,
  303. ) = await self._setup_sent_transactions()
  304. backward_chunk = 0
  305. else:
  306. await self.postgres_store.db_pool.simple_insert(
  307. table="port_from_sqlite3",
  308. values={
  309. "table_name": table,
  310. "forward_rowid": 1,
  311. "backward_rowid": 0,
  312. },
  313. )
  314. forward_chunk = 1
  315. backward_chunk = 0
  316. already_ported = 0
  317. else:
  318. forward_chunk = row["forward_rowid"]
  319. backward_chunk = row["backward_rowid"]
  320. if total_to_port is None:
  321. already_ported, total_to_port = await self._get_total_count_to_port(
  322. table, forward_chunk, backward_chunk
  323. )
  324. else:
  325. def delete_all(txn: LoggingTransaction) -> None:
  326. txn.execute(
  327. "DELETE FROM port_from_sqlite3 WHERE table_name = %s", (table,)
  328. )
  329. txn.execute("TRUNCATE %s CASCADE" % (table,))
  330. await self.postgres_store.execute(delete_all)
  331. await self.postgres_store.db_pool.simple_insert(
  332. table="port_from_sqlite3",
  333. values={"table_name": table, "forward_rowid": 1, "backward_rowid": 0},
  334. )
  335. forward_chunk = 1
  336. backward_chunk = 0
  337. already_ported, total_to_port = await self._get_total_count_to_port(
  338. table, forward_chunk, backward_chunk
  339. )
  340. return table, already_ported, total_to_port, forward_chunk, backward_chunk
  341. async def get_table_constraints(self) -> Dict[str, Set[str]]:
  342. """Returns a map of tables that have foreign key constraints to tables they depend on."""
  343. def _get_constraints(txn: LoggingTransaction) -> Dict[str, Set[str]]:
  344. # We can pull the information about foreign key constraints out from
  345. # the postgres schema tables.
  346. sql = """
  347. SELECT DISTINCT
  348. tc.table_name,
  349. ccu.table_name AS foreign_table_name
  350. FROM
  351. information_schema.table_constraints AS tc
  352. INNER JOIN information_schema.constraint_column_usage AS ccu
  353. USING (table_schema, constraint_name)
  354. WHERE tc.constraint_type = 'FOREIGN KEY'
  355. AND tc.table_name != ccu.table_name;
  356. """
  357. txn.execute(sql)
  358. results: Dict[str, Set[str]] = {}
  359. for table, foreign_table in txn:
  360. results.setdefault(table, set()).add(foreign_table)
  361. return results
  362. return await self.postgres_store.db_pool.runInteraction(
  363. "get_table_constraints", _get_constraints
  364. )
  365. async def handle_table(
  366. self,
  367. table: str,
  368. postgres_size: int,
  369. table_size: int,
  370. forward_chunk: int,
  371. backward_chunk: int,
  372. ) -> None:
  373. logger.info(
  374. "Table %s: %i/%i (rows %i-%i) already ported",
  375. table,
  376. postgres_size,
  377. table_size,
  378. backward_chunk + 1,
  379. forward_chunk - 1,
  380. )
  381. if not table_size:
  382. return
  383. self.progress.add_table(table, postgres_size, table_size)
  384. if table == "event_search":
  385. await self.handle_search_table(
  386. postgres_size, table_size, forward_chunk, backward_chunk
  387. )
  388. return
  389. if table in IGNORED_TABLES:
  390. self.progress.update(table, table_size) # Mark table as done
  391. return
  392. if table == "user_directory_stream_pos":
  393. # We need to make sure there is a single row, `(X, null), as that is
  394. # what synapse expects to be there.
  395. await self.postgres_store.db_pool.simple_insert(
  396. table=table, values={"stream_id": None}
  397. )
  398. self.progress.update(table, table_size) # Mark table as done
  399. return
  400. # We sweep over rowids in two directions: one forwards (rowids 1, 2, 3, ...)
  401. # and another backwards (rowids 0, -1, -2, ...).
  402. forward_select = (
  403. "SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?" % (table,)
  404. )
  405. backward_select = (
  406. "SELECT rowid, * FROM %s WHERE rowid <= ? ORDER BY rowid DESC LIMIT ?"
  407. % (table,)
  408. )
  409. do_forward = [True]
  410. do_backward = [True]
  411. while True:
  412. def r(
  413. txn: LoggingTransaction,
  414. ) -> Tuple[Optional[List[str]], List[Tuple], List[Tuple]]:
  415. forward_rows = []
  416. backward_rows = []
  417. if do_forward[0]:
  418. txn.execute(forward_select, (forward_chunk, self.batch_size))
  419. forward_rows = txn.fetchall()
  420. if not forward_rows:
  421. do_forward[0] = False
  422. if do_backward[0]:
  423. txn.execute(backward_select, (backward_chunk, self.batch_size))
  424. backward_rows = txn.fetchall()
  425. if not backward_rows:
  426. do_backward[0] = False
  427. if forward_rows or backward_rows:
  428. headers = [column[0] for column in txn.description]
  429. else:
  430. headers = None
  431. return headers, forward_rows, backward_rows
  432. headers, frows, brows = await self.sqlite_store.db_pool.runInteraction(
  433. "select", r
  434. )
  435. if frows or brows:
  436. assert headers is not None
  437. if frows:
  438. forward_chunk = max(row[0] for row in frows) + 1
  439. if brows:
  440. backward_chunk = min(row[0] for row in brows) - 1
  441. rows = frows + brows
  442. rows = self._convert_rows(table, headers, rows)
  443. def insert(txn: LoggingTransaction) -> None:
  444. assert headers is not None
  445. self.postgres_store.insert_many_txn(txn, table, headers[1:], rows)
  446. self.postgres_store.db_pool.simple_update_one_txn(
  447. txn,
  448. table="port_from_sqlite3",
  449. keyvalues={"table_name": table},
  450. updatevalues={
  451. "forward_rowid": forward_chunk,
  452. "backward_rowid": backward_chunk,
  453. },
  454. )
  455. await self.postgres_store.execute(insert)
  456. postgres_size += len(rows)
  457. self.progress.update(table, postgres_size)
  458. else:
  459. return
  460. async def handle_search_table(
  461. self,
  462. postgres_size: int,
  463. table_size: int,
  464. forward_chunk: int,
  465. backward_chunk: int,
  466. ) -> None:
  467. select = (
  468. "SELECT es.rowid, es.*, e.origin_server_ts, e.stream_ordering"
  469. " FROM event_search as es"
  470. " INNER JOIN events AS e USING (event_id, room_id)"
  471. " WHERE es.rowid >= ?"
  472. " ORDER BY es.rowid LIMIT ?"
  473. )
  474. while True:
  475. def r(txn: LoggingTransaction) -> Tuple[List[str], List[Tuple]]:
  476. txn.execute(select, (forward_chunk, self.batch_size))
  477. rows = txn.fetchall()
  478. headers = [column[0] for column in txn.description]
  479. return headers, rows
  480. headers, rows = await self.sqlite_store.db_pool.runInteraction("select", r)
  481. if rows:
  482. forward_chunk = rows[-1][0] + 1
  483. # We have to treat event_search differently since it has a
  484. # different structure in the two different databases.
  485. def insert(txn: LoggingTransaction) -> None:
  486. sql = (
  487. "INSERT INTO event_search (event_id, room_id, key,"
  488. " sender, vector, origin_server_ts, stream_ordering)"
  489. " VALUES (?,?,?,?,to_tsvector('english', ?),?,?)"
  490. )
  491. rows_dict = []
  492. for row in rows:
  493. d = dict(zip(headers, row))
  494. if "\0" in d["value"]:
  495. logger.warning("dropping search row %s", d)
  496. else:
  497. rows_dict.append(d)
  498. txn.executemany(
  499. sql,
  500. [
  501. (
  502. row["event_id"],
  503. row["room_id"],
  504. row["key"],
  505. row["sender"],
  506. row["value"],
  507. row["origin_server_ts"],
  508. row["stream_ordering"],
  509. )
  510. for row in rows_dict
  511. ],
  512. )
  513. self.postgres_store.db_pool.simple_update_one_txn(
  514. txn,
  515. table="port_from_sqlite3",
  516. keyvalues={"table_name": "event_search"},
  517. updatevalues={
  518. "forward_rowid": forward_chunk,
  519. "backward_rowid": backward_chunk,
  520. },
  521. )
  522. await self.postgres_store.execute(insert)
  523. postgres_size += len(rows)
  524. self.progress.update("event_search", postgres_size)
  525. else:
  526. return
  527. def build_db_store(
  528. self,
  529. db_config: DatabaseConnectionConfig,
  530. allow_outdated_version: bool = False,
  531. ) -> Store:
  532. """Builds and returns a database store using the provided configuration.
  533. Args:
  534. db_config: The database configuration
  535. allow_outdated_version: True to suppress errors about the database server
  536. version being too old to run a complete synapse
  537. Returns:
  538. The built Store object.
  539. """
  540. self.progress.set_state("Preparing %s" % db_config.config["name"])
  541. engine = create_engine(db_config.config)
  542. hs = MockHomeserver(self.hs_config)
  543. with make_conn(db_config, engine, "portdb") as db_conn:
  544. engine.check_database(
  545. db_conn, allow_outdated_version=allow_outdated_version
  546. )
  547. prepare_database(db_conn, engine, config=self.hs_config)
  548. # Type safety: ignore that we're using Mock homeservers here.
  549. store = Store(DatabasePool(hs, db_config, engine), db_conn, hs) # type: ignore[arg-type]
  550. db_conn.commit()
  551. return store
  552. async def run_background_updates_on_postgres(self) -> None:
  553. # Manually apply all background updates on the PostgreSQL database.
  554. postgres_ready = (
  555. await self.postgres_store.db_pool.updates.has_completed_background_updates()
  556. )
  557. if not postgres_ready:
  558. # Only say that we're running background updates when there are background
  559. # updates to run.
  560. self.progress.set_state("Running background updates on PostgreSQL")
  561. while not postgres_ready:
  562. await self.postgres_store.db_pool.updates.do_next_background_update(True)
  563. postgres_ready = await (
  564. self.postgres_store.db_pool.updates.has_completed_background_updates()
  565. )
  566. @staticmethod
  567. def _is_sqlite_autovacuum_enabled(txn: LoggingTransaction) -> bool:
  568. """
  569. Returns true if auto_vacuum is enabled in SQLite.
  570. https://www.sqlite.org/pragma.html#pragma_auto_vacuum
  571. Vacuuming changes the rowids on rows in the database.
  572. Auto-vacuuming is therefore dangerous when used in conjunction with this script.
  573. Note that the auto_vacuum setting can't be changed without performing
  574. a VACUUM after trying to change the pragma.
  575. """
  576. txn.execute("PRAGMA auto_vacuum")
  577. row = txn.fetchone()
  578. assert row is not None, "`PRAGMA auto_vacuum` did not give a row."
  579. (autovacuum_setting,) = row
  580. # 0 means off. 1 means full. 2 means incremental.
  581. return autovacuum_setting != 0
  582. async def run(self) -> None:
  583. """Ports the SQLite database to a PostgreSQL database.
  584. When a fatal error is met, its message is assigned to the global "end_error"
  585. variable. When this error comes with a stacktrace, its exec_info is assigned to
  586. the global "end_error_exec_info" variable.
  587. """
  588. global end_error
  589. try:
  590. # we allow people to port away from outdated versions of sqlite.
  591. self.sqlite_store = self.build_db_store(
  592. DatabaseConnectionConfig("master-sqlite", self.sqlite_config),
  593. allow_outdated_version=True,
  594. )
  595. # For safety, ensure auto_vacuums are disabled.
  596. if await self.sqlite_store.db_pool.runInteraction(
  597. "is_sqlite_autovacuum_enabled", self._is_sqlite_autovacuum_enabled
  598. ):
  599. end_error = (
  600. "auto_vacuum is enabled in the SQLite database."
  601. " (This is not the default configuration.)\n"
  602. " This script relies on rowids being consistent and must not"
  603. " be used if the database could be vacuumed between re-runs.\n"
  604. " To disable auto_vacuum, you need to stop Synapse and run the following SQL:\n"
  605. " PRAGMA auto_vacuum=off;\n"
  606. " VACUUM;"
  607. )
  608. return
  609. # Check if all background updates are done, abort if not.
  610. updates_complete = (
  611. await self.sqlite_store.db_pool.updates.has_completed_background_updates()
  612. )
  613. if not updates_complete:
  614. end_error = (
  615. "Pending background updates exist in the SQLite3 database."
  616. " Please start Synapse again and wait until every update has finished"
  617. " before running this script.\n"
  618. )
  619. return
  620. self.postgres_store = self.build_db_store(
  621. self.hs_config.database.get_single_database()
  622. )
  623. await self.run_background_updates_on_postgres()
  624. self.progress.set_state("Creating port tables")
  625. def create_port_table(txn: LoggingTransaction) -> None:
  626. txn.execute(
  627. "CREATE TABLE IF NOT EXISTS port_from_sqlite3 ("
  628. " table_name varchar(100) NOT NULL UNIQUE,"
  629. " forward_rowid bigint NOT NULL,"
  630. " backward_rowid bigint NOT NULL"
  631. ")"
  632. )
  633. # The old port script created a table with just a "rowid" column.
  634. # We want people to be able to rerun this script from an old port
  635. # so that they can pick up any missing events that were not
  636. # ported across.
  637. def alter_table(txn: LoggingTransaction) -> None:
  638. txn.execute(
  639. "ALTER TABLE IF EXISTS port_from_sqlite3"
  640. " RENAME rowid TO forward_rowid"
  641. )
  642. txn.execute(
  643. "ALTER TABLE IF EXISTS port_from_sqlite3"
  644. " ADD backward_rowid bigint NOT NULL DEFAULT 0"
  645. )
  646. try:
  647. await self.postgres_store.db_pool.runInteraction(
  648. "alter_table", alter_table
  649. )
  650. except Exception:
  651. # On Error Resume Next
  652. pass
  653. await self.postgres_store.db_pool.runInteraction(
  654. "create_port_table", create_port_table
  655. )
  656. # Step 2. Set up sequences
  657. #
  658. # We do this before porting the tables so that even if we fail half
  659. # way through the postgres DB always have sequences that are greater
  660. # than their respective tables. If we don't then creating the
  661. # `DataStore` object will fail due to the inconsistency.
  662. self.progress.set_state("Setting up sequence generators")
  663. await self._setup_state_group_id_seq()
  664. await self._setup_user_id_seq()
  665. await self._setup_events_stream_seqs()
  666. await self._setup_sequence(
  667. "un_partial_stated_event_stream_sequence",
  668. ("un_partial_stated_event_stream",),
  669. )
  670. await self._setup_sequence(
  671. "device_inbox_sequence", ("device_inbox", "device_federation_outbox")
  672. )
  673. await self._setup_sequence(
  674. "account_data_sequence",
  675. ("room_account_data", "room_tags_revisions", "account_data"),
  676. )
  677. await self._setup_sequence("receipts_sequence", ("receipts_linearized",))
  678. await self._setup_sequence("presence_stream_sequence", ("presence_stream",))
  679. await self._setup_auth_chain_sequence()
  680. await self._setup_sequence(
  681. "application_services_txn_id_seq",
  682. ("application_services_txns",),
  683. "txn_id",
  684. )
  685. # Step 3. Get tables.
  686. self.progress.set_state("Fetching tables")
  687. sqlite_tables = await self.sqlite_store.db_pool.simple_select_onecol(
  688. table="sqlite_master", keyvalues={"type": "table"}, retcol="name"
  689. )
  690. postgres_tables = await self.postgres_store.db_pool.simple_select_onecol(
  691. table="information_schema.tables",
  692. keyvalues={},
  693. retcol="distinct table_name",
  694. )
  695. tables = set(sqlite_tables) & set(postgres_tables)
  696. logger.info("Found %d tables", len(tables))
  697. # Step 4. Figure out what still needs copying
  698. self.progress.set_state("Checking on port progress")
  699. setup_res = await make_deferred_yieldable(
  700. defer.gatherResults(
  701. [
  702. run_in_background(self.setup_table, table)
  703. for table in tables
  704. if table not in ["schema_version", "applied_schema_deltas"]
  705. and not table.startswith("sqlite_")
  706. ],
  707. consumeErrors=True,
  708. )
  709. )
  710. # Map from table name to args passed to `handle_table`, i.e. a tuple
  711. # of: `postgres_size`, `table_size`, `forward_chunk`, `backward_chunk`.
  712. tables_to_port_info_map = {
  713. r[0]: r[1:] for r in setup_res if r[0] not in IGNORED_TABLES
  714. }
  715. # Step 5. Do the copying.
  716. #
  717. # This is slightly convoluted as we need to ensure tables are ported
  718. # in the correct order due to foreign key constraints.
  719. self.progress.set_state("Copying to postgres")
  720. constraints = await self.get_table_constraints()
  721. tables_ported = set() # type: Set[str]
  722. while tables_to_port_info_map:
  723. # Pulls out all tables that are still to be ported and which
  724. # only depend on tables that are already ported (if any).
  725. tables_to_port = [
  726. table
  727. for table in tables_to_port_info_map
  728. if not constraints.get(table, set()) - tables_ported
  729. ]
  730. await make_deferred_yieldable(
  731. defer.gatherResults(
  732. [
  733. run_in_background(
  734. self.handle_table,
  735. table,
  736. *tables_to_port_info_map.pop(table),
  737. )
  738. for table in tables_to_port
  739. ],
  740. consumeErrors=True,
  741. )
  742. )
  743. tables_ported.update(tables_to_port)
  744. self.progress.done()
  745. except Exception as e:
  746. global end_error_exec_info
  747. end_error = str(e)
  748. # Type safety: we're in an exception handler, so the exc_info() tuple
  749. # will not be (None, None, None).
  750. end_error_exec_info = sys.exc_info() # type: ignore[assignment]
  751. logger.exception("")
  752. finally:
  753. reactor.stop()
  754. def _convert_rows(
  755. self, table: str, headers: List[str], rows: List[Tuple]
  756. ) -> List[Tuple]:
  757. bool_col_names = BOOLEAN_COLUMNS.get(table, [])
  758. bool_cols = [i for i, h in enumerate(headers) if h in bool_col_names]
  759. class BadValueException(Exception):
  760. pass
  761. def conv(j: int, col: object) -> object:
  762. if j in bool_cols:
  763. return bool(col)
  764. if isinstance(col, bytes):
  765. return bytearray(col)
  766. elif isinstance(col, str) and "\0" in col:
  767. logger.warning(
  768. "DROPPING ROW: NUL value in table %s col %s: %r",
  769. table,
  770. headers[j],
  771. col,
  772. )
  773. raise BadValueException()
  774. return col
  775. outrows = []
  776. for row in rows:
  777. try:
  778. outrows.append(
  779. tuple(conv(j, col) for j, col in enumerate(row) if j > 0)
  780. )
  781. except BadValueException:
  782. pass
  783. return outrows
  784. async def _setup_sent_transactions(self) -> Tuple[int, int, int]:
  785. # Only save things from the last day
  786. yesterday = int(time.time() * 1000) - 86400000
  787. # And save the max transaction id from each destination
  788. select = (
  789. "SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
  790. "SELECT max(rowid) FROM sent_transactions"
  791. " GROUP BY destination"
  792. ")"
  793. )
  794. def r(txn: LoggingTransaction) -> Tuple[List[str], List[Tuple]]:
  795. txn.execute(select)
  796. rows = txn.fetchall()
  797. headers: List[str] = [column[0] for column in txn.description]
  798. ts_ind = headers.index("ts")
  799. return headers, [r for r in rows if r[ts_ind] < yesterday]
  800. headers, rows = await self.sqlite_store.db_pool.runInteraction("select", r)
  801. rows = self._convert_rows("sent_transactions", headers, rows)
  802. inserted_rows = len(rows)
  803. if inserted_rows:
  804. max_inserted_rowid = max(r[0] for r in rows)
  805. def insert(txn: LoggingTransaction) -> None:
  806. self.postgres_store.insert_many_txn(
  807. txn, "sent_transactions", headers[1:], rows
  808. )
  809. await self.postgres_store.execute(insert)
  810. else:
  811. max_inserted_rowid = 0
  812. def get_start_id(txn: LoggingTransaction) -> int:
  813. txn.execute(
  814. "SELECT rowid FROM sent_transactions WHERE ts >= ?"
  815. " ORDER BY rowid ASC LIMIT 1",
  816. (yesterday,),
  817. )
  818. rows = txn.fetchall()
  819. if rows:
  820. return rows[0][0]
  821. else:
  822. return 1
  823. next_chunk = await self.sqlite_store.execute(get_start_id)
  824. next_chunk = max(max_inserted_rowid + 1, next_chunk)
  825. await self.postgres_store.db_pool.simple_insert(
  826. table="port_from_sqlite3",
  827. values={
  828. "table_name": "sent_transactions",
  829. "forward_rowid": next_chunk,
  830. "backward_rowid": 0,
  831. },
  832. )
  833. def get_sent_table_size(txn: LoggingTransaction) -> int:
  834. txn.execute(
  835. "SELECT count(*) FROM sent_transactions" " WHERE ts >= ?", (yesterday,)
  836. )
  837. result = txn.fetchone()
  838. assert result is not None
  839. return int(result[0])
  840. remaining_count = await self.sqlite_store.execute(get_sent_table_size)
  841. total_count = remaining_count + inserted_rows
  842. return next_chunk, inserted_rows, total_count
  843. async def _get_remaining_count_to_port(
  844. self, table: str, forward_chunk: int, backward_chunk: int
  845. ) -> int:
  846. frows = cast(
  847. List[Tuple[int]],
  848. await self.sqlite_store.execute_sql(
  849. "SELECT count(*) FROM %s WHERE rowid >= ?" % (table,), forward_chunk
  850. ),
  851. )
  852. brows = cast(
  853. List[Tuple[int]],
  854. await self.sqlite_store.execute_sql(
  855. "SELECT count(*) FROM %s WHERE rowid <= ?" % (table,), backward_chunk
  856. ),
  857. )
  858. return frows[0][0] + brows[0][0]
  859. async def _get_already_ported_count(self, table: str) -> int:
  860. rows = await self.postgres_store.execute_sql(
  861. "SELECT count(*) FROM %s" % (table,)
  862. )
  863. return rows[0][0]
  864. async def _get_total_count_to_port(
  865. self, table: str, forward_chunk: int, backward_chunk: int
  866. ) -> Tuple[int, int]:
  867. remaining, done = await make_deferred_yieldable(
  868. defer.gatherResults(
  869. [
  870. run_in_background(
  871. self._get_remaining_count_to_port,
  872. table,
  873. forward_chunk,
  874. backward_chunk,
  875. ),
  876. run_in_background(self._get_already_ported_count, table),
  877. ],
  878. )
  879. )
  880. remaining = int(remaining) if remaining else 0
  881. done = int(done) if done else 0
  882. return done, remaining + done
  883. async def _setup_state_group_id_seq(self) -> None:
  884. curr_id: Optional[
  885. int
  886. ] = await self.sqlite_store.db_pool.simple_select_one_onecol(
  887. table="state_groups", keyvalues={}, retcol="MAX(id)", allow_none=True
  888. )
  889. if not curr_id:
  890. return
  891. def r(txn: LoggingTransaction) -> None:
  892. assert curr_id is not None
  893. next_id = curr_id + 1
  894. txn.execute("ALTER SEQUENCE state_group_id_seq RESTART WITH %s", (next_id,))
  895. await self.postgres_store.db_pool.runInteraction("setup_state_group_id_seq", r)
  896. async def _setup_user_id_seq(self) -> None:
  897. curr_id = await self.sqlite_store.db_pool.runInteraction(
  898. "setup_user_id_seq", find_max_generated_user_id_localpart
  899. )
  900. def r(txn: LoggingTransaction) -> None:
  901. next_id = curr_id + 1
  902. txn.execute("ALTER SEQUENCE user_id_seq RESTART WITH %s", (next_id,))
  903. await self.postgres_store.db_pool.runInteraction("setup_user_id_seq", r)
  904. async def _setup_events_stream_seqs(self) -> None:
  905. """Set the event stream sequences to the correct values."""
  906. # We get called before we've ported the events table, so we need to
  907. # fetch the current positions from the SQLite store.
  908. curr_forward_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  909. table="events", keyvalues={}, retcol="MAX(stream_ordering)", allow_none=True
  910. )
  911. curr_backward_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  912. table="events",
  913. keyvalues={},
  914. retcol="MAX(-MIN(stream_ordering), 1)",
  915. allow_none=True,
  916. )
  917. def _setup_events_stream_seqs_set_pos(txn: LoggingTransaction) -> None:
  918. if curr_forward_id:
  919. txn.execute(
  920. "ALTER SEQUENCE events_stream_seq RESTART WITH %s",
  921. (curr_forward_id + 1,),
  922. )
  923. if curr_backward_id:
  924. txn.execute(
  925. "ALTER SEQUENCE events_backfill_stream_seq RESTART WITH %s",
  926. (curr_backward_id + 1,),
  927. )
  928. await self.postgres_store.db_pool.runInteraction(
  929. "_setup_events_stream_seqs",
  930. _setup_events_stream_seqs_set_pos,
  931. )
  932. async def _setup_sequence(
  933. self,
  934. sequence_name: str,
  935. stream_id_tables: Iterable[str],
  936. column_name: str = "stream_id",
  937. ) -> None:
  938. """Set a sequence to the correct value."""
  939. current_stream_ids = []
  940. for stream_id_table in stream_id_tables:
  941. max_stream_id = cast(
  942. int,
  943. await self.sqlite_store.db_pool.simple_select_one_onecol(
  944. table=stream_id_table,
  945. keyvalues={},
  946. retcol=f"COALESCE(MAX({column_name}), 1)",
  947. allow_none=True,
  948. ),
  949. )
  950. current_stream_ids.append(max_stream_id)
  951. next_id = max(current_stream_ids) + 1
  952. def r(txn: LoggingTransaction) -> None:
  953. sql = "ALTER SEQUENCE %s RESTART WITH" % (sequence_name,)
  954. txn.execute(sql + " %s", (next_id,))
  955. await self.postgres_store.db_pool.runInteraction(
  956. "_setup_%s" % (sequence_name,), r
  957. )
  958. async def _setup_auth_chain_sequence(self) -> None:
  959. curr_chain_id: Optional[
  960. int
  961. ] = await self.sqlite_store.db_pool.simple_select_one_onecol(
  962. table="event_auth_chains",
  963. keyvalues={},
  964. retcol="MAX(chain_id)",
  965. allow_none=True,
  966. )
  967. def r(txn: LoggingTransaction) -> None:
  968. # Presumably there is at least one row in event_auth_chains.
  969. assert curr_chain_id is not None
  970. txn.execute(
  971. "ALTER SEQUENCE event_auth_chain_id RESTART WITH %s",
  972. (curr_chain_id + 1,),
  973. )
  974. if curr_chain_id is not None:
  975. await self.postgres_store.db_pool.runInteraction(
  976. "_setup_event_auth_chain_id",
  977. r,
  978. )
  979. ##############################################
  980. # The following is simply UI stuff
  981. ##############################################
  982. class TableProgress(TypedDict):
  983. start: int
  984. num_done: int
  985. total: int
  986. perc: int
  987. class Progress:
  988. """Used to report progress of the port"""
  989. def __init__(self) -> None:
  990. self.tables: Dict[str, TableProgress] = {}
  991. self.start_time = int(time.time())
  992. def add_table(self, table: str, cur: int, size: int) -> None:
  993. self.tables[table] = {
  994. "start": cur,
  995. "num_done": cur,
  996. "total": size,
  997. "perc": int(cur * 100 / size),
  998. }
  999. def update(self, table: str, num_done: int) -> None:
  1000. data = self.tables[table]
  1001. data["num_done"] = num_done
  1002. data["perc"] = int(num_done * 100 / data["total"])
  1003. def done(self) -> None:
  1004. pass
  1005. def set_state(self, state: str) -> None:
  1006. pass
  1007. class CursesProgress(Progress):
  1008. """Reports progress to a curses window"""
  1009. def __init__(self, stdscr: "curses.window"):
  1010. self.stdscr = stdscr
  1011. curses.use_default_colors()
  1012. curses.curs_set(0)
  1013. curses.init_pair(1, curses.COLOR_RED, -1)
  1014. curses.init_pair(2, curses.COLOR_GREEN, -1)
  1015. self.last_update = 0.0
  1016. self.finished = False
  1017. self.total_processed = 0
  1018. self.total_remaining = 0
  1019. super().__init__()
  1020. def update(self, table: str, num_done: int) -> None:
  1021. super().update(table, num_done)
  1022. self.total_processed = 0
  1023. self.total_remaining = 0
  1024. for data in self.tables.values():
  1025. self.total_processed += data["num_done"] - data["start"]
  1026. self.total_remaining += data["total"] - data["num_done"]
  1027. self.render()
  1028. def render(self, force: bool = False) -> None:
  1029. now = time.time()
  1030. if not force and now - self.last_update < 0.2:
  1031. # reactor.callLater(1, self.render)
  1032. return
  1033. self.stdscr.clear()
  1034. rows, cols = self.stdscr.getmaxyx()
  1035. duration = int(now) - int(self.start_time)
  1036. minutes, seconds = divmod(duration, 60)
  1037. duration_str = "%02dm %02ds" % (minutes, seconds)
  1038. if self.finished:
  1039. status = "Time spent: %s (Done!)" % (duration_str,)
  1040. else:
  1041. if self.total_processed > 0:
  1042. left = float(self.total_remaining) / self.total_processed
  1043. est_remaining = (int(now) - self.start_time) * left
  1044. est_remaining_str = "%02dm %02ds remaining" % divmod(est_remaining, 60)
  1045. else:
  1046. est_remaining_str = "Unknown"
  1047. status = "Time spent: %s (est. remaining: %s)" % (
  1048. duration_str,
  1049. est_remaining_str,
  1050. )
  1051. self.stdscr.addstr(0, 0, status, curses.A_BOLD)
  1052. max_len = max(len(t) for t in self.tables.keys())
  1053. left_margin = 5
  1054. middle_space = 1
  1055. items = sorted(self.tables.items(), key=lambda i: (i[1]["perc"], i[0]))
  1056. for i, (table, data) in enumerate(items):
  1057. if i + 2 >= rows:
  1058. break
  1059. perc = data["perc"]
  1060. color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
  1061. self.stdscr.addstr(
  1062. i + 2, left_margin + max_len - len(table), table, curses.A_BOLD | color
  1063. )
  1064. size = 20
  1065. progress = "[%s%s]" % (
  1066. "#" * int(perc * size / 100),
  1067. " " * (size - int(perc * size / 100)),
  1068. )
  1069. self.stdscr.addstr(
  1070. i + 2,
  1071. left_margin + max_len + middle_space,
  1072. "%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
  1073. )
  1074. if self.finished:
  1075. self.stdscr.addstr(rows - 1, 0, "Press any key to exit...")
  1076. self.stdscr.refresh()
  1077. self.last_update = time.time()
  1078. def done(self) -> None:
  1079. self.finished = True
  1080. self.render(True)
  1081. self.stdscr.getch()
  1082. def set_state(self, state: str) -> None:
  1083. self.stdscr.clear()
  1084. self.stdscr.addstr(0, 0, state + "...", curses.A_BOLD)
  1085. self.stdscr.refresh()
  1086. class TerminalProgress(Progress):
  1087. """Just prints progress to the terminal"""
  1088. def update(self, table: str, num_done: int) -> None:
  1089. super().update(table, num_done)
  1090. data = self.tables[table]
  1091. print(
  1092. "%s: %d%% (%d/%d)" % (table, data["perc"], data["num_done"], data["total"])
  1093. )
  1094. def set_state(self, state: str) -> None:
  1095. print(state + "...")
  1096. ##############################################
  1097. ##############################################
  1098. def main() -> None:
  1099. parser = argparse.ArgumentParser(
  1100. description="A script to port an existing synapse SQLite database to"
  1101. " a new PostgreSQL database."
  1102. )
  1103. parser.add_argument("-v", action="store_true")
  1104. parser.add_argument(
  1105. "--sqlite-database",
  1106. required=True,
  1107. help="The snapshot of the SQLite database file. This must not be"
  1108. " currently used by a running synapse server",
  1109. )
  1110. parser.add_argument(
  1111. "--postgres-config",
  1112. type=argparse.FileType("r"),
  1113. required=True,
  1114. help="The database config file for the PostgreSQL database",
  1115. )
  1116. parser.add_argument(
  1117. "--curses", action="store_true", help="display a curses based progress UI"
  1118. )
  1119. parser.add_argument(
  1120. "--batch-size",
  1121. type=int,
  1122. default=1000,
  1123. help="The number of rows to select from the SQLite table each"
  1124. " iteration [default=1000]",
  1125. )
  1126. args = parser.parse_args()
  1127. logging.basicConfig(
  1128. level=logging.DEBUG if args.v else logging.INFO,
  1129. format="%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
  1130. filename="port-synapse.log" if args.curses else None,
  1131. )
  1132. if not os.path.isfile(args.sqlite_database):
  1133. sys.stderr.write(
  1134. "The sqlite database you specified does not exist, please check that you have the"
  1135. "correct path."
  1136. )
  1137. sys.exit(1)
  1138. sqlite_config = {
  1139. "name": "sqlite3",
  1140. "args": {
  1141. "database": args.sqlite_database,
  1142. "cp_min": 1,
  1143. "cp_max": 1,
  1144. "check_same_thread": False,
  1145. },
  1146. }
  1147. hs_config = yaml.safe_load(args.postgres_config)
  1148. if "database" not in hs_config:
  1149. sys.stderr.write("The configuration file must have a 'database' section.\n")
  1150. sys.exit(4)
  1151. postgres_config = hs_config["database"]
  1152. if "name" not in postgres_config:
  1153. sys.stderr.write("Malformed database config: no 'name'\n")
  1154. sys.exit(2)
  1155. if postgres_config["name"] != "psycopg2":
  1156. sys.stderr.write("Database must use the 'psycopg2' connector.\n")
  1157. sys.exit(3)
  1158. # Don't run the background tasks that get started by the data stores.
  1159. hs_config["run_background_tasks_on"] = "some_other_process"
  1160. config = HomeServerConfig()
  1161. config.parse_config_dict(hs_config, "", "")
  1162. def start(stdscr: Optional["curses.window"] = None) -> None:
  1163. progress: Progress
  1164. if stdscr:
  1165. progress = CursesProgress(stdscr)
  1166. else:
  1167. progress = TerminalProgress()
  1168. porter = Porter(
  1169. sqlite_config=sqlite_config,
  1170. progress=progress,
  1171. batch_size=args.batch_size,
  1172. hs_config=config,
  1173. )
  1174. @defer.inlineCallbacks
  1175. def run() -> Generator["defer.Deferred[Any]", Any, None]:
  1176. with LoggingContext("synapse_port_db_run"):
  1177. yield defer.ensureDeferred(porter.run())
  1178. reactor.callWhenRunning(run)
  1179. reactor.run()
  1180. if args.curses:
  1181. curses.wrapper(start)
  1182. else:
  1183. start()
  1184. if end_error:
  1185. if end_error_exec_info:
  1186. exc_type, exc_value, exc_traceback = end_error_exec_info
  1187. traceback.print_exception(exc_type, exc_value, exc_traceback)
  1188. sys.stderr.write(end_error)
  1189. sys.exit(5)
  1190. if __name__ == "__main__":
  1191. main()