synapse_port_db 30 KB

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