synapse_port_db 36 KB

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