synapse_port_db 30 KB

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