synapse_port_db 34 KB

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