synapse_port_db 35 KB

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