synapse_port_db 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2015 OpenMarket Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from twisted.internet import defer, reactor
  17. from twisted.enterprise import adbapi
  18. from synapse.storage._base import LoggingTransaction, SQLBaseStore
  19. from synapse.storage.engines import create_engine
  20. import argparse
  21. import curses
  22. import logging
  23. import sys
  24. import time
  25. import traceback
  26. import yaml
  27. logger = logging.getLogger("synapse_port_db")
  28. BOOLEAN_COLUMNS = {
  29. "events": ["processed", "outlier"],
  30. "rooms": ["is_public"],
  31. "event_edges": ["is_state"],
  32. "presence_list": ["accepted"],
  33. }
  34. APPEND_ONLY_TABLES = [
  35. "event_content_hashes",
  36. "event_reference_hashes",
  37. "event_signatures",
  38. "event_edge_hashes",
  39. "events",
  40. "event_json",
  41. "state_events",
  42. "room_memberships",
  43. "feedback",
  44. "topics",
  45. "room_names",
  46. "rooms",
  47. "local_media_repository",
  48. "local_media_repository_thumbnails",
  49. "remote_media_cache",
  50. "remote_media_cache_thumbnails",
  51. "redactions",
  52. "event_edges",
  53. "event_auth",
  54. "received_transactions",
  55. "sent_transactions",
  56. "transaction_id_to_pdu",
  57. "users",
  58. "state_groups",
  59. "state_groups_state",
  60. "event_to_state_groups",
  61. "rejections",
  62. ]
  63. end_error_exec_info = None
  64. class Store(object):
  65. """This object is used to pull out some of the convenience API from the
  66. Storage layer.
  67. *All* database interactions should go through this object.
  68. """
  69. def __init__(self, db_pool, engine):
  70. self.db_pool = db_pool
  71. self.database_engine = engine
  72. _simple_insert_txn = SQLBaseStore.__dict__["_simple_insert_txn"]
  73. _simple_insert = SQLBaseStore.__dict__["_simple_insert"]
  74. _simple_select_onecol_txn = SQLBaseStore.__dict__["_simple_select_onecol_txn"]
  75. _simple_select_onecol = SQLBaseStore.__dict__["_simple_select_onecol"]
  76. _simple_select_one_onecol = SQLBaseStore.__dict__["_simple_select_one_onecol"]
  77. _simple_select_one_onecol_txn = SQLBaseStore.__dict__["_simple_select_one_onecol_txn"]
  78. _simple_update_one = SQLBaseStore.__dict__["_simple_update_one"]
  79. _simple_update_one_txn = SQLBaseStore.__dict__["_simple_update_one_txn"]
  80. def runInteraction(self, desc, func, *args, **kwargs):
  81. def r(conn):
  82. try:
  83. i = 0
  84. N = 5
  85. while True:
  86. try:
  87. txn = conn.cursor()
  88. return func(
  89. LoggingTransaction(txn, desc, self.database_engine, []),
  90. *args, **kwargs
  91. )
  92. except self.database_engine.module.DatabaseError as e:
  93. if self.database_engine.is_deadlock(e):
  94. logger.warn("[TXN DEADLOCK] {%s} %d/%d", desc, i, N)
  95. if i < N:
  96. i += 1
  97. conn.rollback()
  98. continue
  99. raise
  100. except Exception as e:
  101. logger.debug("[TXN FAIL] {%s} %s", desc, e)
  102. raise
  103. return self.db_pool.runWithConnection(r)
  104. def execute(self, f, *args, **kwargs):
  105. return self.runInteraction(f.__name__, f, *args, **kwargs)
  106. def execute_sql(self, sql, *args):
  107. def r(txn):
  108. txn.execute(sql, args)
  109. return txn.fetchall()
  110. return self.runInteraction("execute_sql", r)
  111. def insert_many_txn(self, txn, table, headers, rows):
  112. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  113. table,
  114. ", ".join(k for k in headers),
  115. ", ".join("%s" for _ in headers)
  116. )
  117. try:
  118. txn.executemany(sql, rows)
  119. except:
  120. logger.exception(
  121. "Failed to insert: %s",
  122. table,
  123. )
  124. raise
  125. class Porter(object):
  126. def __init__(self, **kwargs):
  127. self.__dict__.update(kwargs)
  128. @defer.inlineCallbacks
  129. def setup_table(self, table):
  130. if table in APPEND_ONLY_TABLES:
  131. # It's safe to just carry on inserting.
  132. next_chunk = yield self.postgres_store._simple_select_one_onecol(
  133. table="port_from_sqlite3",
  134. keyvalues={"table_name": table},
  135. retcol="rowid",
  136. allow_none=True,
  137. )
  138. total_to_port = None
  139. if next_chunk is None:
  140. if table == "sent_transactions":
  141. next_chunk, already_ported, total_to_port = (
  142. yield self._setup_sent_transactions()
  143. )
  144. else:
  145. yield self.postgres_store._simple_insert(
  146. table="port_from_sqlite3",
  147. values={"table_name": table, "rowid": 1}
  148. )
  149. next_chunk = 1
  150. already_ported = 0
  151. if total_to_port is None:
  152. already_ported, total_to_port = yield self._get_total_count_to_port(
  153. table, next_chunk
  154. )
  155. else:
  156. def delete_all(txn):
  157. txn.execute(
  158. "DELETE FROM port_from_sqlite3 WHERE table_name = %s",
  159. (table,)
  160. )
  161. txn.execute("TRUNCATE %s CASCADE" % (table,))
  162. yield self.postgres_store.execute(delete_all)
  163. yield self.postgres_store._simple_insert(
  164. table="port_from_sqlite3",
  165. values={"table_name": table, "rowid": 0}
  166. )
  167. next_chunk = 1
  168. already_ported, total_to_port = yield self._get_total_count_to_port(
  169. table, next_chunk
  170. )
  171. defer.returnValue((table, already_ported, total_to_port, next_chunk))
  172. @defer.inlineCallbacks
  173. def handle_table(self, table, postgres_size, table_size, next_chunk):
  174. if not table_size:
  175. return
  176. self.progress.add_table(table, postgres_size, table_size)
  177. select = (
  178. "SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?"
  179. % (table,)
  180. )
  181. while True:
  182. def r(txn):
  183. txn.execute(select, (next_chunk, self.batch_size,))
  184. rows = txn.fetchall()
  185. headers = [column[0] for column in txn.description]
  186. return headers, rows
  187. headers, rows = yield self.sqlite_store.runInteraction("select", r)
  188. if rows:
  189. next_chunk = rows[-1][0] + 1
  190. self._convert_rows(table, headers, rows)
  191. def insert(txn):
  192. self.postgres_store.insert_many_txn(
  193. txn, table, headers[1:], rows
  194. )
  195. self.postgres_store._simple_update_one_txn(
  196. txn,
  197. table="port_from_sqlite3",
  198. keyvalues={"table_name": table},
  199. updatevalues={"rowid": next_chunk},
  200. )
  201. yield self.postgres_store.execute(insert)
  202. postgres_size += len(rows)
  203. self.progress.update(table, postgres_size)
  204. else:
  205. return
  206. def setup_db(self, db_config, database_engine):
  207. db_conn = database_engine.module.connect(
  208. **{
  209. k: v for k, v in db_config.get("args", {}).items()
  210. if not k.startswith("cp_")
  211. }
  212. )
  213. database_engine.prepare_database(db_conn)
  214. db_conn.commit()
  215. @defer.inlineCallbacks
  216. def run(self):
  217. try:
  218. sqlite_db_pool = adbapi.ConnectionPool(
  219. self.sqlite_config["name"],
  220. **self.sqlite_config["args"]
  221. )
  222. postgres_db_pool = adbapi.ConnectionPool(
  223. self.postgres_config["name"],
  224. **self.postgres_config["args"]
  225. )
  226. sqlite_engine = create_engine("sqlite3")
  227. postgres_engine = create_engine("psycopg2")
  228. self.sqlite_store = Store(sqlite_db_pool, sqlite_engine)
  229. self.postgres_store = Store(postgres_db_pool, postgres_engine)
  230. yield self.postgres_store.execute(
  231. postgres_engine.check_database
  232. )
  233. # Step 1. Set up databases.
  234. self.progress.set_state("Preparing SQLite3")
  235. self.setup_db(sqlite_config, sqlite_engine)
  236. self.progress.set_state("Preparing PostgreSQL")
  237. self.setup_db(postgres_config, postgres_engine)
  238. # Step 2. Get tables.
  239. self.progress.set_state("Fetching tables")
  240. sqlite_tables = yield self.sqlite_store._simple_select_onecol(
  241. table="sqlite_master",
  242. keyvalues={
  243. "type": "table",
  244. },
  245. retcol="name",
  246. )
  247. postgres_tables = yield self.postgres_store._simple_select_onecol(
  248. table="information_schema.tables",
  249. keyvalues={
  250. "table_schema": "public",
  251. },
  252. retcol="distinct table_name",
  253. )
  254. tables = set(sqlite_tables) & set(postgres_tables)
  255. self.progress.set_state("Creating tables")
  256. logger.info("Found %d tables", len(tables))
  257. def create_port_table(txn):
  258. txn.execute(
  259. "CREATE TABLE port_from_sqlite3 ("
  260. " table_name varchar(100) NOT NULL UNIQUE,"
  261. " rowid bigint NOT NULL"
  262. ")"
  263. )
  264. try:
  265. yield self.postgres_store.runInteraction(
  266. "create_port_table", create_port_table
  267. )
  268. except Exception as e:
  269. logger.info("Failed to create port table: %s", e)
  270. self.progress.set_state("Setting up")
  271. # Set up tables.
  272. setup_res = yield defer.gatherResults(
  273. [
  274. self.setup_table(table)
  275. for table in tables
  276. if table not in ["schema_version", "applied_schema_deltas"]
  277. and not table.startswith("sqlite_")
  278. ],
  279. consumeErrors=True,
  280. )
  281. # Process tables.
  282. yield defer.gatherResults(
  283. [
  284. self.handle_table(*res)
  285. for res in setup_res
  286. ],
  287. consumeErrors=True,
  288. )
  289. self.progress.done()
  290. except:
  291. global end_error_exec_info
  292. end_error_exec_info = sys.exc_info()
  293. logger.exception("")
  294. finally:
  295. reactor.stop()
  296. def _convert_rows(self, table, headers, rows):
  297. bool_col_names = BOOLEAN_COLUMNS.get(table, [])
  298. bool_cols = [
  299. i for i, h in enumerate(headers) if h in bool_col_names
  300. ]
  301. def conv(j, col):
  302. if j in bool_cols:
  303. return bool(col)
  304. return col
  305. for i, row in enumerate(rows):
  306. rows[i] = tuple(
  307. conv(j, col)
  308. for j, col in enumerate(row)
  309. if j > 0
  310. )
  311. @defer.inlineCallbacks
  312. def _setup_sent_transactions(self):
  313. # Only save things from the last day
  314. yesterday = int(time.time()*1000) - 86400000
  315. # And save the max transaction id from each destination
  316. select = (
  317. "SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
  318. "SELECT max(rowid) FROM sent_transactions"
  319. " GROUP BY destination"
  320. ")"
  321. )
  322. def r(txn):
  323. txn.execute(select)
  324. rows = txn.fetchall()
  325. headers = [column[0] for column in txn.description]
  326. ts_ind = headers.index('ts')
  327. return headers, [r for r in rows if r[ts_ind] < yesterday]
  328. headers, rows = yield self.sqlite_store.runInteraction(
  329. "select", r,
  330. )
  331. self._convert_rows("sent_transactions", headers, rows)
  332. inserted_rows = len(rows)
  333. if inserted_rows:
  334. max_inserted_rowid = max(r[0] for r in rows)
  335. def insert(txn):
  336. self.postgres_store.insert_many_txn(
  337. txn, "sent_transactions", headers[1:], rows
  338. )
  339. yield self.postgres_store.execute(insert)
  340. else:
  341. max_inserted_rowid = 0
  342. def get_start_id(txn):
  343. txn.execute(
  344. "SELECT rowid FROM sent_transactions WHERE ts >= ?"
  345. " ORDER BY rowid ASC LIMIT 1",
  346. (yesterday,)
  347. )
  348. rows = txn.fetchall()
  349. if rows:
  350. return rows[0][0]
  351. else:
  352. return 1
  353. next_chunk = yield self.sqlite_store.execute(get_start_id)
  354. next_chunk = max(max_inserted_rowid + 1, next_chunk)
  355. yield self.postgres_store._simple_insert(
  356. table="port_from_sqlite3",
  357. values={"table_name": "sent_transactions", "rowid": next_chunk}
  358. )
  359. def get_sent_table_size(txn):
  360. txn.execute(
  361. "SELECT count(*) FROM sent_transactions"
  362. " WHERE ts >= ?",
  363. (yesterday,)
  364. )
  365. size, = txn.fetchone()
  366. return int(size)
  367. remaining_count = yield self.sqlite_store.execute(
  368. get_sent_table_size
  369. )
  370. total_count = remaining_count + inserted_rows
  371. defer.returnValue((next_chunk, inserted_rows, total_count))
  372. @defer.inlineCallbacks
  373. def _get_remaining_count_to_port(self, table, next_chunk):
  374. rows = yield self.sqlite_store.execute_sql(
  375. "SELECT count(*) FROM %s WHERE rowid >= ?" % (table,),
  376. next_chunk,
  377. )
  378. defer.returnValue(rows[0][0])
  379. @defer.inlineCallbacks
  380. def _get_already_ported_count(self, table):
  381. rows = yield self.postgres_store.execute_sql(
  382. "SELECT count(*) FROM %s" % (table,),
  383. )
  384. defer.returnValue(rows[0][0])
  385. @defer.inlineCallbacks
  386. def _get_total_count_to_port(self, table, next_chunk):
  387. remaining, done = yield defer.gatherResults(
  388. [
  389. self._get_remaining_count_to_port(table, next_chunk),
  390. self._get_already_ported_count(table),
  391. ],
  392. consumeErrors=True,
  393. )
  394. remaining = int(remaining) if remaining else 0
  395. done = int(done) if done else 0
  396. defer.returnValue((done, remaining + done))
  397. ##############################################
  398. ###### The following is simply UI stuff ######
  399. ##############################################
  400. class Progress(object):
  401. """Used to report progress of the port
  402. """
  403. def __init__(self):
  404. self.tables = {}
  405. self.start_time = int(time.time())
  406. def add_table(self, table, cur, size):
  407. self.tables[table] = {
  408. "start": cur,
  409. "num_done": cur,
  410. "total": size,
  411. "perc": int(cur * 100 / size),
  412. }
  413. def update(self, table, num_done):
  414. data = self.tables[table]
  415. data["num_done"] = num_done
  416. data["perc"] = int(num_done * 100 / data["total"])
  417. def done(self):
  418. pass
  419. class CursesProgress(Progress):
  420. """Reports progress to a curses window
  421. """
  422. def __init__(self, stdscr):
  423. self.stdscr = stdscr
  424. curses.use_default_colors()
  425. curses.curs_set(0)
  426. curses.init_pair(1, curses.COLOR_RED, -1)
  427. curses.init_pair(2, curses.COLOR_GREEN, -1)
  428. self.last_update = 0
  429. self.finished = False
  430. self.total_processed = 0
  431. self.total_remaining = 0
  432. super(CursesProgress, self).__init__()
  433. def update(self, table, num_done):
  434. super(CursesProgress, self).update(table, num_done)
  435. self.total_processed = 0
  436. self.total_remaining = 0
  437. for table, data in self.tables.items():
  438. self.total_processed += data["num_done"] - data["start"]
  439. self.total_remaining += data["total"] - data["num_done"]
  440. self.render()
  441. def render(self, force=False):
  442. now = time.time()
  443. if not force and now - self.last_update < 0.2:
  444. # reactor.callLater(1, self.render)
  445. return
  446. self.stdscr.clear()
  447. rows, cols = self.stdscr.getmaxyx()
  448. duration = int(now) - int(self.start_time)
  449. minutes, seconds = divmod(duration, 60)
  450. duration_str = '%02dm %02ds' % (minutes, seconds,)
  451. if self.finished:
  452. status = "Time spent: %s (Done!)" % (duration_str,)
  453. else:
  454. if self.total_processed > 0:
  455. left = float(self.total_remaining) / self.total_processed
  456. est_remaining = (int(now) - self.start_time) * left
  457. est_remaining_str = '%02dm %02ds remaining' % divmod(est_remaining, 60)
  458. else:
  459. est_remaining_str = "Unknown"
  460. status = (
  461. "Time spent: %s (est. remaining: %s)"
  462. % (duration_str, est_remaining_str,)
  463. )
  464. self.stdscr.addstr(
  465. 0, 0,
  466. status,
  467. curses.A_BOLD,
  468. )
  469. max_len = max([len(t) for t in self.tables.keys()])
  470. left_margin = 5
  471. middle_space = 1
  472. items = self.tables.items()
  473. items.sort(
  474. key=lambda i: (i[1]["perc"], i[0]),
  475. )
  476. for i, (table, data) in enumerate(items):
  477. if i + 2 >= rows:
  478. break
  479. perc = data["perc"]
  480. color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
  481. self.stdscr.addstr(
  482. i+2, left_margin + max_len - len(table),
  483. table,
  484. curses.A_BOLD | color,
  485. )
  486. size = 20
  487. progress = "[%s%s]" % (
  488. "#" * int(perc*size/100),
  489. " " * (size - int(perc*size/100)),
  490. )
  491. self.stdscr.addstr(
  492. i+2, left_margin + max_len + middle_space,
  493. "%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
  494. )
  495. if self.finished:
  496. self.stdscr.addstr(
  497. rows-1, 0,
  498. "Press any key to exit...",
  499. )
  500. self.stdscr.refresh()
  501. self.last_update = time.time()
  502. def done(self):
  503. self.finished = True
  504. self.render(True)
  505. self.stdscr.getch()
  506. def set_state(self, state):
  507. self.stdscr.clear()
  508. self.stdscr.addstr(
  509. 0, 0,
  510. state + "...",
  511. curses.A_BOLD,
  512. )
  513. self.stdscr.refresh()
  514. class TerminalProgress(Progress):
  515. """Just prints progress to the terminal
  516. """
  517. def update(self, table, num_done):
  518. super(TerminalProgress, self).update(table, num_done)
  519. data = self.tables[table]
  520. print "%s: %d%% (%d/%d)" % (
  521. table, data["perc"],
  522. data["num_done"], data["total"],
  523. )
  524. def set_state(self, state):
  525. print state + "..."
  526. ##############################################
  527. ##############################################
  528. if __name__ == "__main__":
  529. parser = argparse.ArgumentParser(
  530. description="A script to port an existing synapse SQLite database to"
  531. " a new PostgreSQL database."
  532. )
  533. parser.add_argument("-v", action='store_true')
  534. parser.add_argument(
  535. "--sqlite-database", required=True,
  536. help="The snapshot of the SQLite database file. This must not be"
  537. " currently used by a running synapse server"
  538. )
  539. parser.add_argument(
  540. "--postgres-config", type=argparse.FileType('r'), required=True,
  541. help="The database config file for the PostgreSQL database"
  542. )
  543. parser.add_argument(
  544. "--curses", action='store_true',
  545. help="display a curses based progress UI"
  546. )
  547. parser.add_argument(
  548. "--batch-size", type=int, default=1000,
  549. help="The number of rows to select from the SQLite table each"
  550. " iteration [default=1000]",
  551. )
  552. args = parser.parse_args()
  553. logging_config = {
  554. "level": logging.DEBUG if args.v else logging.INFO,
  555. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
  556. }
  557. if args.curses:
  558. logging_config["filename"] = "port-synapse.log"
  559. logging.basicConfig(**logging_config)
  560. sqlite_config = {
  561. "name": "sqlite3",
  562. "args": {
  563. "database": args.sqlite_database,
  564. "cp_min": 1,
  565. "cp_max": 1,
  566. "check_same_thread": False,
  567. },
  568. }
  569. postgres_config = yaml.safe_load(args.postgres_config)
  570. if "database" in postgres_config:
  571. postgres_config = postgres_config["database"]
  572. if "name" not in postgres_config:
  573. sys.stderr.write("Malformed database config: no 'name'")
  574. sys.exit(2)
  575. if postgres_config["name"] != "psycopg2":
  576. sys.stderr.write("Database must use 'psycopg2' connector.")
  577. sys.exit(3)
  578. def start(stdscr=None):
  579. if stdscr:
  580. progress = CursesProgress(stdscr)
  581. else:
  582. progress = TerminalProgress()
  583. porter = Porter(
  584. sqlite_config=sqlite_config,
  585. postgres_config=postgres_config,
  586. progress=progress,
  587. batch_size=args.batch_size,
  588. )
  589. reactor.callWhenRunning(porter.run)
  590. reactor.run()
  591. if args.curses:
  592. curses.wrapper(start)
  593. else:
  594. start()
  595. if end_error_exec_info:
  596. exc_type, exc_value, exc_traceback = end_error_exec_info
  597. traceback.print_exception(exc_type, exc_value, exc_traceback)