synapse_port_db 41 KB

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