synapse_port_db 34 KB

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