synapse_port_db 40 KB

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