synapse_port_db 29 KB

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