synapse_port_db.py 42 KB

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