synapse_port_db 34 KB

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