synapse_port_db 41 KB

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