synapse_port_db 41 KB

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