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.
 
 
 
 
 
 

1234 lines
41 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 sys
  21. import time
  22. import traceback
  23. from typing import Dict, Iterable, Optional, Set
  24. import yaml
  25. from twisted.internet import defer, reactor
  26. import synapse
  27. from synapse.config.database import DatabaseConnectionConfig
  28. from synapse.config.homeserver import HomeServerConfig
  29. from synapse.logging.context import (
  30. LoggingContext,
  31. make_deferred_yieldable,
  32. run_in_background,
  33. )
  34. from synapse.storage.database import DatabasePool, make_conn
  35. from synapse.storage.databases.main.client_ips import ClientIpBackgroundUpdateStore
  36. from synapse.storage.databases.main.deviceinbox import DeviceInboxBackgroundUpdateStore
  37. from synapse.storage.databases.main.devices import DeviceBackgroundUpdateStore
  38. from synapse.storage.databases.main.end_to_end_keys import EndToEndKeyBackgroundStore
  39. from synapse.storage.databases.main.events_bg_updates import (
  40. EventsBackgroundUpdatesStore,
  41. )
  42. from synapse.storage.databases.main.media_repository import (
  43. MediaRepositoryBackgroundUpdateStore,
  44. )
  45. from synapse.storage.databases.main.pusher import PusherWorkerStore
  46. from synapse.storage.databases.main.registration import (
  47. RegistrationBackgroundUpdateStore,
  48. find_max_generated_user_id_localpart,
  49. )
  50. from synapse.storage.databases.main.room import RoomBackgroundUpdateStore
  51. from synapse.storage.databases.main.roommember import RoomMemberBackgroundUpdateStore
  52. from synapse.storage.databases.main.search import SearchBackgroundUpdateStore
  53. from synapse.storage.databases.main.state import MainStateBackgroundUpdateStore
  54. from synapse.storage.databases.main.stats import StatsStore
  55. from synapse.storage.databases.main.user_directory import (
  56. UserDirectoryBackgroundUpdateStore,
  57. )
  58. from synapse.storage.databases.state.bg_updates import StateBackgroundUpdateStore
  59. from synapse.storage.engines import create_engine
  60. from synapse.storage.prepare_database import prepare_database
  61. from synapse.util import Clock
  62. from synapse.util.versionstring import get_version_string
  63. logger = logging.getLogger("synapse_port_db")
  64. BOOLEAN_COLUMNS = {
  65. "events": ["processed", "outlier", "contains_url"],
  66. "rooms": ["is_public", "has_auth_chain_index"],
  67. "event_edges": ["is_state"],
  68. "presence_list": ["accepted"],
  69. "presence_stream": ["currently_active"],
  70. "public_room_list_stream": ["visibility"],
  71. "devices": ["hidden"],
  72. "device_lists_outbound_pokes": ["sent"],
  73. "users_who_share_rooms": ["share_private"],
  74. "groups": ["is_public"],
  75. "group_rooms": ["is_public"],
  76. "group_users": ["is_public", "is_admin"],
  77. "group_summary_rooms": ["is_public"],
  78. "group_room_categories": ["is_public"],
  79. "group_summary_users": ["is_public"],
  80. "group_roles": ["is_public"],
  81. "local_group_membership": ["is_publicised", "is_admin"],
  82. "e2e_room_keys": ["is_verified"],
  83. "account_validity": ["email_sent"],
  84. "redactions": ["have_censored"],
  85. "room_stats_state": ["is_federatable"],
  86. "local_media_repository": ["safe_from_quarantine"],
  87. "users": ["shadow_banned"],
  88. "e2e_fallback_keys_json": ["used"],
  89. }
  90. APPEND_ONLY_TABLES = [
  91. "event_reference_hashes",
  92. "events",
  93. "event_json",
  94. "state_events",
  95. "room_memberships",
  96. "topics",
  97. "room_names",
  98. "rooms",
  99. "local_media_repository",
  100. "local_media_repository_thumbnails",
  101. "remote_media_cache",
  102. "remote_media_cache_thumbnails",
  103. "redactions",
  104. "event_edges",
  105. "event_auth",
  106. "received_transactions",
  107. "sent_transactions",
  108. "transaction_id_to_pdu",
  109. "users",
  110. "state_groups",
  111. "state_groups_state",
  112. "event_to_state_groups",
  113. "rejections",
  114. "event_search",
  115. "presence_stream",
  116. "push_rules_stream",
  117. "ex_outlier_stream",
  118. "cache_invalidation_stream_by_instance",
  119. "public_room_list_stream",
  120. "state_group_edges",
  121. "stream_ordering_to_exterm",
  122. ]
  123. IGNORED_TABLES = {
  124. # We don't port these tables, as they're a faff and we can regenerate
  125. # them anyway.
  126. "user_directory",
  127. "user_directory_search",
  128. "user_directory_search_content",
  129. "user_directory_search_docsize",
  130. "user_directory_search_segdir",
  131. "user_directory_search_segments",
  132. "user_directory_search_stat",
  133. "user_directory_search_pos",
  134. "users_who_share_private_rooms",
  135. "users_in_public_room",
  136. # UI auth sessions have foreign keys so additional care needs to be taken,
  137. # the sessions are transient anyway, so ignore them.
  138. "ui_auth_sessions",
  139. "ui_auth_sessions_credentials",
  140. "ui_auth_sessions_ips",
  141. }
  142. # Error returned by the run function. Used at the top-level part of the script to
  143. # handle errors and return codes.
  144. end_error = None # type: Optional[str]
  145. # The exec_info for the error, if any. If error is defined but not exec_info the script
  146. # will show only the error message without the stacktrace, if exec_info is defined but
  147. # not the error then the script will show nothing outside of what's printed in the run
  148. # function. If both are defined, the script will print both the error and the stacktrace.
  149. end_error_exec_info = None
  150. class Store(
  151. ClientIpBackgroundUpdateStore,
  152. DeviceInboxBackgroundUpdateStore,
  153. DeviceBackgroundUpdateStore,
  154. EventsBackgroundUpdatesStore,
  155. MediaRepositoryBackgroundUpdateStore,
  156. RegistrationBackgroundUpdateStore,
  157. RoomBackgroundUpdateStore,
  158. RoomMemberBackgroundUpdateStore,
  159. SearchBackgroundUpdateStore,
  160. StateBackgroundUpdateStore,
  161. MainStateBackgroundUpdateStore,
  162. UserDirectoryBackgroundUpdateStore,
  163. EndToEndKeyBackgroundStore,
  164. StatsStore,
  165. PusherWorkerStore,
  166. ):
  167. def execute(self, f, *args, **kwargs):
  168. return self.db_pool.runInteraction(f.__name__, f, *args, **kwargs)
  169. def execute_sql(self, sql, *args):
  170. def r(txn):
  171. txn.execute(sql, args)
  172. return txn.fetchall()
  173. return self.db_pool.runInteraction("execute_sql", r)
  174. def insert_many_txn(self, txn, table, headers, rows):
  175. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  176. table,
  177. ", ".join(k for k in headers),
  178. ", ".join("%s" for _ in headers),
  179. )
  180. try:
  181. txn.executemany(sql, rows)
  182. except Exception:
  183. logger.exception("Failed to insert: %s", table)
  184. raise
  185. def set_room_is_public(self, room_id, is_public):
  186. raise Exception(
  187. "Attempt to set room_is_public during port_db: database not empty?"
  188. )
  189. class MockHomeserver:
  190. def __init__(self, config):
  191. self.clock = Clock(reactor)
  192. self.config = config
  193. self.hostname = config.server_name
  194. self.version_string = "Synapse/" + get_version_string(synapse)
  195. def get_clock(self):
  196. return self.clock
  197. def get_reactor(self):
  198. return reactor
  199. def get_instance_name(self):
  200. return "master"
  201. class Porter(object):
  202. def __init__(self, **kwargs):
  203. self.__dict__.update(kwargs)
  204. async def setup_table(self, table):
  205. if table in APPEND_ONLY_TABLES:
  206. # It's safe to just carry on inserting.
  207. row = await self.postgres_store.db_pool.simple_select_one(
  208. table="port_from_sqlite3",
  209. keyvalues={"table_name": table},
  210. retcols=("forward_rowid", "backward_rowid"),
  211. allow_none=True,
  212. )
  213. total_to_port = None
  214. if row is None:
  215. if table == "sent_transactions":
  216. (
  217. forward_chunk,
  218. already_ported,
  219. total_to_port,
  220. ) = await self._setup_sent_transactions()
  221. backward_chunk = 0
  222. else:
  223. await self.postgres_store.db_pool.simple_insert(
  224. table="port_from_sqlite3",
  225. values={
  226. "table_name": table,
  227. "forward_rowid": 1,
  228. "backward_rowid": 0,
  229. },
  230. )
  231. forward_chunk = 1
  232. backward_chunk = 0
  233. already_ported = 0
  234. else:
  235. forward_chunk = row["forward_rowid"]
  236. backward_chunk = row["backward_rowid"]
  237. if total_to_port is None:
  238. already_ported, total_to_port = await self._get_total_count_to_port(
  239. table, forward_chunk, backward_chunk
  240. )
  241. else:
  242. def delete_all(txn):
  243. txn.execute(
  244. "DELETE FROM port_from_sqlite3 WHERE table_name = %s", (table,)
  245. )
  246. txn.execute("TRUNCATE %s CASCADE" % (table,))
  247. await self.postgres_store.execute(delete_all)
  248. await self.postgres_store.db_pool.simple_insert(
  249. table="port_from_sqlite3",
  250. values={"table_name": table, "forward_rowid": 1, "backward_rowid": 0},
  251. )
  252. forward_chunk = 1
  253. backward_chunk = 0
  254. already_ported, total_to_port = await self._get_total_count_to_port(
  255. table, forward_chunk, backward_chunk
  256. )
  257. return table, already_ported, total_to_port, forward_chunk, backward_chunk
  258. async def get_table_constraints(self) -> Dict[str, Set[str]]:
  259. """Returns a map of tables that have foreign key constraints to tables they depend on.
  260. """
  261. def _get_constraints(txn):
  262. # We can pull the information about foreign key constraints out from
  263. # the postgres schema tables.
  264. sql = """
  265. SELECT DISTINCT
  266. tc.table_name,
  267. ccu.table_name AS foreign_table_name
  268. FROM
  269. information_schema.table_constraints AS tc
  270. INNER JOIN information_schema.constraint_column_usage AS ccu
  271. USING (table_schema, constraint_name)
  272. WHERE tc.constraint_type = 'FOREIGN KEY';
  273. """
  274. txn.execute(sql)
  275. results = {}
  276. for table, foreign_table in txn:
  277. results.setdefault(table, set()).add(foreign_table)
  278. return results
  279. return await self.postgres_store.db_pool.runInteraction(
  280. "get_table_constraints", _get_constraints
  281. )
  282. async def handle_table(
  283. self, table, postgres_size, table_size, forward_chunk, backward_chunk
  284. ):
  285. logger.info(
  286. "Table %s: %i/%i (rows %i-%i) already ported",
  287. table,
  288. postgres_size,
  289. table_size,
  290. backward_chunk + 1,
  291. forward_chunk - 1,
  292. )
  293. if not table_size:
  294. return
  295. self.progress.add_table(table, postgres_size, table_size)
  296. if table == "event_search":
  297. await self.handle_search_table(
  298. postgres_size, table_size, forward_chunk, backward_chunk
  299. )
  300. return
  301. if table in IGNORED_TABLES:
  302. self.progress.update(table, table_size) # Mark table as done
  303. return
  304. if table == "user_directory_stream_pos":
  305. # We need to make sure there is a single row, `(X, null), as that is
  306. # what synapse expects to be there.
  307. await self.postgres_store.db_pool.simple_insert(
  308. table=table, values={"stream_id": None}
  309. )
  310. self.progress.update(table, table_size) # Mark table as done
  311. return
  312. forward_select = (
  313. "SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?" % (table,)
  314. )
  315. backward_select = (
  316. "SELECT rowid, * FROM %s WHERE rowid <= ? ORDER BY rowid LIMIT ?" % (table,)
  317. )
  318. do_forward = [True]
  319. do_backward = [True]
  320. while True:
  321. def r(txn):
  322. forward_rows = []
  323. backward_rows = []
  324. if do_forward[0]:
  325. txn.execute(forward_select, (forward_chunk, self.batch_size))
  326. forward_rows = txn.fetchall()
  327. if not forward_rows:
  328. do_forward[0] = False
  329. if do_backward[0]:
  330. txn.execute(backward_select, (backward_chunk, self.batch_size))
  331. backward_rows = txn.fetchall()
  332. if not backward_rows:
  333. do_backward[0] = False
  334. if forward_rows or backward_rows:
  335. headers = [column[0] for column in txn.description]
  336. else:
  337. headers = None
  338. return headers, forward_rows, backward_rows
  339. headers, frows, brows = await self.sqlite_store.db_pool.runInteraction(
  340. "select", r
  341. )
  342. if frows or brows:
  343. if frows:
  344. forward_chunk = max(row[0] for row in frows) + 1
  345. if brows:
  346. backward_chunk = min(row[0] for row in brows) - 1
  347. rows = frows + brows
  348. rows = self._convert_rows(table, headers, rows)
  349. def insert(txn):
  350. self.postgres_store.insert_many_txn(txn, table, headers[1:], rows)
  351. self.postgres_store.db_pool.simple_update_one_txn(
  352. txn,
  353. table="port_from_sqlite3",
  354. keyvalues={"table_name": table},
  355. updatevalues={
  356. "forward_rowid": forward_chunk,
  357. "backward_rowid": backward_chunk,
  358. },
  359. )
  360. await self.postgres_store.execute(insert)
  361. postgres_size += len(rows)
  362. self.progress.update(table, postgres_size)
  363. else:
  364. return
  365. async def handle_search_table(
  366. self, postgres_size, table_size, forward_chunk, backward_chunk
  367. ):
  368. select = (
  369. "SELECT es.rowid, es.*, e.origin_server_ts, e.stream_ordering"
  370. " FROM event_search as es"
  371. " INNER JOIN events AS e USING (event_id, room_id)"
  372. " WHERE es.rowid >= ?"
  373. " ORDER BY es.rowid LIMIT ?"
  374. )
  375. while True:
  376. def r(txn):
  377. txn.execute(select, (forward_chunk, self.batch_size))
  378. rows = txn.fetchall()
  379. headers = [column[0] for column in txn.description]
  380. return headers, rows
  381. headers, rows = await self.sqlite_store.db_pool.runInteraction("select", r)
  382. if rows:
  383. forward_chunk = rows[-1][0] + 1
  384. # We have to treat event_search differently since it has a
  385. # different structure in the two different databases.
  386. def insert(txn):
  387. sql = (
  388. "INSERT INTO event_search (event_id, room_id, key,"
  389. " sender, vector, origin_server_ts, stream_ordering)"
  390. " VALUES (?,?,?,?,to_tsvector('english', ?),?,?)"
  391. )
  392. rows_dict = []
  393. for row in rows:
  394. d = dict(zip(headers, row))
  395. if "\0" in d["value"]:
  396. logger.warning("dropping search row %s", d)
  397. else:
  398. rows_dict.append(d)
  399. txn.executemany(
  400. sql,
  401. [
  402. (
  403. row["event_id"],
  404. row["room_id"],
  405. row["key"],
  406. row["sender"],
  407. row["value"],
  408. row["origin_server_ts"],
  409. row["stream_ordering"],
  410. )
  411. for row in rows_dict
  412. ],
  413. )
  414. self.postgres_store.db_pool.simple_update_one_txn(
  415. txn,
  416. table="port_from_sqlite3",
  417. keyvalues={"table_name": "event_search"},
  418. updatevalues={
  419. "forward_rowid": forward_chunk,
  420. "backward_rowid": backward_chunk,
  421. },
  422. )
  423. await self.postgres_store.execute(insert)
  424. postgres_size += len(rows)
  425. self.progress.update("event_search", postgres_size)
  426. else:
  427. return
  428. def build_db_store(
  429. self, db_config: DatabaseConnectionConfig, allow_outdated_version: bool = False,
  430. ):
  431. """Builds and returns a database store using the provided configuration.
  432. Args:
  433. db_config: The database configuration
  434. allow_outdated_version: True to suppress errors about the database server
  435. version being too old to run a complete synapse
  436. Returns:
  437. The built Store object.
  438. """
  439. self.progress.set_state("Preparing %s" % db_config.config["name"])
  440. engine = create_engine(db_config.config)
  441. hs = MockHomeserver(self.hs_config)
  442. with make_conn(db_config, engine, "portdb") as db_conn:
  443. engine.check_database(
  444. db_conn, allow_outdated_version=allow_outdated_version
  445. )
  446. prepare_database(db_conn, engine, config=self.hs_config)
  447. store = Store(DatabasePool(hs, db_config, engine), db_conn, hs)
  448. db_conn.commit()
  449. return store
  450. async def run_background_updates_on_postgres(self):
  451. # Manually apply all background updates on the PostgreSQL database.
  452. postgres_ready = (
  453. await self.postgres_store.db_pool.updates.has_completed_background_updates()
  454. )
  455. if not postgres_ready:
  456. # Only say that we're running background updates when there are background
  457. # updates to run.
  458. self.progress.set_state("Running background updates on PostgreSQL")
  459. while not postgres_ready:
  460. await self.postgres_store.db_pool.updates.do_next_background_update(100)
  461. postgres_ready = await (
  462. self.postgres_store.db_pool.updates.has_completed_background_updates()
  463. )
  464. async def run(self):
  465. """Ports the SQLite database to a PostgreSQL database.
  466. When a fatal error is met, its message is assigned to the global "end_error"
  467. variable. When this error comes with a stacktrace, its exec_info is assigned to
  468. the global "end_error_exec_info" variable.
  469. """
  470. global end_error
  471. try:
  472. # we allow people to port away from outdated versions of sqlite.
  473. self.sqlite_store = self.build_db_store(
  474. DatabaseConnectionConfig("master-sqlite", self.sqlite_config),
  475. allow_outdated_version=True,
  476. )
  477. # Check if all background updates are done, abort if not.
  478. updates_complete = (
  479. await self.sqlite_store.db_pool.updates.has_completed_background_updates()
  480. )
  481. if not updates_complete:
  482. end_error = (
  483. "Pending background updates exist in the SQLite3 database."
  484. " Please start Synapse again and wait until every update has finished"
  485. " before running this script.\n"
  486. )
  487. return
  488. self.postgres_store = self.build_db_store(
  489. self.hs_config.get_single_database()
  490. )
  491. await self.run_background_updates_on_postgres()
  492. self.progress.set_state("Creating port tables")
  493. def create_port_table(txn):
  494. txn.execute(
  495. "CREATE TABLE IF NOT EXISTS port_from_sqlite3 ("
  496. " table_name varchar(100) NOT NULL UNIQUE,"
  497. " forward_rowid bigint NOT NULL,"
  498. " backward_rowid bigint NOT NULL"
  499. ")"
  500. )
  501. # The old port script created a table with just a "rowid" column.
  502. # We want people to be able to rerun this script from an old port
  503. # so that they can pick up any missing events that were not
  504. # ported across.
  505. def alter_table(txn):
  506. txn.execute(
  507. "ALTER TABLE IF EXISTS port_from_sqlite3"
  508. " RENAME rowid TO forward_rowid"
  509. )
  510. txn.execute(
  511. "ALTER TABLE IF EXISTS port_from_sqlite3"
  512. " ADD backward_rowid bigint NOT NULL DEFAULT 0"
  513. )
  514. try:
  515. await self.postgres_store.db_pool.runInteraction(
  516. "alter_table", alter_table
  517. )
  518. except Exception:
  519. # On Error Resume Next
  520. pass
  521. await self.postgres_store.db_pool.runInteraction(
  522. "create_port_table", create_port_table
  523. )
  524. # Step 2. Set up sequences
  525. #
  526. # We do this before porting the tables so that event if we fail half
  527. # way through the postgres DB always have sequences that are greater
  528. # than their respective tables. If we don't then creating the
  529. # `DataStore` object will fail due to the inconsistency.
  530. self.progress.set_state("Setting up sequence generators")
  531. await self._setup_state_group_id_seq()
  532. await self._setup_user_id_seq()
  533. await self._setup_events_stream_seqs()
  534. await self._setup_sequence(
  535. "device_inbox_sequence", ("device_inbox", "device_federation_outbox")
  536. )
  537. await self._setup_sequence(
  538. "account_data_sequence", ("room_account_data", "room_tags_revisions", "account_data"))
  539. await self._setup_sequence("receipts_sequence", ("receipts_linearized", ))
  540. await self._setup_auth_chain_sequence()
  541. # Step 3. Get tables.
  542. self.progress.set_state("Fetching tables")
  543. sqlite_tables = await self.sqlite_store.db_pool.simple_select_onecol(
  544. table="sqlite_master", keyvalues={"type": "table"}, retcol="name"
  545. )
  546. postgres_tables = await self.postgres_store.db_pool.simple_select_onecol(
  547. table="information_schema.tables",
  548. keyvalues={},
  549. retcol="distinct table_name",
  550. )
  551. tables = set(sqlite_tables) & set(postgres_tables)
  552. logger.info("Found %d tables", len(tables))
  553. # Step 4. Figure out what still needs copying
  554. self.progress.set_state("Checking on port progress")
  555. setup_res = await make_deferred_yieldable(
  556. defer.gatherResults(
  557. [
  558. run_in_background(self.setup_table, table)
  559. for table in tables
  560. if table not in ["schema_version", "applied_schema_deltas"]
  561. and not table.startswith("sqlite_")
  562. ],
  563. consumeErrors=True,
  564. )
  565. )
  566. # Map from table name to args passed to `handle_table`, i.e. a tuple
  567. # of: `postgres_size`, `table_size`, `forward_chunk`, `backward_chunk`.
  568. tables_to_port_info_map = {r[0]: r[1:] for r in setup_res}
  569. # Step 5. Do the copying.
  570. #
  571. # This is slightly convoluted as we need to ensure tables are ported
  572. # in the correct order due to foreign key constraints.
  573. self.progress.set_state("Copying to postgres")
  574. constraints = await self.get_table_constraints()
  575. tables_ported = set() # type: Set[str]
  576. while tables_to_port_info_map:
  577. # Pulls out all tables that are still to be ported and which
  578. # only depend on tables that are already ported (if any).
  579. tables_to_port = [
  580. table
  581. for table in tables_to_port_info_map
  582. if not constraints.get(table, set()) - tables_ported
  583. ]
  584. await make_deferred_yieldable(
  585. defer.gatherResults(
  586. [
  587. run_in_background(
  588. self.handle_table,
  589. table,
  590. *tables_to_port_info_map.pop(table),
  591. )
  592. for table in tables_to_port
  593. ],
  594. consumeErrors=True,
  595. )
  596. )
  597. tables_ported.update(tables_to_port)
  598. self.progress.done()
  599. except Exception as e:
  600. global end_error_exec_info
  601. end_error = str(e)
  602. end_error_exec_info = sys.exc_info()
  603. logger.exception("")
  604. finally:
  605. reactor.stop()
  606. def _convert_rows(self, table, headers, rows):
  607. bool_col_names = BOOLEAN_COLUMNS.get(table, [])
  608. bool_cols = [i for i, h in enumerate(headers) if h in bool_col_names]
  609. class BadValueException(Exception):
  610. pass
  611. def conv(j, col):
  612. if j in bool_cols:
  613. return bool(col)
  614. if isinstance(col, bytes):
  615. return bytearray(col)
  616. elif isinstance(col, str) and "\0" in col:
  617. logger.warning(
  618. "DROPPING ROW: NUL value in table %s col %s: %r",
  619. table,
  620. headers[j],
  621. col,
  622. )
  623. raise BadValueException()
  624. return col
  625. outrows = []
  626. for i, row in enumerate(rows):
  627. try:
  628. outrows.append(
  629. tuple(conv(j, col) for j, col in enumerate(row) if j > 0)
  630. )
  631. except BadValueException:
  632. pass
  633. return outrows
  634. async def _setup_sent_transactions(self):
  635. # Only save things from the last day
  636. yesterday = int(time.time() * 1000) - 86400000
  637. # And save the max transaction id from each destination
  638. select = (
  639. "SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
  640. "SELECT max(rowid) FROM sent_transactions"
  641. " GROUP BY destination"
  642. ")"
  643. )
  644. def r(txn):
  645. txn.execute(select)
  646. rows = txn.fetchall()
  647. headers = [column[0] for column in txn.description]
  648. ts_ind = headers.index("ts")
  649. return headers, [r for r in rows if r[ts_ind] < yesterday]
  650. headers, rows = await self.sqlite_store.db_pool.runInteraction("select", r)
  651. rows = self._convert_rows("sent_transactions", headers, rows)
  652. inserted_rows = len(rows)
  653. if inserted_rows:
  654. max_inserted_rowid = max(r[0] for r in rows)
  655. def insert(txn):
  656. self.postgres_store.insert_many_txn(
  657. txn, "sent_transactions", headers[1:], rows
  658. )
  659. await self.postgres_store.execute(insert)
  660. else:
  661. max_inserted_rowid = 0
  662. def get_start_id(txn):
  663. txn.execute(
  664. "SELECT rowid FROM sent_transactions WHERE ts >= ?"
  665. " ORDER BY rowid ASC LIMIT 1",
  666. (yesterday,),
  667. )
  668. rows = txn.fetchall()
  669. if rows:
  670. return rows[0][0]
  671. else:
  672. return 1
  673. next_chunk = await self.sqlite_store.execute(get_start_id)
  674. next_chunk = max(max_inserted_rowid + 1, next_chunk)
  675. await self.postgres_store.db_pool.simple_insert(
  676. table="port_from_sqlite3",
  677. values={
  678. "table_name": "sent_transactions",
  679. "forward_rowid": next_chunk,
  680. "backward_rowid": 0,
  681. },
  682. )
  683. def get_sent_table_size(txn):
  684. txn.execute(
  685. "SELECT count(*) FROM sent_transactions" " WHERE ts >= ?", (yesterday,)
  686. )
  687. (size,) = txn.fetchone()
  688. return int(size)
  689. remaining_count = await self.sqlite_store.execute(get_sent_table_size)
  690. total_count = remaining_count + inserted_rows
  691. return next_chunk, inserted_rows, total_count
  692. async def _get_remaining_count_to_port(self, table, forward_chunk, backward_chunk):
  693. frows = await self.sqlite_store.execute_sql(
  694. "SELECT count(*) FROM %s WHERE rowid >= ?" % (table,), forward_chunk
  695. )
  696. brows = await self.sqlite_store.execute_sql(
  697. "SELECT count(*) FROM %s WHERE rowid <= ?" % (table,), backward_chunk
  698. )
  699. return frows[0][0] + brows[0][0]
  700. async def _get_already_ported_count(self, table):
  701. rows = await self.postgres_store.execute_sql(
  702. "SELECT count(*) FROM %s" % (table,)
  703. )
  704. return rows[0][0]
  705. async def _get_total_count_to_port(self, table, forward_chunk, backward_chunk):
  706. remaining, done = await make_deferred_yieldable(
  707. defer.gatherResults(
  708. [
  709. run_in_background(
  710. self._get_remaining_count_to_port,
  711. table,
  712. forward_chunk,
  713. backward_chunk,
  714. ),
  715. run_in_background(self._get_already_ported_count, table),
  716. ],
  717. )
  718. )
  719. remaining = int(remaining) if remaining else 0
  720. done = int(done) if done else 0
  721. return done, remaining + done
  722. async def _setup_state_group_id_seq(self) -> None:
  723. curr_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  724. table="state_groups", keyvalues={}, retcol="MAX(id)", allow_none=True
  725. )
  726. if not curr_id:
  727. return
  728. def r(txn):
  729. next_id = curr_id + 1
  730. txn.execute("ALTER SEQUENCE state_group_id_seq RESTART WITH %s", (next_id,))
  731. await self.postgres_store.db_pool.runInteraction("setup_state_group_id_seq", r)
  732. async def _setup_user_id_seq(self) -> None:
  733. curr_id = await self.sqlite_store.db_pool.runInteraction(
  734. "setup_user_id_seq", find_max_generated_user_id_localpart
  735. )
  736. def r(txn):
  737. next_id = curr_id + 1
  738. txn.execute("ALTER SEQUENCE user_id_seq RESTART WITH %s", (next_id,))
  739. await self.postgres_store.db_pool.runInteraction("setup_user_id_seq", r)
  740. async def _setup_events_stream_seqs(self) -> None:
  741. """Set the event stream sequences to the correct values.
  742. """
  743. # We get called before we've ported the events table, so we need to
  744. # fetch the current positions from the SQLite store.
  745. curr_forward_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  746. table="events", keyvalues={}, retcol="MAX(stream_ordering)", allow_none=True
  747. )
  748. curr_backward_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  749. table="events",
  750. keyvalues={},
  751. retcol="MAX(-MIN(stream_ordering), 1)",
  752. allow_none=True,
  753. )
  754. def _setup_events_stream_seqs_set_pos(txn):
  755. if curr_forward_id:
  756. txn.execute(
  757. "ALTER SEQUENCE events_stream_seq RESTART WITH %s",
  758. (curr_forward_id + 1,),
  759. )
  760. txn.execute(
  761. "ALTER SEQUENCE events_backfill_stream_seq RESTART WITH %s",
  762. (curr_backward_id + 1,),
  763. )
  764. await self.postgres_store.db_pool.runInteraction(
  765. "_setup_events_stream_seqs", _setup_events_stream_seqs_set_pos,
  766. )
  767. async def _setup_sequence(self, sequence_name: str, stream_id_tables: Iterable[str]) -> None:
  768. """Set a sequence to the correct value.
  769. """
  770. current_stream_ids = []
  771. for stream_id_table in stream_id_tables:
  772. max_stream_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  773. table=stream_id_table,
  774. keyvalues={},
  775. retcol="COALESCE(MAX(stream_id), 1)",
  776. allow_none=True,
  777. )
  778. current_stream_ids.append(max_stream_id)
  779. next_id = max(current_stream_ids) + 1
  780. def r(txn):
  781. sql = "ALTER SEQUENCE %s RESTART WITH" % (sequence_name, )
  782. txn.execute(sql + " %s", (next_id, ))
  783. await self.postgres_store.db_pool.runInteraction("_setup_%s" % (sequence_name,), r)
  784. async def _setup_auth_chain_sequence(self) -> None:
  785. curr_chain_id = await self.sqlite_store.db_pool.simple_select_one_onecol(
  786. table="event_auth_chains", keyvalues={}, retcol="MAX(chain_id)", allow_none=True
  787. )
  788. def r(txn):
  789. txn.execute(
  790. "ALTER SEQUENCE event_auth_chain_id RESTART WITH %s",
  791. (curr_chain_id,),
  792. )
  793. await self.postgres_store.db_pool.runInteraction(
  794. "_setup_event_auth_chain_id", r,
  795. )
  796. ##############################################
  797. # The following is simply UI stuff
  798. ##############################################
  799. class Progress(object):
  800. """Used to report progress of the port
  801. """
  802. def __init__(self):
  803. self.tables = {}
  804. self.start_time = int(time.time())
  805. def add_table(self, table, cur, size):
  806. self.tables[table] = {
  807. "start": cur,
  808. "num_done": cur,
  809. "total": size,
  810. "perc": int(cur * 100 / size),
  811. }
  812. def update(self, table, num_done):
  813. data = self.tables[table]
  814. data["num_done"] = num_done
  815. data["perc"] = int(num_done * 100 / data["total"])
  816. def done(self):
  817. pass
  818. class CursesProgress(Progress):
  819. """Reports progress to a curses window
  820. """
  821. def __init__(self, stdscr):
  822. self.stdscr = stdscr
  823. curses.use_default_colors()
  824. curses.curs_set(0)
  825. curses.init_pair(1, curses.COLOR_RED, -1)
  826. curses.init_pair(2, curses.COLOR_GREEN, -1)
  827. self.last_update = 0
  828. self.finished = False
  829. self.total_processed = 0
  830. self.total_remaining = 0
  831. super(CursesProgress, self).__init__()
  832. def update(self, table, num_done):
  833. super(CursesProgress, self).update(table, num_done)
  834. self.total_processed = 0
  835. self.total_remaining = 0
  836. for table, data in self.tables.items():
  837. self.total_processed += data["num_done"] - data["start"]
  838. self.total_remaining += data["total"] - data["num_done"]
  839. self.render()
  840. def render(self, force=False):
  841. now = time.time()
  842. if not force and now - self.last_update < 0.2:
  843. # reactor.callLater(1, self.render)
  844. return
  845. self.stdscr.clear()
  846. rows, cols = self.stdscr.getmaxyx()
  847. duration = int(now) - int(self.start_time)
  848. minutes, seconds = divmod(duration, 60)
  849. duration_str = "%02dm %02ds" % (minutes, seconds)
  850. if self.finished:
  851. status = "Time spent: %s (Done!)" % (duration_str,)
  852. else:
  853. if self.total_processed > 0:
  854. left = float(self.total_remaining) / self.total_processed
  855. est_remaining = (int(now) - self.start_time) * left
  856. est_remaining_str = "%02dm %02ds remaining" % divmod(est_remaining, 60)
  857. else:
  858. est_remaining_str = "Unknown"
  859. status = "Time spent: %s (est. remaining: %s)" % (
  860. duration_str,
  861. est_remaining_str,
  862. )
  863. self.stdscr.addstr(0, 0, status, curses.A_BOLD)
  864. max_len = max([len(t) for t in self.tables.keys()])
  865. left_margin = 5
  866. middle_space = 1
  867. items = self.tables.items()
  868. items = sorted(items, key=lambda i: (i[1]["perc"], i[0]))
  869. for i, (table, data) in enumerate(items):
  870. if i + 2 >= rows:
  871. break
  872. perc = data["perc"]
  873. color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
  874. self.stdscr.addstr(
  875. i + 2, left_margin + max_len - len(table), table, curses.A_BOLD | color
  876. )
  877. size = 20
  878. progress = "[%s%s]" % (
  879. "#" * int(perc * size / 100),
  880. " " * (size - int(perc * size / 100)),
  881. )
  882. self.stdscr.addstr(
  883. i + 2,
  884. left_margin + max_len + middle_space,
  885. "%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
  886. )
  887. if self.finished:
  888. self.stdscr.addstr(rows - 1, 0, "Press any key to exit...")
  889. self.stdscr.refresh()
  890. self.last_update = time.time()
  891. def done(self):
  892. self.finished = True
  893. self.render(True)
  894. self.stdscr.getch()
  895. def set_state(self, state):
  896. self.stdscr.clear()
  897. self.stdscr.addstr(0, 0, state + "...", curses.A_BOLD)
  898. self.stdscr.refresh()
  899. class TerminalProgress(Progress):
  900. """Just prints progress to the terminal
  901. """
  902. def update(self, table, num_done):
  903. super(TerminalProgress, self).update(table, num_done)
  904. data = self.tables[table]
  905. print(
  906. "%s: %d%% (%d/%d)" % (table, data["perc"], data["num_done"], data["total"])
  907. )
  908. def set_state(self, state):
  909. print(state + "...")
  910. ##############################################
  911. ##############################################
  912. if __name__ == "__main__":
  913. parser = argparse.ArgumentParser(
  914. description="A script to port an existing synapse SQLite database to"
  915. " a new PostgreSQL database."
  916. )
  917. parser.add_argument("-v", action="store_true")
  918. parser.add_argument(
  919. "--sqlite-database",
  920. required=True,
  921. help="The snapshot of the SQLite database file. This must not be"
  922. " currently used by a running synapse server",
  923. )
  924. parser.add_argument(
  925. "--postgres-config",
  926. type=argparse.FileType("r"),
  927. required=True,
  928. help="The database config file for the PostgreSQL database",
  929. )
  930. parser.add_argument(
  931. "--curses", action="store_true", help="display a curses based progress UI"
  932. )
  933. parser.add_argument(
  934. "--batch-size",
  935. type=int,
  936. default=1000,
  937. help="The number of rows to select from the SQLite table each"
  938. " iteration [default=1000]",
  939. )
  940. args = parser.parse_args()
  941. logging_config = {
  942. "level": logging.DEBUG if args.v else logging.INFO,
  943. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
  944. }
  945. if args.curses:
  946. logging_config["filename"] = "port-synapse.log"
  947. logging.basicConfig(**logging_config)
  948. sqlite_config = {
  949. "name": "sqlite3",
  950. "args": {
  951. "database": args.sqlite_database,
  952. "cp_min": 1,
  953. "cp_max": 1,
  954. "check_same_thread": False,
  955. },
  956. }
  957. hs_config = yaml.safe_load(args.postgres_config)
  958. if "database" not in hs_config:
  959. sys.stderr.write("The configuration file must have a 'database' section.\n")
  960. sys.exit(4)
  961. postgres_config = hs_config["database"]
  962. if "name" not in postgres_config:
  963. sys.stderr.write("Malformed database config: no 'name'\n")
  964. sys.exit(2)
  965. if postgres_config["name"] != "psycopg2":
  966. sys.stderr.write("Database must use the 'psycopg2' connector.\n")
  967. sys.exit(3)
  968. config = HomeServerConfig()
  969. config.parse_config_dict(hs_config, "", "")
  970. def start(stdscr=None):
  971. if stdscr:
  972. progress = CursesProgress(stdscr)
  973. else:
  974. progress = TerminalProgress()
  975. porter = Porter(
  976. sqlite_config=sqlite_config,
  977. progress=progress,
  978. batch_size=args.batch_size,
  979. hs_config=config,
  980. )
  981. @defer.inlineCallbacks
  982. def run():
  983. with LoggingContext("synapse_port_db_run"):
  984. yield defer.ensureDeferred(porter.run())
  985. reactor.callWhenRunning(run)
  986. reactor.run()
  987. if args.curses:
  988. curses.wrapper(start)
  989. else:
  990. start()
  991. if end_error:
  992. if end_error_exec_info:
  993. exc_type, exc_value, exc_traceback = end_error_exec_info
  994. traceback.print_exception(exc_type, exc_value, exc_traceback)
  995. sys.stderr.write(end_error)
  996. sys.exit(5)