1
0

synapse_port_db 41 KB

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