synapse_port_db 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2015, 2016 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. from synapse.storage.prepare_database import prepare_database
  21. import argparse
  22. import curses
  23. import logging
  24. import sys
  25. import time
  26. import traceback
  27. import yaml
  28. logger = logging.getLogger("synapse_port_db")
  29. BOOLEAN_COLUMNS = {
  30. "events": ["processed", "outlier", "contains_url"],
  31. "rooms": ["is_public"],
  32. "event_edges": ["is_state"],
  33. "presence_list": ["accepted"],
  34. "presence_stream": ["currently_active"],
  35. "public_room_list_stream": ["visibility"],
  36. }
  37. APPEND_ONLY_TABLES = [
  38. "event_content_hashes",
  39. "event_reference_hashes",
  40. "event_signatures",
  41. "event_edge_hashes",
  42. "events",
  43. "event_json",
  44. "state_events",
  45. "room_memberships",
  46. "feedback",
  47. "topics",
  48. "room_names",
  49. "rooms",
  50. "local_media_repository",
  51. "local_media_repository_thumbnails",
  52. "remote_media_cache",
  53. "remote_media_cache_thumbnails",
  54. "redactions",
  55. "event_edges",
  56. "event_auth",
  57. "received_transactions",
  58. "sent_transactions",
  59. "transaction_id_to_pdu",
  60. "users",
  61. "state_groups",
  62. "state_groups_state",
  63. "event_to_state_groups",
  64. "rejections",
  65. "event_search",
  66. "presence_stream",
  67. "push_rules_stream",
  68. "current_state_resets",
  69. "ex_outlier_stream",
  70. "cache_invalidation_stream",
  71. "public_room_list_stream",
  72. "state_group_edges",
  73. "stream_ordering_to_exterm",
  74. ]
  75. end_error_exec_info = None
  76. class Store(object):
  77. """This object is used to pull out some of the convenience API from the
  78. Storage layer.
  79. *All* database interactions should go through this object.
  80. """
  81. def __init__(self, db_pool, engine):
  82. self.db_pool = db_pool
  83. self.database_engine = engine
  84. _simple_insert_txn = SQLBaseStore.__dict__["_simple_insert_txn"]
  85. _simple_insert = SQLBaseStore.__dict__["_simple_insert"]
  86. _simple_select_onecol_txn = SQLBaseStore.__dict__["_simple_select_onecol_txn"]
  87. _simple_select_onecol = SQLBaseStore.__dict__["_simple_select_onecol"]
  88. _simple_select_one = SQLBaseStore.__dict__["_simple_select_one"]
  89. _simple_select_one_txn = SQLBaseStore.__dict__["_simple_select_one_txn"]
  90. _simple_select_one_onecol = SQLBaseStore.__dict__["_simple_select_one_onecol"]
  91. _simple_select_one_onecol_txn = SQLBaseStore.__dict__[
  92. "_simple_select_one_onecol_txn"
  93. ]
  94. _simple_update_one = SQLBaseStore.__dict__["_simple_update_one"]
  95. _simple_update_one_txn = SQLBaseStore.__dict__["_simple_update_one_txn"]
  96. def runInteraction(self, desc, func, *args, **kwargs):
  97. def r(conn):
  98. try:
  99. i = 0
  100. N = 5
  101. while True:
  102. try:
  103. txn = conn.cursor()
  104. return func(
  105. LoggingTransaction(txn, desc, self.database_engine, []),
  106. *args, **kwargs
  107. )
  108. except self.database_engine.module.DatabaseError as e:
  109. if self.database_engine.is_deadlock(e):
  110. logger.warn("[TXN DEADLOCK] {%s} %d/%d", desc, i, N)
  111. if i < N:
  112. i += 1
  113. conn.rollback()
  114. continue
  115. raise
  116. except Exception as e:
  117. logger.debug("[TXN FAIL] {%s} %s", desc, e)
  118. raise
  119. return self.db_pool.runWithConnection(r)
  120. def execute(self, f, *args, **kwargs):
  121. return self.runInteraction(f.__name__, f, *args, **kwargs)
  122. def execute_sql(self, sql, *args):
  123. def r(txn):
  124. txn.execute(sql, args)
  125. return txn.fetchall()
  126. return self.runInteraction("execute_sql", r)
  127. def insert_many_txn(self, txn, table, headers, rows):
  128. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  129. table,
  130. ", ".join(k for k in headers),
  131. ", ".join("%s" for _ in headers)
  132. )
  133. try:
  134. txn.executemany(sql, rows)
  135. except:
  136. logger.exception(
  137. "Failed to insert: %s",
  138. table,
  139. )
  140. raise
  141. class Porter(object):
  142. def __init__(self, **kwargs):
  143. self.__dict__.update(kwargs)
  144. @defer.inlineCallbacks
  145. def setup_table(self, table):
  146. if table in APPEND_ONLY_TABLES:
  147. # It's safe to just carry on inserting.
  148. row = yield self.postgres_store._simple_select_one(
  149. table="port_from_sqlite3",
  150. keyvalues={"table_name": table},
  151. retcols=("forward_rowid", "backward_rowid"),
  152. allow_none=True,
  153. )
  154. total_to_port = None
  155. if row is None:
  156. if table == "sent_transactions":
  157. forward_chunk, already_ported, total_to_port = (
  158. yield self._setup_sent_transactions()
  159. )
  160. backward_chunk = 0
  161. else:
  162. yield self.postgres_store._simple_insert(
  163. table="port_from_sqlite3",
  164. values={
  165. "table_name": table,
  166. "forward_rowid": 1,
  167. "backward_rowid": 0,
  168. }
  169. )
  170. forward_chunk = 1
  171. backward_chunk = 0
  172. already_ported = 0
  173. else:
  174. forward_chunk = row["forward_rowid"]
  175. backward_chunk = row["backward_rowid"]
  176. if total_to_port is None:
  177. already_ported, total_to_port = yield self._get_total_count_to_port(
  178. table, forward_chunk, backward_chunk
  179. )
  180. else:
  181. def delete_all(txn):
  182. txn.execute(
  183. "DELETE FROM port_from_sqlite3 WHERE table_name = %s",
  184. (table,)
  185. )
  186. txn.execute("TRUNCATE %s CASCADE" % (table,))
  187. yield self.postgres_store.execute(delete_all)
  188. yield self.postgres_store._simple_insert(
  189. table="port_from_sqlite3",
  190. values={
  191. "table_name": table,
  192. "forward_rowid": 1,
  193. "backward_rowid": 0,
  194. }
  195. )
  196. forward_chunk = 1
  197. backward_chunk = 0
  198. already_ported, total_to_port = yield self._get_total_count_to_port(
  199. table, forward_chunk, backward_chunk
  200. )
  201. defer.returnValue(
  202. (table, already_ported, total_to_port, forward_chunk, backward_chunk)
  203. )
  204. @defer.inlineCallbacks
  205. def handle_table(self, table, postgres_size, table_size, forward_chunk,
  206. backward_chunk):
  207. if not table_size:
  208. return
  209. self.progress.add_table(table, postgres_size, table_size)
  210. if table == "event_search":
  211. yield self.handle_search_table(
  212. postgres_size, table_size, forward_chunk, backward_chunk
  213. )
  214. return
  215. forward_select = (
  216. "SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?"
  217. % (table,)
  218. )
  219. backward_select = (
  220. "SELECT rowid, * FROM %s WHERE rowid <= ? ORDER BY rowid LIMIT ?"
  221. % (table,)
  222. )
  223. do_forward = [True]
  224. do_backward = [True]
  225. while True:
  226. def r(txn):
  227. forward_rows = []
  228. backward_rows = []
  229. if do_forward[0]:
  230. txn.execute(forward_select, (forward_chunk, self.batch_size,))
  231. forward_rows = txn.fetchall()
  232. if not forward_rows:
  233. do_forward[0] = False
  234. if do_backward[0]:
  235. txn.execute(backward_select, (backward_chunk, self.batch_size,))
  236. backward_rows = txn.fetchall()
  237. if not backward_rows:
  238. do_backward[0] = False
  239. if forward_rows or backward_rows:
  240. headers = [column[0] for column in txn.description]
  241. else:
  242. headers = None
  243. return headers, forward_rows, backward_rows
  244. headers, frows, brows = yield self.sqlite_store.runInteraction(
  245. "select", r
  246. )
  247. if frows or brows:
  248. if frows:
  249. forward_chunk = max(row[0] for row in frows) + 1
  250. if brows:
  251. backward_chunk = min(row[0] for row in brows) - 1
  252. rows = frows + brows
  253. self._convert_rows(table, headers, rows)
  254. def insert(txn):
  255. self.postgres_store.insert_many_txn(
  256. txn, table, headers[1:], rows
  257. )
  258. self.postgres_store._simple_update_one_txn(
  259. txn,
  260. table="port_from_sqlite3",
  261. keyvalues={"table_name": table},
  262. updatevalues={
  263. "forward_rowid": forward_chunk,
  264. "backward_rowid": backward_chunk,
  265. },
  266. )
  267. yield self.postgres_store.execute(insert)
  268. postgres_size += len(rows)
  269. self.progress.update(table, postgres_size)
  270. else:
  271. return
  272. @defer.inlineCallbacks
  273. def handle_search_table(self, postgres_size, table_size, forward_chunk,
  274. backward_chunk):
  275. select = (
  276. "SELECT es.rowid, es.*, e.origin_server_ts, e.stream_ordering"
  277. " FROM event_search as es"
  278. " INNER JOIN events AS e USING (event_id, room_id)"
  279. " WHERE es.rowid >= ?"
  280. " ORDER BY es.rowid LIMIT ?"
  281. )
  282. while True:
  283. def r(txn):
  284. txn.execute(select, (forward_chunk, self.batch_size,))
  285. rows = txn.fetchall()
  286. headers = [column[0] for column in txn.description]
  287. return headers, rows
  288. headers, rows = yield self.sqlite_store.runInteraction("select", r)
  289. if rows:
  290. forward_chunk = rows[-1][0] + 1
  291. # We have to treat event_search differently since it has a
  292. # different structure in the two different databases.
  293. def insert(txn):
  294. sql = (
  295. "INSERT INTO event_search (event_id, room_id, key,"
  296. " sender, vector, origin_server_ts, stream_ordering)"
  297. " VALUES (?,?,?,?,to_tsvector('english', ?),?,?)"
  298. )
  299. rows_dict = [
  300. dict(zip(headers, row))
  301. for row in rows
  302. ]
  303. txn.executemany(sql, [
  304. (
  305. row["event_id"],
  306. row["room_id"],
  307. row["key"],
  308. row["sender"],
  309. row["value"],
  310. row["origin_server_ts"],
  311. row["stream_ordering"],
  312. )
  313. for row in rows_dict
  314. ])
  315. self.postgres_store._simple_update_one_txn(
  316. txn,
  317. table="port_from_sqlite3",
  318. keyvalues={"table_name": "event_search"},
  319. updatevalues={
  320. "forward_rowid": forward_chunk,
  321. "backward_rowid": backward_chunk,
  322. },
  323. )
  324. yield self.postgres_store.execute(insert)
  325. postgres_size += len(rows)
  326. self.progress.update("event_search", postgres_size)
  327. else:
  328. return
  329. def setup_db(self, db_config, database_engine):
  330. db_conn = database_engine.module.connect(
  331. **{
  332. k: v for k, v in db_config.get("args", {}).items()
  333. if not k.startswith("cp_")
  334. }
  335. )
  336. prepare_database(db_conn, database_engine, config=None)
  337. db_conn.commit()
  338. @defer.inlineCallbacks
  339. def run(self):
  340. try:
  341. sqlite_db_pool = adbapi.ConnectionPool(
  342. self.sqlite_config["name"],
  343. **self.sqlite_config["args"]
  344. )
  345. postgres_db_pool = adbapi.ConnectionPool(
  346. self.postgres_config["name"],
  347. **self.postgres_config["args"]
  348. )
  349. sqlite_engine = create_engine(sqlite_config)
  350. postgres_engine = create_engine(postgres_config)
  351. self.sqlite_store = Store(sqlite_db_pool, sqlite_engine)
  352. self.postgres_store = Store(postgres_db_pool, postgres_engine)
  353. yield self.postgres_store.execute(
  354. postgres_engine.check_database
  355. )
  356. # Step 1. Set up databases.
  357. self.progress.set_state("Preparing SQLite3")
  358. self.setup_db(sqlite_config, sqlite_engine)
  359. self.progress.set_state("Preparing PostgreSQL")
  360. self.setup_db(postgres_config, postgres_engine)
  361. # Step 2. Get tables.
  362. self.progress.set_state("Fetching tables")
  363. sqlite_tables = yield self.sqlite_store._simple_select_onecol(
  364. table="sqlite_master",
  365. keyvalues={
  366. "type": "table",
  367. },
  368. retcol="name",
  369. )
  370. postgres_tables = yield self.postgres_store._simple_select_onecol(
  371. table="information_schema.tables",
  372. keyvalues={
  373. "table_schema": "public",
  374. },
  375. retcol="distinct table_name",
  376. )
  377. tables = set(sqlite_tables) & set(postgres_tables)
  378. self.progress.set_state("Creating tables")
  379. logger.info("Found %d tables", len(tables))
  380. def create_port_table(txn):
  381. txn.execute(
  382. "CREATE TABLE port_from_sqlite3 ("
  383. " table_name varchar(100) NOT NULL UNIQUE,"
  384. " forward_rowid bigint NOT NULL,"
  385. " backward_rowid bigint NOT NULL"
  386. ")"
  387. )
  388. # The old port script created a table with just a "rowid" column.
  389. # We want people to be able to rerun this script from an old port
  390. # so that they can pick up any missing events that were not
  391. # ported across.
  392. def alter_table(txn):
  393. txn.execute(
  394. "ALTER TABLE IF EXISTS port_from_sqlite3"
  395. " RENAME rowid TO forward_rowid"
  396. )
  397. txn.execute(
  398. "ALTER TABLE IF EXISTS port_from_sqlite3"
  399. " ADD backward_rowid bigint NOT NULL DEFAULT 0"
  400. )
  401. try:
  402. yield self.postgres_store.runInteraction(
  403. "alter_table", alter_table
  404. )
  405. except Exception as e:
  406. logger.info("Failed to create port table: %s", e)
  407. try:
  408. yield self.postgres_store.runInteraction(
  409. "create_port_table", create_port_table
  410. )
  411. except Exception as e:
  412. logger.info("Failed to create port table: %s", e)
  413. self.progress.set_state("Setting up")
  414. # Set up tables.
  415. setup_res = yield defer.gatherResults(
  416. [
  417. self.setup_table(table)
  418. for table in tables
  419. if table not in ["schema_version", "applied_schema_deltas"]
  420. and not table.startswith("sqlite_")
  421. ],
  422. consumeErrors=True,
  423. )
  424. # Process tables.
  425. yield defer.gatherResults(
  426. [
  427. self.handle_table(*res)
  428. for res in setup_res
  429. ],
  430. consumeErrors=True,
  431. )
  432. self.progress.done()
  433. except:
  434. global end_error_exec_info
  435. end_error_exec_info = sys.exc_info()
  436. logger.exception("")
  437. finally:
  438. reactor.stop()
  439. def _convert_rows(self, table, headers, rows):
  440. bool_col_names = BOOLEAN_COLUMNS.get(table, [])
  441. bool_cols = [
  442. i for i, h in enumerate(headers) if h in bool_col_names
  443. ]
  444. def conv(j, col):
  445. if j in bool_cols:
  446. return bool(col)
  447. return col
  448. for i, row in enumerate(rows):
  449. rows[i] = tuple(
  450. conv(j, col)
  451. for j, col in enumerate(row)
  452. if j > 0
  453. )
  454. @defer.inlineCallbacks
  455. def _setup_sent_transactions(self):
  456. # Only save things from the last day
  457. yesterday = int(time.time() * 1000) - 86400000
  458. # And save the max transaction id from each destination
  459. select = (
  460. "SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
  461. "SELECT max(rowid) FROM sent_transactions"
  462. " GROUP BY destination"
  463. ")"
  464. )
  465. def r(txn):
  466. txn.execute(select)
  467. rows = txn.fetchall()
  468. headers = [column[0] for column in txn.description]
  469. ts_ind = headers.index('ts')
  470. return headers, [r for r in rows if r[ts_ind] < yesterday]
  471. headers, rows = yield self.sqlite_store.runInteraction(
  472. "select", r,
  473. )
  474. self._convert_rows("sent_transactions", headers, rows)
  475. inserted_rows = len(rows)
  476. if inserted_rows:
  477. max_inserted_rowid = max(r[0] for r in rows)
  478. def insert(txn):
  479. self.postgres_store.insert_many_txn(
  480. txn, "sent_transactions", headers[1:], rows
  481. )
  482. yield self.postgres_store.execute(insert)
  483. else:
  484. max_inserted_rowid = 0
  485. def get_start_id(txn):
  486. txn.execute(
  487. "SELECT rowid FROM sent_transactions WHERE ts >= ?"
  488. " ORDER BY rowid ASC LIMIT 1",
  489. (yesterday,)
  490. )
  491. rows = txn.fetchall()
  492. if rows:
  493. return rows[0][0]
  494. else:
  495. return 1
  496. next_chunk = yield self.sqlite_store.execute(get_start_id)
  497. next_chunk = max(max_inserted_rowid + 1, next_chunk)
  498. yield self.postgres_store._simple_insert(
  499. table="port_from_sqlite3",
  500. values={
  501. "table_name": "sent_transactions",
  502. "forward_rowid": next_chunk,
  503. "backward_rowid": 0,
  504. }
  505. )
  506. def get_sent_table_size(txn):
  507. txn.execute(
  508. "SELECT count(*) FROM sent_transactions"
  509. " WHERE ts >= ?",
  510. (yesterday,)
  511. )
  512. size, = txn.fetchone()
  513. return int(size)
  514. remaining_count = yield self.sqlite_store.execute(
  515. get_sent_table_size
  516. )
  517. total_count = remaining_count + inserted_rows
  518. defer.returnValue((next_chunk, inserted_rows, total_count))
  519. @defer.inlineCallbacks
  520. def _get_remaining_count_to_port(self, table, forward_chunk, backward_chunk):
  521. frows = yield self.sqlite_store.execute_sql(
  522. "SELECT count(*) FROM %s WHERE rowid >= ?" % (table,),
  523. forward_chunk,
  524. )
  525. brows = yield self.sqlite_store.execute_sql(
  526. "SELECT count(*) FROM %s WHERE rowid <= ?" % (table,),
  527. backward_chunk,
  528. )
  529. defer.returnValue(frows[0][0] + brows[0][0])
  530. @defer.inlineCallbacks
  531. def _get_already_ported_count(self, table):
  532. rows = yield self.postgres_store.execute_sql(
  533. "SELECT count(*) FROM %s" % (table,),
  534. )
  535. defer.returnValue(rows[0][0])
  536. @defer.inlineCallbacks
  537. def _get_total_count_to_port(self, table, forward_chunk, backward_chunk):
  538. remaining, done = yield defer.gatherResults(
  539. [
  540. self._get_remaining_count_to_port(table, forward_chunk, backward_chunk),
  541. self._get_already_ported_count(table),
  542. ],
  543. consumeErrors=True,
  544. )
  545. remaining = int(remaining) if remaining else 0
  546. done = int(done) if done else 0
  547. defer.returnValue((done, remaining + done))
  548. ##############################################
  549. ###### The following is simply UI stuff ######
  550. ##############################################
  551. class Progress(object):
  552. """Used to report progress of the port
  553. """
  554. def __init__(self):
  555. self.tables = {}
  556. self.start_time = int(time.time())
  557. def add_table(self, table, cur, size):
  558. self.tables[table] = {
  559. "start": cur,
  560. "num_done": cur,
  561. "total": size,
  562. "perc": int(cur * 100 / size),
  563. }
  564. def update(self, table, num_done):
  565. data = self.tables[table]
  566. data["num_done"] = num_done
  567. data["perc"] = int(num_done * 100 / data["total"])
  568. def done(self):
  569. pass
  570. class CursesProgress(Progress):
  571. """Reports progress to a curses window
  572. """
  573. def __init__(self, stdscr):
  574. self.stdscr = stdscr
  575. curses.use_default_colors()
  576. curses.curs_set(0)
  577. curses.init_pair(1, curses.COLOR_RED, -1)
  578. curses.init_pair(2, curses.COLOR_GREEN, -1)
  579. self.last_update = 0
  580. self.finished = False
  581. self.total_processed = 0
  582. self.total_remaining = 0
  583. super(CursesProgress, self).__init__()
  584. def update(self, table, num_done):
  585. super(CursesProgress, self).update(table, num_done)
  586. self.total_processed = 0
  587. self.total_remaining = 0
  588. for table, data in self.tables.items():
  589. self.total_processed += data["num_done"] - data["start"]
  590. self.total_remaining += data["total"] - data["num_done"]
  591. self.render()
  592. def render(self, force=False):
  593. now = time.time()
  594. if not force and now - self.last_update < 0.2:
  595. # reactor.callLater(1, self.render)
  596. return
  597. self.stdscr.clear()
  598. rows, cols = self.stdscr.getmaxyx()
  599. duration = int(now) - int(self.start_time)
  600. minutes, seconds = divmod(duration, 60)
  601. duration_str = '%02dm %02ds' % (minutes, seconds,)
  602. if self.finished:
  603. status = "Time spent: %s (Done!)" % (duration_str,)
  604. else:
  605. if self.total_processed > 0:
  606. left = float(self.total_remaining) / self.total_processed
  607. est_remaining = (int(now) - self.start_time) * left
  608. est_remaining_str = '%02dm %02ds remaining' % divmod(est_remaining, 60)
  609. else:
  610. est_remaining_str = "Unknown"
  611. status = (
  612. "Time spent: %s (est. remaining: %s)"
  613. % (duration_str, est_remaining_str,)
  614. )
  615. self.stdscr.addstr(
  616. 0, 0,
  617. status,
  618. curses.A_BOLD,
  619. )
  620. max_len = max([len(t) for t in self.tables.keys()])
  621. left_margin = 5
  622. middle_space = 1
  623. items = self.tables.items()
  624. items.sort(
  625. key=lambda i: (i[1]["perc"], i[0]),
  626. )
  627. for i, (table, data) in enumerate(items):
  628. if i + 2 >= rows:
  629. break
  630. perc = data["perc"]
  631. color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
  632. self.stdscr.addstr(
  633. i + 2, left_margin + max_len - len(table),
  634. table,
  635. curses.A_BOLD | color,
  636. )
  637. size = 20
  638. progress = "[%s%s]" % (
  639. "#" * int(perc * size / 100),
  640. " " * (size - int(perc * size / 100)),
  641. )
  642. self.stdscr.addstr(
  643. i + 2, left_margin + max_len + middle_space,
  644. "%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
  645. )
  646. if self.finished:
  647. self.stdscr.addstr(
  648. rows - 1, 0,
  649. "Press any key to exit...",
  650. )
  651. self.stdscr.refresh()
  652. self.last_update = time.time()
  653. def done(self):
  654. self.finished = True
  655. self.render(True)
  656. self.stdscr.getch()
  657. def set_state(self, state):
  658. self.stdscr.clear()
  659. self.stdscr.addstr(
  660. 0, 0,
  661. state + "...",
  662. curses.A_BOLD,
  663. )
  664. self.stdscr.refresh()
  665. class TerminalProgress(Progress):
  666. """Just prints progress to the terminal
  667. """
  668. def update(self, table, num_done):
  669. super(TerminalProgress, self).update(table, num_done)
  670. data = self.tables[table]
  671. print "%s: %d%% (%d/%d)" % (
  672. table, data["perc"],
  673. data["num_done"], data["total"],
  674. )
  675. def set_state(self, state):
  676. print state + "..."
  677. ##############################################
  678. ##############################################
  679. if __name__ == "__main__":
  680. parser = argparse.ArgumentParser(
  681. description="A script to port an existing synapse SQLite database to"
  682. " a new PostgreSQL database."
  683. )
  684. parser.add_argument("-v", action='store_true')
  685. parser.add_argument(
  686. "--sqlite-database", required=True,
  687. help="The snapshot of the SQLite database file. This must not be"
  688. " currently used by a running synapse server"
  689. )
  690. parser.add_argument(
  691. "--postgres-config", type=argparse.FileType('r'), required=True,
  692. help="The database config file for the PostgreSQL database"
  693. )
  694. parser.add_argument(
  695. "--curses", action='store_true',
  696. help="display a curses based progress UI"
  697. )
  698. parser.add_argument(
  699. "--batch-size", type=int, default=1000,
  700. help="The number of rows to select from the SQLite table each"
  701. " iteration [default=1000]",
  702. )
  703. args = parser.parse_args()
  704. logging_config = {
  705. "level": logging.DEBUG if args.v else logging.INFO,
  706. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
  707. }
  708. if args.curses:
  709. logging_config["filename"] = "port-synapse.log"
  710. logging.basicConfig(**logging_config)
  711. sqlite_config = {
  712. "name": "sqlite3",
  713. "args": {
  714. "database": args.sqlite_database,
  715. "cp_min": 1,
  716. "cp_max": 1,
  717. "check_same_thread": False,
  718. },
  719. }
  720. postgres_config = yaml.safe_load(args.postgres_config)
  721. if "database" in postgres_config:
  722. postgres_config = postgres_config["database"]
  723. if "name" not in postgres_config:
  724. sys.stderr.write("Malformed database config: no 'name'")
  725. sys.exit(2)
  726. if postgres_config["name"] != "psycopg2":
  727. sys.stderr.write("Database must use 'psycopg2' connector.")
  728. sys.exit(3)
  729. def start(stdscr=None):
  730. if stdscr:
  731. progress = CursesProgress(stdscr)
  732. else:
  733. progress = TerminalProgress()
  734. porter = Porter(
  735. sqlite_config=sqlite_config,
  736. postgres_config=postgres_config,
  737. progress=progress,
  738. batch_size=args.batch_size,
  739. )
  740. reactor.callWhenRunning(porter.run)
  741. reactor.run()
  742. if args.curses:
  743. curses.wrapper(start)
  744. else:
  745. start()
  746. if end_error_exec_info:
  747. exc_type, exc_value, exc_traceback = end_error_exec_info
  748. traceback.print_exception(exc_type, exc_value, exc_traceback)