synapse_port_db 30 KB

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