synapse_port_db 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright 2015, 2016 OpenMarket Ltd
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from twisted.internet import defer, reactor
  17. from twisted.enterprise import adbapi
  18. from synapse.storage._base import LoggingTransaction, SQLBaseStore
  19. from synapse.storage.engines import create_engine
  20. from synapse.storage.prepare_database import prepare_database
  21. import argparse
  22. import curses
  23. import logging
  24. import sys
  25. import time
  26. import traceback
  27. import yaml
  28. logger = logging.getLogger("synapse_port_db")
  29. BOOLEAN_COLUMNS = {
  30. "events": ["processed", "outlier"],
  31. "rooms": ["is_public"],
  32. "event_edges": ["is_state"],
  33. "presence_list": ["accepted"],
  34. "presence_stream": ["currently_active"],
  35. }
  36. APPEND_ONLY_TABLES = [
  37. "event_content_hashes",
  38. "event_reference_hashes",
  39. "event_signatures",
  40. "event_edge_hashes",
  41. "events",
  42. "event_json",
  43. "state_events",
  44. "room_memberships",
  45. "feedback",
  46. "topics",
  47. "room_names",
  48. "rooms",
  49. "local_media_repository",
  50. "local_media_repository_thumbnails",
  51. "remote_media_cache",
  52. "remote_media_cache_thumbnails",
  53. "redactions",
  54. "event_edges",
  55. "event_auth",
  56. "received_transactions",
  57. "sent_transactions",
  58. "transaction_id_to_pdu",
  59. "users",
  60. "state_groups",
  61. "state_groups_state",
  62. "event_to_state_groups",
  63. "rejections",
  64. "event_search",
  65. ]
  66. end_error_exec_info = None
  67. class Store(object):
  68. """This object is used to pull out some of the convenience API from the
  69. Storage layer.
  70. *All* database interactions should go through this object.
  71. """
  72. def __init__(self, db_pool, engine):
  73. self.db_pool = db_pool
  74. self.database_engine = engine
  75. _simple_insert_txn = SQLBaseStore.__dict__["_simple_insert_txn"]
  76. _simple_insert = SQLBaseStore.__dict__["_simple_insert"]
  77. _simple_select_onecol_txn = SQLBaseStore.__dict__["_simple_select_onecol_txn"]
  78. _simple_select_onecol = SQLBaseStore.__dict__["_simple_select_onecol"]
  79. _simple_select_one_onecol = SQLBaseStore.__dict__["_simple_select_one_onecol"]
  80. _simple_select_one_onecol_txn = SQLBaseStore.__dict__["_simple_select_one_onecol_txn"]
  81. _simple_update_one = SQLBaseStore.__dict__["_simple_update_one"]
  82. _simple_update_one_txn = SQLBaseStore.__dict__["_simple_update_one_txn"]
  83. def runInteraction(self, desc, func, *args, **kwargs):
  84. def r(conn):
  85. try:
  86. i = 0
  87. N = 5
  88. while True:
  89. try:
  90. txn = conn.cursor()
  91. return func(
  92. LoggingTransaction(txn, desc, self.database_engine, []),
  93. *args, **kwargs
  94. )
  95. except self.database_engine.module.DatabaseError as e:
  96. if self.database_engine.is_deadlock(e):
  97. logger.warn("[TXN DEADLOCK] {%s} %d/%d", desc, i, N)
  98. if i < N:
  99. i += 1
  100. conn.rollback()
  101. continue
  102. raise
  103. except Exception as e:
  104. logger.debug("[TXN FAIL] {%s} %s", desc, e)
  105. raise
  106. return self.db_pool.runWithConnection(r)
  107. def execute(self, f, *args, **kwargs):
  108. return self.runInteraction(f.__name__, f, *args, **kwargs)
  109. def execute_sql(self, sql, *args):
  110. def r(txn):
  111. txn.execute(sql, args)
  112. return txn.fetchall()
  113. return self.runInteraction("execute_sql", r)
  114. def insert_many_txn(self, txn, table, headers, rows):
  115. sql = "INSERT INTO %s (%s) VALUES (%s)" % (
  116. table,
  117. ", ".join(k for k in headers),
  118. ", ".join("%s" for _ in headers)
  119. )
  120. try:
  121. txn.executemany(sql, rows)
  122. except:
  123. logger.exception(
  124. "Failed to insert: %s",
  125. table,
  126. )
  127. raise
  128. class Porter(object):
  129. def __init__(self, **kwargs):
  130. self.__dict__.update(kwargs)
  131. @defer.inlineCallbacks
  132. def setup_table(self, table):
  133. if table in APPEND_ONLY_TABLES:
  134. # It's safe to just carry on inserting.
  135. next_chunk = yield self.postgres_store._simple_select_one_onecol(
  136. table="port_from_sqlite3",
  137. keyvalues={"table_name": table},
  138. retcol="rowid",
  139. allow_none=True,
  140. )
  141. total_to_port = None
  142. if next_chunk is None:
  143. if table == "sent_transactions":
  144. next_chunk, already_ported, total_to_port = (
  145. yield self._setup_sent_transactions()
  146. )
  147. else:
  148. yield self.postgres_store._simple_insert(
  149. table="port_from_sqlite3",
  150. values={"table_name": table, "rowid": 1}
  151. )
  152. next_chunk = 1
  153. already_ported = 0
  154. if total_to_port is None:
  155. already_ported, total_to_port = yield self._get_total_count_to_port(
  156. table, next_chunk
  157. )
  158. else:
  159. def delete_all(txn):
  160. txn.execute(
  161. "DELETE FROM port_from_sqlite3 WHERE table_name = %s",
  162. (table,)
  163. )
  164. txn.execute("TRUNCATE %s CASCADE" % (table,))
  165. yield self.postgres_store.execute(delete_all)
  166. yield self.postgres_store._simple_insert(
  167. table="port_from_sqlite3",
  168. values={"table_name": table, "rowid": 0}
  169. )
  170. next_chunk = 1
  171. already_ported, total_to_port = yield self._get_total_count_to_port(
  172. table, next_chunk
  173. )
  174. defer.returnValue((table, already_ported, total_to_port, next_chunk))
  175. @defer.inlineCallbacks
  176. def handle_table(self, table, postgres_size, table_size, next_chunk):
  177. if not table_size:
  178. return
  179. self.progress.add_table(table, postgres_size, table_size)
  180. if table == "event_search":
  181. yield self.handle_search_table(postgres_size, table_size, next_chunk)
  182. return
  183. select = (
  184. "SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?"
  185. % (table,)
  186. )
  187. while True:
  188. def r(txn):
  189. txn.execute(select, (next_chunk, self.batch_size,))
  190. rows = txn.fetchall()
  191. headers = [column[0] for column in txn.description]
  192. return headers, rows
  193. headers, rows = yield self.sqlite_store.runInteraction("select", r)
  194. if rows:
  195. next_chunk = rows[-1][0] + 1
  196. self._convert_rows(table, headers, rows)
  197. def insert(txn):
  198. self.postgres_store.insert_many_txn(
  199. txn, table, headers[1:], rows
  200. )
  201. self.postgres_store._simple_update_one_txn(
  202. txn,
  203. table="port_from_sqlite3",
  204. keyvalues={"table_name": table},
  205. updatevalues={"rowid": next_chunk},
  206. )
  207. yield self.postgres_store.execute(insert)
  208. postgres_size += len(rows)
  209. self.progress.update(table, postgres_size)
  210. else:
  211. return
  212. @defer.inlineCallbacks
  213. def handle_search_table(self, postgres_size, table_size, next_chunk):
  214. select = (
  215. "SELECT es.rowid, es.*, e.origin_server_ts, e.stream_ordering"
  216. " FROM event_search as es"
  217. " INNER JOIN events AS e USING (event_id, room_id)"
  218. " WHERE es.rowid >= ?"
  219. " ORDER BY es.rowid LIMIT ?"
  220. )
  221. while True:
  222. def r(txn):
  223. txn.execute(select, (next_chunk, self.batch_size,))
  224. rows = txn.fetchall()
  225. headers = [column[0] for column in txn.description]
  226. return headers, rows
  227. headers, rows = yield self.sqlite_store.runInteraction("select", r)
  228. if rows:
  229. next_chunk = rows[-1][0] + 1
  230. # We have to treat event_search differently since it has a
  231. # different structure in the two different databases.
  232. def insert(txn):
  233. sql = (
  234. "INSERT INTO event_search (event_id, room_id, key,"
  235. " sender, vector, origin_server_ts, stream_ordering)"
  236. " VALUES (?,?,?,?,to_tsvector('english', ?),?,?)"
  237. )
  238. rows_dict = [
  239. dict(zip(headers, row))
  240. for row in rows
  241. ]
  242. txn.executemany(sql, [
  243. (
  244. row["event_id"],
  245. row["room_id"],
  246. row["key"],
  247. row["sender"],
  248. row["value"],
  249. row["origin_server_ts"],
  250. row["stream_ordering"],
  251. )
  252. for row in rows_dict
  253. ])
  254. self.postgres_store._simple_update_one_txn(
  255. txn,
  256. table="port_from_sqlite3",
  257. keyvalues={"table_name": "event_search"},
  258. updatevalues={"rowid": next_chunk},
  259. )
  260. yield self.postgres_store.execute(insert)
  261. postgres_size += len(rows)
  262. self.progress.update("event_search", postgres_size)
  263. else:
  264. return
  265. def setup_db(self, db_config, database_engine):
  266. db_conn = database_engine.module.connect(
  267. **{
  268. k: v for k, v in db_config.get("args", {}).items()
  269. if not k.startswith("cp_")
  270. }
  271. )
  272. prepare_database(db_conn, database_engine, config=None)
  273. db_conn.commit()
  274. @defer.inlineCallbacks
  275. def run(self):
  276. try:
  277. sqlite_db_pool = adbapi.ConnectionPool(
  278. self.sqlite_config["name"],
  279. **self.sqlite_config["args"]
  280. )
  281. postgres_db_pool = adbapi.ConnectionPool(
  282. self.postgres_config["name"],
  283. **self.postgres_config["args"]
  284. )
  285. sqlite_engine = create_engine(sqlite_config)
  286. postgres_engine = create_engine(postgres_config)
  287. self.sqlite_store = Store(sqlite_db_pool, sqlite_engine)
  288. self.postgres_store = Store(postgres_db_pool, postgres_engine)
  289. yield self.postgres_store.execute(
  290. postgres_engine.check_database
  291. )
  292. # Step 1. Set up databases.
  293. self.progress.set_state("Preparing SQLite3")
  294. self.setup_db(sqlite_config, sqlite_engine)
  295. self.progress.set_state("Preparing PostgreSQL")
  296. self.setup_db(postgres_config, postgres_engine)
  297. # Step 2. Get tables.
  298. self.progress.set_state("Fetching tables")
  299. sqlite_tables = yield self.sqlite_store._simple_select_onecol(
  300. table="sqlite_master",
  301. keyvalues={
  302. "type": "table",
  303. },
  304. retcol="name",
  305. )
  306. postgres_tables = yield self.postgres_store._simple_select_onecol(
  307. table="information_schema.tables",
  308. keyvalues={
  309. "table_schema": "public",
  310. },
  311. retcol="distinct table_name",
  312. )
  313. tables = set(sqlite_tables) & set(postgres_tables)
  314. self.progress.set_state("Creating tables")
  315. logger.info("Found %d tables", len(tables))
  316. def create_port_table(txn):
  317. txn.execute(
  318. "CREATE TABLE port_from_sqlite3 ("
  319. " table_name varchar(100) NOT NULL UNIQUE,"
  320. " rowid bigint NOT NULL"
  321. ")"
  322. )
  323. try:
  324. yield self.postgres_store.runInteraction(
  325. "create_port_table", create_port_table
  326. )
  327. except Exception as e:
  328. logger.info("Failed to create port table: %s", e)
  329. self.progress.set_state("Setting up")
  330. # Set up tables.
  331. setup_res = yield defer.gatherResults(
  332. [
  333. self.setup_table(table)
  334. for table in tables
  335. if table not in ["schema_version", "applied_schema_deltas"]
  336. and not table.startswith("sqlite_")
  337. ],
  338. consumeErrors=True,
  339. )
  340. # Process tables.
  341. yield defer.gatherResults(
  342. [
  343. self.handle_table(*res)
  344. for res in setup_res
  345. ],
  346. consumeErrors=True,
  347. )
  348. self.progress.done()
  349. except:
  350. global end_error_exec_info
  351. end_error_exec_info = sys.exc_info()
  352. logger.exception("")
  353. finally:
  354. reactor.stop()
  355. def _convert_rows(self, table, headers, rows):
  356. bool_col_names = BOOLEAN_COLUMNS.get(table, [])
  357. bool_cols = [
  358. i for i, h in enumerate(headers) if h in bool_col_names
  359. ]
  360. def conv(j, col):
  361. if j in bool_cols:
  362. return bool(col)
  363. return col
  364. for i, row in enumerate(rows):
  365. rows[i] = tuple(
  366. conv(j, col)
  367. for j, col in enumerate(row)
  368. if j > 0
  369. )
  370. @defer.inlineCallbacks
  371. def _setup_sent_transactions(self):
  372. # Only save things from the last day
  373. yesterday = int(time.time()*1000) - 86400000
  374. # And save the max transaction id from each destination
  375. select = (
  376. "SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
  377. "SELECT max(rowid) FROM sent_transactions"
  378. " GROUP BY destination"
  379. ")"
  380. )
  381. def r(txn):
  382. txn.execute(select)
  383. rows = txn.fetchall()
  384. headers = [column[0] for column in txn.description]
  385. ts_ind = headers.index('ts')
  386. return headers, [r for r in rows if r[ts_ind] < yesterday]
  387. headers, rows = yield self.sqlite_store.runInteraction(
  388. "select", r,
  389. )
  390. self._convert_rows("sent_transactions", headers, rows)
  391. inserted_rows = len(rows)
  392. if inserted_rows:
  393. max_inserted_rowid = max(r[0] for r in rows)
  394. def insert(txn):
  395. self.postgres_store.insert_many_txn(
  396. txn, "sent_transactions", headers[1:], rows
  397. )
  398. yield self.postgres_store.execute(insert)
  399. else:
  400. max_inserted_rowid = 0
  401. def get_start_id(txn):
  402. txn.execute(
  403. "SELECT rowid FROM sent_transactions WHERE ts >= ?"
  404. " ORDER BY rowid ASC LIMIT 1",
  405. (yesterday,)
  406. )
  407. rows = txn.fetchall()
  408. if rows:
  409. return rows[0][0]
  410. else:
  411. return 1
  412. next_chunk = yield self.sqlite_store.execute(get_start_id)
  413. next_chunk = max(max_inserted_rowid + 1, next_chunk)
  414. yield self.postgres_store._simple_insert(
  415. table="port_from_sqlite3",
  416. values={"table_name": "sent_transactions", "rowid": next_chunk}
  417. )
  418. def get_sent_table_size(txn):
  419. txn.execute(
  420. "SELECT count(*) FROM sent_transactions"
  421. " WHERE ts >= ?",
  422. (yesterday,)
  423. )
  424. size, = txn.fetchone()
  425. return int(size)
  426. remaining_count = yield self.sqlite_store.execute(
  427. get_sent_table_size
  428. )
  429. total_count = remaining_count + inserted_rows
  430. defer.returnValue((next_chunk, inserted_rows, total_count))
  431. @defer.inlineCallbacks
  432. def _get_remaining_count_to_port(self, table, next_chunk):
  433. rows = yield self.sqlite_store.execute_sql(
  434. "SELECT count(*) FROM %s WHERE rowid >= ?" % (table,),
  435. next_chunk,
  436. )
  437. defer.returnValue(rows[0][0])
  438. @defer.inlineCallbacks
  439. def _get_already_ported_count(self, table):
  440. rows = yield self.postgres_store.execute_sql(
  441. "SELECT count(*) FROM %s" % (table,),
  442. )
  443. defer.returnValue(rows[0][0])
  444. @defer.inlineCallbacks
  445. def _get_total_count_to_port(self, table, next_chunk):
  446. remaining, done = yield defer.gatherResults(
  447. [
  448. self._get_remaining_count_to_port(table, next_chunk),
  449. self._get_already_ported_count(table),
  450. ],
  451. consumeErrors=True,
  452. )
  453. remaining = int(remaining) if remaining else 0
  454. done = int(done) if done else 0
  455. defer.returnValue((done, remaining + done))
  456. ##############################################
  457. ###### The following is simply UI stuff ######
  458. ##############################################
  459. class Progress(object):
  460. """Used to report progress of the port
  461. """
  462. def __init__(self):
  463. self.tables = {}
  464. self.start_time = int(time.time())
  465. def add_table(self, table, cur, size):
  466. self.tables[table] = {
  467. "start": cur,
  468. "num_done": cur,
  469. "total": size,
  470. "perc": int(cur * 100 / size),
  471. }
  472. def update(self, table, num_done):
  473. data = self.tables[table]
  474. data["num_done"] = num_done
  475. data["perc"] = int(num_done * 100 / data["total"])
  476. def done(self):
  477. pass
  478. class CursesProgress(Progress):
  479. """Reports progress to a curses window
  480. """
  481. def __init__(self, stdscr):
  482. self.stdscr = stdscr
  483. curses.use_default_colors()
  484. curses.curs_set(0)
  485. curses.init_pair(1, curses.COLOR_RED, -1)
  486. curses.init_pair(2, curses.COLOR_GREEN, -1)
  487. self.last_update = 0
  488. self.finished = False
  489. self.total_processed = 0
  490. self.total_remaining = 0
  491. super(CursesProgress, self).__init__()
  492. def update(self, table, num_done):
  493. super(CursesProgress, self).update(table, num_done)
  494. self.total_processed = 0
  495. self.total_remaining = 0
  496. for table, data in self.tables.items():
  497. self.total_processed += data["num_done"] - data["start"]
  498. self.total_remaining += data["total"] - data["num_done"]
  499. self.render()
  500. def render(self, force=False):
  501. now = time.time()
  502. if not force and now - self.last_update < 0.2:
  503. # reactor.callLater(1, self.render)
  504. return
  505. self.stdscr.clear()
  506. rows, cols = self.stdscr.getmaxyx()
  507. duration = int(now) - int(self.start_time)
  508. minutes, seconds = divmod(duration, 60)
  509. duration_str = '%02dm %02ds' % (minutes, seconds,)
  510. if self.finished:
  511. status = "Time spent: %s (Done!)" % (duration_str,)
  512. else:
  513. if self.total_processed > 0:
  514. left = float(self.total_remaining) / self.total_processed
  515. est_remaining = (int(now) - self.start_time) * left
  516. est_remaining_str = '%02dm %02ds remaining' % divmod(est_remaining, 60)
  517. else:
  518. est_remaining_str = "Unknown"
  519. status = (
  520. "Time spent: %s (est. remaining: %s)"
  521. % (duration_str, est_remaining_str,)
  522. )
  523. self.stdscr.addstr(
  524. 0, 0,
  525. status,
  526. curses.A_BOLD,
  527. )
  528. max_len = max([len(t) for t in self.tables.keys()])
  529. left_margin = 5
  530. middle_space = 1
  531. items = self.tables.items()
  532. items.sort(
  533. key=lambda i: (i[1]["perc"], i[0]),
  534. )
  535. for i, (table, data) in enumerate(items):
  536. if i + 2 >= rows:
  537. break
  538. perc = data["perc"]
  539. color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
  540. self.stdscr.addstr(
  541. i+2, left_margin + max_len - len(table),
  542. table,
  543. curses.A_BOLD | color,
  544. )
  545. size = 20
  546. progress = "[%s%s]" % (
  547. "#" * int(perc*size/100),
  548. " " * (size - int(perc*size/100)),
  549. )
  550. self.stdscr.addstr(
  551. i+2, left_margin + max_len + middle_space,
  552. "%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
  553. )
  554. if self.finished:
  555. self.stdscr.addstr(
  556. rows-1, 0,
  557. "Press any key to exit...",
  558. )
  559. self.stdscr.refresh()
  560. self.last_update = time.time()
  561. def done(self):
  562. self.finished = True
  563. self.render(True)
  564. self.stdscr.getch()
  565. def set_state(self, state):
  566. self.stdscr.clear()
  567. self.stdscr.addstr(
  568. 0, 0,
  569. state + "...",
  570. curses.A_BOLD,
  571. )
  572. self.stdscr.refresh()
  573. class TerminalProgress(Progress):
  574. """Just prints progress to the terminal
  575. """
  576. def update(self, table, num_done):
  577. super(TerminalProgress, self).update(table, num_done)
  578. data = self.tables[table]
  579. print "%s: %d%% (%d/%d)" % (
  580. table, data["perc"],
  581. data["num_done"], data["total"],
  582. )
  583. def set_state(self, state):
  584. print state + "..."
  585. ##############################################
  586. ##############################################
  587. if __name__ == "__main__":
  588. parser = argparse.ArgumentParser(
  589. description="A script to port an existing synapse SQLite database to"
  590. " a new PostgreSQL database."
  591. )
  592. parser.add_argument("-v", action='store_true')
  593. parser.add_argument(
  594. "--sqlite-database", required=True,
  595. help="The snapshot of the SQLite database file. This must not be"
  596. " currently used by a running synapse server"
  597. )
  598. parser.add_argument(
  599. "--postgres-config", type=argparse.FileType('r'), required=True,
  600. help="The database config file for the PostgreSQL database"
  601. )
  602. parser.add_argument(
  603. "--curses", action='store_true',
  604. help="display a curses based progress UI"
  605. )
  606. parser.add_argument(
  607. "--batch-size", type=int, default=1000,
  608. help="The number of rows to select from the SQLite table each"
  609. " iteration [default=1000]",
  610. )
  611. args = parser.parse_args()
  612. logging_config = {
  613. "level": logging.DEBUG if args.v else logging.INFO,
  614. "format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s"
  615. }
  616. if args.curses:
  617. logging_config["filename"] = "port-synapse.log"
  618. logging.basicConfig(**logging_config)
  619. sqlite_config = {
  620. "name": "sqlite3",
  621. "args": {
  622. "database": args.sqlite_database,
  623. "cp_min": 1,
  624. "cp_max": 1,
  625. "check_same_thread": False,
  626. },
  627. }
  628. postgres_config = yaml.safe_load(args.postgres_config)
  629. if "database" in postgres_config:
  630. postgres_config = postgres_config["database"]
  631. if "name" not in postgres_config:
  632. sys.stderr.write("Malformed database config: no 'name'")
  633. sys.exit(2)
  634. if postgres_config["name"] != "psycopg2":
  635. sys.stderr.write("Database must use 'psycopg2' connector.")
  636. sys.exit(3)
  637. def start(stdscr=None):
  638. if stdscr:
  639. progress = CursesProgress(stdscr)
  640. else:
  641. progress = TerminalProgress()
  642. porter = Porter(
  643. sqlite_config=sqlite_config,
  644. postgres_config=postgres_config,
  645. progress=progress,
  646. batch_size=args.batch_size,
  647. )
  648. reactor.callWhenRunning(porter.run)
  649. reactor.run()
  650. if args.curses:
  651. curses.wrapper(start)
  652. else:
  653. start()
  654. if end_error_exec_info:
  655. exc_type, exc_value, exc_traceback = end_error_exec_info
  656. traceback.print_exception(exc_type, exc_value, exc_traceback)