synapse_port_db 36 KB

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