synapse_port_db 31 KB

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