synapse_port_db 41 KB

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