2015-05-06 06:41:19 -04:00
|
|
|
#!/usr/bin/env python
|
2015-04-10 13:47:20 -04:00
|
|
|
# -*- coding: utf-8 -*-
|
2016-01-06 23:26:29 -05:00
|
|
|
# Copyright 2015, 2016 OpenMarket Ltd
|
2018-04-06 08:45:10 -04:00
|
|
|
# Copyright 2018 New Vector Ltd
|
2019-10-23 10:31:59 -04:00
|
|
|
# Copyright 2019 The Matrix.org Foundation C.I.C.
|
2015-04-10 13:47:20 -04:00
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import argparse
|
2015-04-17 06:13:05 -04:00
|
|
|
import curses
|
2015-04-10 13:47:20 -04:00
|
|
|
import logging
|
2015-04-17 06:13:05 -04:00
|
|
|
import sys
|
|
|
|
import time
|
|
|
|
import traceback
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2018-04-06 18:37:36 -04:00
|
|
|
from six import string_types
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
import yaml
|
|
|
|
|
|
|
|
from twisted.enterprise import adbapi
|
|
|
|
from twisted.internet import defer, reactor
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
from synapse.config.homeserver import HomeServerConfig
|
|
|
|
from synapse.logging.context import PreserveLoggingContext
|
|
|
|
from synapse.storage._base import LoggingTransaction
|
2019-10-23 10:54:17 -04:00
|
|
|
from synapse.storage.data_stores.main.client_ips import ClientIpBackgroundUpdateStore
|
2019-10-24 08:31:49 -04:00
|
|
|
from synapse.storage.data_stores.main.deviceinbox import (
|
|
|
|
DeviceInboxBackgroundUpdateStore,
|
|
|
|
)
|
2019-10-23 10:54:17 -04:00
|
|
|
from synapse.storage.data_stores.main.devices import DeviceBackgroundUpdateStore
|
|
|
|
from synapse.storage.data_stores.main.events_bg_updates import (
|
2019-10-24 08:31:49 -04:00
|
|
|
EventsBackgroundUpdatesStore,
|
2019-10-23 10:54:17 -04:00
|
|
|
)
|
|
|
|
from synapse.storage.data_stores.main.media_repository import (
|
2019-10-24 08:31:49 -04:00
|
|
|
MediaRepositoryBackgroundUpdateStore,
|
2019-10-23 10:54:17 -04:00
|
|
|
)
|
|
|
|
from synapse.storage.data_stores.main.registration import (
|
2019-10-24 08:31:49 -04:00
|
|
|
RegistrationBackgroundUpdateStore,
|
2019-10-23 10:54:17 -04:00
|
|
|
)
|
2019-12-04 12:57:35 -05:00
|
|
|
from synapse.storage.data_stores.main.room import RoomBackgroundUpdateStore
|
2019-10-23 10:54:17 -04:00
|
|
|
from synapse.storage.data_stores.main.roommember import RoomMemberBackgroundUpdateStore
|
|
|
|
from synapse.storage.data_stores.main.search import SearchBackgroundUpdateStore
|
|
|
|
from synapse.storage.data_stores.main.state import StateBackgroundUpdateStore
|
|
|
|
from synapse.storage.data_stores.main.stats import StatsStore
|
|
|
|
from synapse.storage.data_stores.main.user_directory import (
|
2019-10-24 08:31:49 -04:00
|
|
|
UserDirectoryBackgroundUpdateStore,
|
2019-10-23 10:54:17 -04:00
|
|
|
)
|
2019-10-24 08:31:49 -04:00
|
|
|
from synapse.storage.engines import create_engine
|
|
|
|
from synapse.storage.prepare_database import prepare_database
|
2019-10-23 10:31:59 -04:00
|
|
|
from synapse.util import Clock
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-09-03 02:51:42 -04:00
|
|
|
logger = logging.getLogger("synapse_port_db")
|
2015-04-10 13:47:20 -04:00
|
|
|
|
|
|
|
|
2015-04-15 05:23:24 -04:00
|
|
|
BOOLEAN_COLUMNS = {
|
2016-08-04 06:28:02 -04:00
|
|
|
"events": ["processed", "outlier", "contains_url"],
|
2015-04-15 05:23:24 -04:00
|
|
|
"rooms": ["is_public"],
|
|
|
|
"event_edges": ["is_state"],
|
|
|
|
"presence_list": ["accepted"],
|
2016-04-06 09:08:18 -04:00
|
|
|
"presence_stream": ["currently_active"],
|
2016-09-27 06:19:45 -04:00
|
|
|
"public_room_list_stream": ["visibility"],
|
2019-10-24 07:38:48 -04:00
|
|
|
"devices": ["hidden"],
|
2017-02-11 20:49:31 -05:00
|
|
|
"device_lists_outbound_pokes": ["sent"],
|
2017-06-16 15:51:19 -04:00
|
|
|
"users_who_share_rooms": ["share_private"],
|
2017-10-26 12:24:54 -04:00
|
|
|
"groups": ["is_public"],
|
2017-11-14 10:55:15 -05:00
|
|
|
"group_rooms": ["is_public"],
|
|
|
|
"group_users": ["is_public", "is_admin"],
|
2017-11-14 10:48:50 -05:00
|
|
|
"group_summary_rooms": ["is_public"],
|
|
|
|
"group_room_categories": ["is_public"],
|
|
|
|
"group_summary_users": ["is_public"],
|
|
|
|
"group_roles": ["is_public"],
|
|
|
|
"local_group_membership": ["is_publicised", "is_admin"],
|
2019-02-20 17:11:21 -05:00
|
|
|
"e2e_room_keys": ["is_verified"],
|
2019-06-03 12:06:47 -04:00
|
|
|
"account_validity": ["email_sent"],
|
2019-10-18 05:13:59 -04:00
|
|
|
"redactions": ["have_censored"],
|
|
|
|
"room_stats_state": ["is_federatable"],
|
2015-04-15 05:23:24 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2015-04-13 08:45:04 -04:00
|
|
|
APPEND_ONLY_TABLES = [
|
|
|
|
"event_reference_hashes",
|
|
|
|
"events",
|
|
|
|
"event_json",
|
|
|
|
"state_events",
|
|
|
|
"room_memberships",
|
|
|
|
"topics",
|
|
|
|
"room_names",
|
|
|
|
"rooms",
|
|
|
|
"local_media_repository",
|
|
|
|
"local_media_repository_thumbnails",
|
|
|
|
"remote_media_cache",
|
|
|
|
"remote_media_cache_thumbnails",
|
|
|
|
"redactions",
|
|
|
|
"event_edges",
|
|
|
|
"event_auth",
|
|
|
|
"received_transactions",
|
|
|
|
"sent_transactions",
|
|
|
|
"transaction_id_to_pdu",
|
|
|
|
"users",
|
|
|
|
"state_groups",
|
|
|
|
"state_groups_state",
|
|
|
|
"event_to_state_groups",
|
|
|
|
"rejections",
|
2015-11-18 10:54:50 -05:00
|
|
|
"event_search",
|
2016-09-27 06:19:45 -04:00
|
|
|
"presence_stream",
|
|
|
|
"push_rules_stream",
|
|
|
|
"ex_outlier_stream",
|
|
|
|
"cache_invalidation_stream",
|
|
|
|
"public_room_list_stream",
|
|
|
|
"state_group_edges",
|
|
|
|
"stream_ordering_to_exterm",
|
2015-04-13 08:45:04 -04:00
|
|
|
]
|
|
|
|
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
end_error_exec_info = None
|
|
|
|
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
class Store(
|
|
|
|
ClientIpBackgroundUpdateStore,
|
|
|
|
DeviceInboxBackgroundUpdateStore,
|
|
|
|
DeviceBackgroundUpdateStore,
|
|
|
|
EventsBackgroundUpdatesStore,
|
|
|
|
MediaRepositoryBackgroundUpdateStore,
|
|
|
|
RegistrationBackgroundUpdateStore,
|
2019-12-04 12:57:35 -05:00
|
|
|
RoomBackgroundUpdateStore,
|
2019-10-23 10:31:59 -04:00
|
|
|
RoomMemberBackgroundUpdateStore,
|
|
|
|
SearchBackgroundUpdateStore,
|
|
|
|
StateBackgroundUpdateStore,
|
|
|
|
UserDirectoryBackgroundUpdateStore,
|
|
|
|
StatsStore,
|
|
|
|
):
|
|
|
|
def __init__(self, db_conn, hs):
|
|
|
|
super().__init__(db_conn, hs)
|
|
|
|
self.db_pool = hs.get_db_pool()
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
@defer.inlineCallbacks
|
2015-04-10 13:47:20 -04:00
|
|
|
def runInteraction(self, desc, func, *args, **kwargs):
|
|
|
|
def r(conn):
|
|
|
|
try:
|
|
|
|
i = 0
|
|
|
|
N = 5
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
txn = conn.cursor()
|
|
|
|
return func(
|
2017-06-16 15:24:14 -04:00
|
|
|
LoggingTransaction(txn, desc, self.database_engine, [], []),
|
2018-10-19 20:16:55 -04:00
|
|
|
*args,
|
|
|
|
**kwargs
|
2015-04-10 13:47:20 -04:00
|
|
|
)
|
2015-04-13 08:45:04 -04:00
|
|
|
except self.database_engine.module.DatabaseError as e:
|
|
|
|
if self.database_engine.is_deadlock(e):
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning("[TXN DEADLOCK] {%s} %d/%d", desc, i, N)
|
2015-04-10 13:47:20 -04:00
|
|
|
if i < N:
|
|
|
|
i += 1
|
|
|
|
conn.rollback()
|
|
|
|
continue
|
|
|
|
raise
|
|
|
|
except Exception as e:
|
2015-04-17 06:13:05 -04:00
|
|
|
logger.debug("[TXN FAIL] {%s} %s", desc, e)
|
2015-04-10 13:47:20 -04:00
|
|
|
raise
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
with PreserveLoggingContext():
|
|
|
|
return (yield self.db_pool.runWithConnection(r))
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-27 12:36:37 -04:00
|
|
|
def execute(self, f, *args, **kwargs):
|
|
|
|
return self.runInteraction(f.__name__, f, *args, **kwargs)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
def execute_sql(self, sql, *args):
|
|
|
|
def r(txn):
|
|
|
|
txn.execute(sql, args)
|
|
|
|
return txn.fetchall()
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
return self.runInteraction("execute_sql", r)
|
|
|
|
|
2015-04-15 05:23:24 -04:00
|
|
|
def insert_many_txn(self, txn, table, headers, rows):
|
2015-04-10 13:47:20 -04:00
|
|
|
sql = "INSERT INTO %s (%s) VALUES (%s)" % (
|
|
|
|
table,
|
|
|
|
", ".join(k for k in headers),
|
2018-10-19 20:16:55 -04:00
|
|
|
", ".join("%s" for _ in headers),
|
2015-04-10 13:47:20 -04:00
|
|
|
)
|
|
|
|
|
2015-04-15 05:23:24 -04:00
|
|
|
try:
|
|
|
|
txn.executemany(sql, rows)
|
2018-10-19 20:16:55 -04:00
|
|
|
except Exception:
|
|
|
|
logger.exception("Failed to insert: %s", table)
|
2015-04-15 05:23:24 -04:00
|
|
|
raise
|
2015-04-10 13:47:20 -04:00
|
|
|
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
class MockHomeserver:
|
|
|
|
def __init__(self, config, database_engine, db_conn, db_pool):
|
|
|
|
self.database_engine = database_engine
|
|
|
|
self.db_conn = db_conn
|
|
|
|
self.db_pool = db_pool
|
|
|
|
self.clock = Clock(reactor)
|
|
|
|
self.config = config
|
|
|
|
self.hostname = config.server_name
|
|
|
|
|
|
|
|
def get_db_conn(self):
|
|
|
|
return self.db_conn
|
|
|
|
|
|
|
|
def get_db_pool(self):
|
|
|
|
return self.db_pool
|
|
|
|
|
|
|
|
def get_clock(self):
|
|
|
|
return self.clock
|
|
|
|
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
class Porter(object):
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
self.__dict__.update(kwargs)
|
2015-04-15 05:23:24 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
@defer.inlineCallbacks
|
2015-04-27 12:53:40 -04:00
|
|
|
def setup_table(self, table):
|
2015-04-28 06:16:44 -04:00
|
|
|
if table in APPEND_ONLY_TABLES:
|
2015-04-17 06:13:05 -04:00
|
|
|
# It's safe to just carry on inserting.
|
2019-12-04 05:15:55 -05:00
|
|
|
row = yield self.postgres_store.simple_select_one(
|
2015-04-17 06:13:05 -04:00
|
|
|
table="port_from_sqlite3",
|
|
|
|
keyvalues={"table_name": table},
|
2016-08-04 06:28:02 -04:00
|
|
|
retcols=("forward_rowid", "backward_rowid"),
|
2015-04-17 06:13:05 -04:00
|
|
|
allow_none=True,
|
|
|
|
)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
total_to_port = None
|
2016-08-04 06:28:02 -04:00
|
|
|
if row is None:
|
2015-04-28 06:16:44 -04:00
|
|
|
if table == "sent_transactions":
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_chunk, already_ported, total_to_port = (
|
2015-04-28 06:16:44 -04:00
|
|
|
yield self._setup_sent_transactions()
|
|
|
|
)
|
2016-08-04 06:28:02 -04:00
|
|
|
backward_chunk = 0
|
2015-04-28 06:16:44 -04:00
|
|
|
else:
|
2019-12-04 05:15:55 -05:00
|
|
|
yield self.postgres_store.simple_insert(
|
2015-04-28 06:16:44 -04:00
|
|
|
table="port_from_sqlite3",
|
2016-08-04 06:28:02 -04:00
|
|
|
values={
|
|
|
|
"table_name": table,
|
|
|
|
"forward_rowid": 1,
|
|
|
|
"backward_rowid": 0,
|
2018-10-19 20:16:55 -04:00
|
|
|
},
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
2015-04-13 08:45:04 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_chunk = 1
|
|
|
|
backward_chunk = 0
|
2015-04-28 06:16:44 -04:00
|
|
|
already_ported = 0
|
2016-08-04 06:28:02 -04:00
|
|
|
else:
|
|
|
|
forward_chunk = row["forward_rowid"]
|
|
|
|
backward_chunk = row["backward_rowid"]
|
2015-04-27 12:36:37 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
if total_to_port is None:
|
|
|
|
already_ported, total_to_port = yield self._get_total_count_to_port(
|
2016-08-04 06:28:02 -04:00
|
|
|
table, forward_chunk, backward_chunk
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
else:
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
def delete_all(txn):
|
|
|
|
txn.execute(
|
2018-10-19 20:16:55 -04:00
|
|
|
"DELETE FROM port_from_sqlite3 WHERE table_name = %s", (table,)
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
txn.execute("TRUNCATE %s CASCADE" % (table,))
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
yield self.postgres_store.execute(delete_all)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
2019-12-04 05:15:55 -05:00
|
|
|
yield self.postgres_store.simple_insert(
|
2015-04-27 12:36:37 -04:00
|
|
|
table="port_from_sqlite3",
|
2018-10-19 20:16:55 -04:00
|
|
|
values={"table_name": table, "forward_rowid": 1, "backward_rowid": 0},
|
2015-04-27 12:36:37 -04:00
|
|
|
)
|
2015-04-15 05:23:24 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_chunk = 1
|
|
|
|
backward_chunk = 0
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
already_ported, total_to_port = yield self._get_total_count_to_port(
|
2016-08-04 06:28:02 -04:00
|
|
|
table, forward_chunk, backward_chunk
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
defer.returnValue(
|
|
|
|
(table, already_ported, total_to_port, forward_chunk, backward_chunk)
|
|
|
|
)
|
2015-04-27 12:53:40 -04:00
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
2018-10-19 20:16:55 -04:00
|
|
|
def handle_table(
|
|
|
|
self, table, postgres_size, table_size, forward_chunk, backward_chunk
|
|
|
|
):
|
2018-04-06 08:47:11 -04:00
|
|
|
logger.info(
|
|
|
|
"Table %s: %i/%i (rows %i-%i) already ported",
|
2018-10-19 20:16:55 -04:00
|
|
|
table,
|
|
|
|
postgres_size,
|
|
|
|
table_size,
|
|
|
|
backward_chunk + 1,
|
|
|
|
forward_chunk - 1,
|
2018-04-06 08:47:11 -04:00
|
|
|
)
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
if not table_size:
|
2015-04-10 13:47:20 -04:00
|
|
|
return
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
self.progress.add_table(table, postgres_size, table_size)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-04-22 05:35:53 -04:00
|
|
|
if table == "event_search":
|
2016-08-04 06:28:02 -04:00
|
|
|
yield self.handle_search_table(
|
|
|
|
postgres_size, table_size, forward_chunk, backward_chunk
|
|
|
|
)
|
2016-04-22 05:35:53 -04:00
|
|
|
return
|
|
|
|
|
2017-07-20 05:47:01 -04:00
|
|
|
if table in (
|
2018-10-19 20:16:55 -04:00
|
|
|
"user_directory",
|
|
|
|
"user_directory_search",
|
|
|
|
"users_who_share_rooms",
|
2017-07-20 05:47:01 -04:00
|
|
|
"users_in_pubic_room",
|
|
|
|
):
|
|
|
|
# We don't port these tables, as they're a faff and we can regenreate
|
|
|
|
# them anyway.
|
|
|
|
self.progress.update(table, table_size) # Mark table as done
|
|
|
|
return
|
|
|
|
|
|
|
|
if table == "user_directory_stream_pos":
|
2017-07-20 11:16:29 -04:00
|
|
|
# We need to make sure there is a single row, `(X, null), as that is
|
|
|
|
# what synapse expects to be there.
|
2019-12-04 05:15:55 -05:00
|
|
|
yield self.postgres_store.simple_insert(
|
2018-10-19 20:16:55 -04:00
|
|
|
table=table, values={"stream_id": None}
|
2017-07-20 05:47:01 -04:00
|
|
|
)
|
|
|
|
self.progress.update(table, table_size) # Mark table as done
|
|
|
|
return
|
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_select = (
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT rowid, * FROM %s WHERE rowid >= ? ORDER BY rowid LIMIT ?" % (table,)
|
2015-04-17 06:13:05 -04:00
|
|
|
)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
backward_select = (
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT rowid, * FROM %s WHERE rowid <= ? ORDER BY rowid LIMIT ?" % (table,)
|
2016-08-04 06:28:02 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
do_forward = [True]
|
|
|
|
do_backward = [True]
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
while True:
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
def r(txn):
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_rows = []
|
|
|
|
backward_rows = []
|
|
|
|
if do_forward[0]:
|
2018-10-19 20:16:55 -04:00
|
|
|
txn.execute(forward_select, (forward_chunk, self.batch_size))
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_rows = txn.fetchall()
|
|
|
|
if not forward_rows:
|
|
|
|
do_forward[0] = False
|
|
|
|
|
|
|
|
if do_backward[0]:
|
2018-10-19 20:16:55 -04:00
|
|
|
txn.execute(backward_select, (backward_chunk, self.batch_size))
|
2016-08-04 06:28:02 -04:00
|
|
|
backward_rows = txn.fetchall()
|
|
|
|
if not backward_rows:
|
|
|
|
do_backward[0] = False
|
|
|
|
|
|
|
|
if forward_rows or backward_rows:
|
|
|
|
headers = [column[0] for column in txn.description]
|
|
|
|
else:
|
|
|
|
headers = None
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
return headers, forward_rows, backward_rows
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
headers, frows, brows = yield self.sqlite_store.runInteraction("select", r)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
if frows or brows:
|
|
|
|
if frows:
|
|
|
|
forward_chunk = max(row[0] for row in frows) + 1
|
|
|
|
if brows:
|
|
|
|
backward_chunk = min(row[0] for row in brows) - 1
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
rows = frows + brows
|
2017-10-31 12:58:49 -04:00
|
|
|
rows = self._convert_rows(table, headers, rows)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-04-22 05:35:53 -04:00
|
|
|
def insert(txn):
|
2018-10-19 20:16:55 -04:00
|
|
|
self.postgres_store.insert_many_txn(txn, table, headers[1:], rows)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2019-12-04 05:15:55 -05:00
|
|
|
self.postgres_store.simple_update_one_txn(
|
2016-04-22 05:35:53 -04:00
|
|
|
txn,
|
|
|
|
table="port_from_sqlite3",
|
|
|
|
keyvalues={"table_name": table},
|
2016-08-04 06:28:02 -04:00
|
|
|
updatevalues={
|
|
|
|
"forward_rowid": forward_chunk,
|
|
|
|
"backward_rowid": backward_chunk,
|
|
|
|
},
|
2016-04-22 05:35:53 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
yield self.postgres_store.execute(insert)
|
|
|
|
|
|
|
|
postgres_size += len(rows)
|
|
|
|
|
|
|
|
self.progress.update(table, postgres_size)
|
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
2018-10-19 20:16:55 -04:00
|
|
|
def handle_search_table(
|
|
|
|
self, postgres_size, table_size, forward_chunk, backward_chunk
|
|
|
|
):
|
2016-04-22 05:35:53 -04:00
|
|
|
select = (
|
|
|
|
"SELECT es.rowid, es.*, e.origin_server_ts, e.stream_ordering"
|
|
|
|
" FROM event_search as es"
|
|
|
|
" INNER JOIN events AS e USING (event_id, room_id)"
|
|
|
|
" WHERE es.rowid >= ?"
|
|
|
|
" ORDER BY es.rowid LIMIT ?"
|
|
|
|
)
|
2015-11-18 10:54:50 -05:00
|
|
|
|
2016-04-22 05:35:53 -04:00
|
|
|
while True:
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2016-04-22 05:35:53 -04:00
|
|
|
def r(txn):
|
2018-10-19 20:16:55 -04:00
|
|
|
txn.execute(select, (forward_chunk, self.batch_size))
|
2016-04-22 05:35:53 -04:00
|
|
|
rows = txn.fetchall()
|
|
|
|
headers = [column[0] for column in txn.description]
|
|
|
|
|
|
|
|
return headers, rows
|
|
|
|
|
|
|
|
headers, rows = yield self.sqlite_store.runInteraction("select", r)
|
|
|
|
|
|
|
|
if rows:
|
2016-08-04 06:28:02 -04:00
|
|
|
forward_chunk = rows[-1][0] + 1
|
2016-04-22 05:35:53 -04:00
|
|
|
|
|
|
|
# We have to treat event_search differently since it has a
|
|
|
|
# different structure in the two different databases.
|
|
|
|
def insert(txn):
|
|
|
|
sql = (
|
|
|
|
"INSERT INTO event_search (event_id, room_id, key,"
|
|
|
|
" sender, vector, origin_server_ts, stream_ordering)"
|
|
|
|
" VALUES (?,?,?,?,to_tsvector('english', ?),?,?)"
|
|
|
|
)
|
|
|
|
|
2017-10-01 19:53:32 -04:00
|
|
|
rows_dict = []
|
|
|
|
for row in rows:
|
|
|
|
d = dict(zip(headers, row))
|
|
|
|
if "\0" in d['value']:
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning('dropping search row %s', d)
|
2017-10-01 19:53:32 -04:00
|
|
|
else:
|
|
|
|
rows_dict.append(d)
|
2016-04-22 05:35:53 -04:00
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
txn.executemany(
|
|
|
|
sql,
|
|
|
|
[
|
|
|
|
(
|
|
|
|
row["event_id"],
|
|
|
|
row["room_id"],
|
|
|
|
row["key"],
|
|
|
|
row["sender"],
|
|
|
|
row["value"],
|
|
|
|
row["origin_server_ts"],
|
|
|
|
row["stream_ordering"],
|
|
|
|
)
|
|
|
|
for row in rows_dict
|
|
|
|
],
|
|
|
|
)
|
2016-04-22 05:35:53 -04:00
|
|
|
|
2019-12-04 05:15:55 -05:00
|
|
|
self.postgres_store.simple_update_one_txn(
|
2016-04-22 05:35:53 -04:00
|
|
|
txn,
|
|
|
|
table="port_from_sqlite3",
|
|
|
|
keyvalues={"table_name": "event_search"},
|
2016-08-04 06:28:02 -04:00
|
|
|
updatevalues={
|
|
|
|
"forward_rowid": forward_chunk,
|
|
|
|
"backward_rowid": backward_chunk,
|
|
|
|
},
|
2016-04-22 05:35:53 -04:00
|
|
|
)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
yield self.postgres_store.execute(insert)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
postgres_size += len(rows)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2016-04-22 05:35:53 -04:00
|
|
|
self.progress.update("event_search", postgres_size)
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
else:
|
|
|
|
return
|
|
|
|
|
|
|
|
def setup_db(self, db_config, database_engine):
|
|
|
|
db_conn = database_engine.module.connect(
|
|
|
|
**{
|
2018-10-19 20:16:55 -04:00
|
|
|
k: v
|
|
|
|
for k, v in db_config.get("args", {}).items()
|
2015-04-17 06:13:05 -04:00
|
|
|
if not k.startswith("cp_")
|
|
|
|
}
|
2015-04-10 13:47:20 -04:00
|
|
|
)
|
|
|
|
|
2016-04-06 09:08:18 -04:00
|
|
|
prepare_database(db_conn, database_engine, config=None)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
db_conn.commit()
|
2015-04-13 08:45:04 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
return db_conn
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
@defer.inlineCallbacks
|
2019-10-23 10:31:59 -04:00
|
|
|
def build_db_store(self, config):
|
|
|
|
"""Builds and returns a database store using the provided configuration.
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
Args:
|
|
|
|
config: The database configuration, i.e. a dict following the structure of
|
|
|
|
the "database" section of Synapse's configuration file.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The built Store object.
|
|
|
|
"""
|
|
|
|
engine = create_engine(config)
|
|
|
|
|
|
|
|
self.progress.set_state("Preparing %s" % config["name"])
|
|
|
|
conn = self.setup_db(config, engine)
|
|
|
|
|
|
|
|
db_pool = adbapi.ConnectionPool(
|
|
|
|
config["name"], **config["args"]
|
|
|
|
)
|
|
|
|
|
|
|
|
hs = MockHomeserver(self.hs_config, engine, conn, db_pool)
|
|
|
|
|
|
|
|
store = Store(conn, hs)
|
|
|
|
|
|
|
|
yield store.runInteraction(
|
|
|
|
"%s_engine.check_database" % config["name"],
|
|
|
|
engine.check_database,
|
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
return store
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def run_background_updates_on_postgres(self):
|
|
|
|
# Manually apply all background updates on the PostgreSQL database.
|
|
|
|
postgres_ready = yield self.postgres_store.has_completed_background_updates()
|
|
|
|
|
|
|
|
if not postgres_ready:
|
|
|
|
# Only say that we're running background updates when there are background
|
|
|
|
# updates to run.
|
|
|
|
self.progress.set_state("Running background updates on PostgreSQL")
|
|
|
|
|
|
|
|
while not postgres_ready:
|
|
|
|
yield self.postgres_store.do_next_background_update(100)
|
|
|
|
postgres_ready = yield (
|
|
|
|
self.postgres_store.has_completed_background_updates()
|
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
@defer.inlineCallbacks
|
|
|
|
def run(self):
|
|
|
|
try:
|
|
|
|
self.sqlite_store = yield self.build_db_store(self.sqlite_config)
|
|
|
|
|
|
|
|
# Check if all background updates are done, abort if not.
|
|
|
|
updates_complete = yield self.sqlite_store.has_completed_background_updates()
|
|
|
|
if not updates_complete:
|
|
|
|
sys.stderr.write(
|
|
|
|
"Pending background updates exist in the SQLite3 database."
|
|
|
|
" Please start Synapse again and wait until every update has finished"
|
|
|
|
" before running this script.\n"
|
|
|
|
)
|
|
|
|
defer.returnValue(None)
|
2015-04-29 06:42:28 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
self.postgres_store = yield self.build_db_store(
|
|
|
|
self.hs_config.database_config
|
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
yield self.run_background_updates_on_postgres()
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2018-04-06 08:47:11 -04:00
|
|
|
self.progress.set_state("Creating port tables")
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
def create_port_table(txn):
|
|
|
|
txn.execute(
|
2018-04-06 08:45:10 -04:00
|
|
|
"CREATE TABLE IF NOT EXISTS port_from_sqlite3 ("
|
2015-04-17 06:13:05 -04:00
|
|
|
" table_name varchar(100) NOT NULL UNIQUE,"
|
2016-08-04 06:28:02 -04:00
|
|
|
" forward_rowid bigint NOT NULL,"
|
|
|
|
" backward_rowid bigint NOT NULL"
|
2015-04-17 06:13:05 -04:00
|
|
|
")"
|
|
|
|
)
|
|
|
|
|
2016-08-04 06:35:49 -04:00
|
|
|
# The old port script created a table with just a "rowid" column.
|
|
|
|
# We want people to be able to rerun this script from an old port
|
|
|
|
# so that they can pick up any missing events that were not
|
|
|
|
# ported across.
|
|
|
|
def alter_table(txn):
|
|
|
|
txn.execute(
|
|
|
|
"ALTER TABLE IF EXISTS port_from_sqlite3"
|
|
|
|
" RENAME rowid TO forward_rowid"
|
|
|
|
)
|
|
|
|
txn.execute(
|
|
|
|
"ALTER TABLE IF EXISTS port_from_sqlite3"
|
|
|
|
" ADD backward_rowid bigint NOT NULL DEFAULT 0"
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
2018-10-19 20:16:55 -04:00
|
|
|
yield self.postgres_store.runInteraction("alter_table", alter_table)
|
2018-10-24 05:35:01 -04:00
|
|
|
except Exception:
|
|
|
|
# On Error Resume Next
|
2018-04-06 08:45:10 -04:00
|
|
|
pass
|
2016-08-04 06:35:49 -04:00
|
|
|
|
2018-04-06 08:45:10 -04:00
|
|
|
yield self.postgres_store.runInteraction(
|
|
|
|
"create_port_table", create_port_table
|
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2018-04-06 08:47:11 -04:00
|
|
|
# Step 2. Get tables.
|
|
|
|
self.progress.set_state("Fetching tables")
|
2019-12-04 05:15:55 -05:00
|
|
|
sqlite_tables = yield self.sqlite_store.simple_select_onecol(
|
2018-10-19 20:16:55 -04:00
|
|
|
table="sqlite_master", keyvalues={"type": "table"}, retcol="name"
|
2018-04-06 08:47:11 -04:00
|
|
|
)
|
|
|
|
|
2019-12-04 05:15:55 -05:00
|
|
|
postgres_tables = yield self.postgres_store.simple_select_onecol(
|
2018-04-06 08:47:11 -04:00
|
|
|
table="information_schema.tables",
|
|
|
|
keyvalues={},
|
|
|
|
retcol="distinct table_name",
|
|
|
|
)
|
|
|
|
|
|
|
|
tables = set(sqlite_tables) & set(postgres_tables)
|
|
|
|
logger.info("Found %d tables", len(tables))
|
2015-04-27 12:53:40 -04:00
|
|
|
|
2018-04-06 08:47:11 -04:00
|
|
|
# Step 3. Figure out what still needs copying
|
|
|
|
self.progress.set_state("Checking on port progress")
|
2015-04-27 12:53:40 -04:00
|
|
|
setup_res = yield defer.gatherResults(
|
2015-04-17 06:13:05 -04:00
|
|
|
[
|
2015-04-27 12:53:40 -04:00
|
|
|
self.setup_table(table)
|
2015-04-17 06:13:05 -04:00
|
|
|
for table in tables
|
|
|
|
if table not in ["schema_version", "applied_schema_deltas"]
|
|
|
|
and not table.startswith("sqlite_")
|
|
|
|
],
|
|
|
|
consumeErrors=True,
|
|
|
|
)
|
|
|
|
|
2018-04-06 08:47:11 -04:00
|
|
|
# Step 4. Do the copying.
|
|
|
|
self.progress.set_state("Copying to postgres")
|
2015-04-27 12:53:40 -04:00
|
|
|
yield defer.gatherResults(
|
2018-10-19 20:16:55 -04:00
|
|
|
[self.handle_table(*res) for res in setup_res], consumeErrors=True
|
2015-04-27 12:53:40 -04:00
|
|
|
)
|
|
|
|
|
2018-04-06 08:48:40 -04:00
|
|
|
# Step 5. Do final post-processing
|
|
|
|
yield self._setup_state_group_id_seq()
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
self.progress.done()
|
2018-10-19 20:16:55 -04:00
|
|
|
except Exception:
|
2015-04-17 06:13:05 -04:00
|
|
|
global end_error_exec_info
|
|
|
|
end_error_exec_info = sys.exc_info()
|
|
|
|
logger.exception("")
|
|
|
|
finally:
|
|
|
|
reactor.stop()
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
def _convert_rows(self, table, headers, rows):
|
|
|
|
bool_col_names = BOOLEAN_COLUMNS.get(table, [])
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
bool_cols = [i for i, h in enumerate(headers) if h in bool_col_names]
|
2015-04-28 06:16:44 -04:00
|
|
|
|
2017-10-31 12:58:49 -04:00
|
|
|
class BadValueException(Exception):
|
|
|
|
pass
|
|
|
|
|
2015-04-28 06:16:44 -04:00
|
|
|
def conv(j, col):
|
|
|
|
if j in bool_cols:
|
|
|
|
return bool(col)
|
2019-10-23 10:31:59 -04:00
|
|
|
if isinstance(col, bytes):
|
|
|
|
return bytearray(col)
|
2018-04-06 18:37:36 -04:00
|
|
|
elif isinstance(col, string_types) and "\0" in col:
|
2019-10-31 06:23:24 -04:00
|
|
|
logger.warning(
|
2018-10-19 20:16:55 -04:00
|
|
|
"DROPPING ROW: NUL value in table %s col %s: %r",
|
|
|
|
table,
|
|
|
|
headers[j],
|
|
|
|
col,
|
|
|
|
)
|
|
|
|
raise BadValueException()
|
2015-04-28 06:16:44 -04:00
|
|
|
return col
|
|
|
|
|
2017-10-31 12:58:49 -04:00
|
|
|
outrows = []
|
2015-04-28 06:16:44 -04:00
|
|
|
for i, row in enumerate(rows):
|
2017-10-31 12:58:49 -04:00
|
|
|
try:
|
2018-10-19 20:16:55 -04:00
|
|
|
outrows.append(
|
|
|
|
tuple(conv(j, col) for j, col in enumerate(row) if j > 0)
|
|
|
|
)
|
2017-10-31 12:58:49 -04:00
|
|
|
except BadValueException:
|
|
|
|
pass
|
|
|
|
|
|
|
|
return outrows
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _setup_sent_transactions(self):
|
|
|
|
# Only save things from the last day
|
2016-08-04 06:28:02 -04:00
|
|
|
yesterday = int(time.time() * 1000) - 86400000
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
# And save the max transaction id from each destination
|
|
|
|
select = (
|
|
|
|
"SELECT rowid, * FROM sent_transactions WHERE rowid IN ("
|
|
|
|
"SELECT max(rowid) FROM sent_transactions"
|
|
|
|
" GROUP BY destination"
|
|
|
|
")"
|
|
|
|
)
|
|
|
|
|
|
|
|
def r(txn):
|
|
|
|
txn.execute(select)
|
|
|
|
rows = txn.fetchall()
|
|
|
|
headers = [column[0] for column in txn.description]
|
|
|
|
|
|
|
|
ts_ind = headers.index('ts')
|
|
|
|
|
|
|
|
return headers, [r for r in rows if r[ts_ind] < yesterday]
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
headers, rows = yield self.sqlite_store.runInteraction("select", r)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
2017-10-31 12:58:49 -04:00
|
|
|
rows = self._convert_rows("sent_transactions", headers, rows)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
inserted_rows = len(rows)
|
2015-09-02 06:11:11 -04:00
|
|
|
if inserted_rows:
|
|
|
|
max_inserted_rowid = max(r[0] for r in rows)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
2015-09-02 06:11:11 -04:00
|
|
|
def insert(txn):
|
|
|
|
self.postgres_store.insert_many_txn(
|
|
|
|
txn, "sent_transactions", headers[1:], rows
|
|
|
|
)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
2015-09-02 06:11:11 -04:00
|
|
|
yield self.postgres_store.execute(insert)
|
|
|
|
else:
|
|
|
|
max_inserted_rowid = 0
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
def get_start_id(txn):
|
|
|
|
txn.execute(
|
|
|
|
"SELECT rowid FROM sent_transactions WHERE ts >= ?"
|
|
|
|
" ORDER BY rowid ASC LIMIT 1",
|
2018-10-19 20:16:55 -04:00
|
|
|
(yesterday,),
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
rows = txn.fetchall()
|
|
|
|
if rows:
|
|
|
|
return rows[0][0]
|
|
|
|
else:
|
|
|
|
return 1
|
|
|
|
|
|
|
|
next_chunk = yield self.sqlite_store.execute(get_start_id)
|
|
|
|
next_chunk = max(max_inserted_rowid + 1, next_chunk)
|
|
|
|
|
2019-12-04 05:15:55 -05:00
|
|
|
yield self.postgres_store.simple_insert(
|
2015-04-28 06:16:44 -04:00
|
|
|
table="port_from_sqlite3",
|
2016-08-04 06:28:02 -04:00
|
|
|
values={
|
|
|
|
"table_name": "sent_transactions",
|
|
|
|
"forward_rowid": next_chunk,
|
|
|
|
"backward_rowid": 0,
|
2018-10-19 20:16:55 -04:00
|
|
|
},
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
def get_sent_table_size(txn):
|
|
|
|
txn.execute(
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT count(*) FROM sent_transactions" " WHERE ts >= ?", (yesterday,)
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
size, = txn.fetchone()
|
|
|
|
return int(size)
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
remaining_count = yield self.sqlite_store.execute(get_sent_table_size)
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
total_count = remaining_count + inserted_rows
|
|
|
|
|
2015-04-28 07:40:04 -04:00
|
|
|
defer.returnValue((next_chunk, inserted_rows, total_count))
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
2016-08-04 06:28:02 -04:00
|
|
|
def _get_remaining_count_to_port(self, table, forward_chunk, backward_chunk):
|
|
|
|
frows = yield self.sqlite_store.execute_sql(
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT count(*) FROM %s WHERE rowid >= ?" % (table,), forward_chunk
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
|
2016-08-04 06:28:02 -04:00
|
|
|
brows = yield self.sqlite_store.execute_sql(
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT count(*) FROM %s WHERE rowid <= ?" % (table,), backward_chunk
|
2016-08-04 06:28:02 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
defer.returnValue(frows[0][0] + brows[0][0])
|
2015-04-28 06:16:44 -04:00
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
|
|
|
def _get_already_ported_count(self, table):
|
|
|
|
rows = yield self.postgres_store.execute_sql(
|
2018-10-19 20:16:55 -04:00
|
|
|
"SELECT count(*) FROM %s" % (table,)
|
2015-04-28 06:16:44 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
defer.returnValue(rows[0][0])
|
|
|
|
|
|
|
|
@defer.inlineCallbacks
|
2016-08-04 06:28:02 -04:00
|
|
|
def _get_total_count_to_port(self, table, forward_chunk, backward_chunk):
|
2015-04-28 06:16:44 -04:00
|
|
|
remaining, done = yield defer.gatherResults(
|
|
|
|
[
|
2016-08-04 06:28:02 -04:00
|
|
|
self._get_remaining_count_to_port(table, forward_chunk, backward_chunk),
|
2015-04-28 06:16:44 -04:00
|
|
|
self._get_already_ported_count(table),
|
|
|
|
],
|
|
|
|
consumeErrors=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
remaining = int(remaining) if remaining else 0
|
|
|
|
done = int(done) if done else 0
|
|
|
|
|
|
|
|
defer.returnValue((done, remaining + done))
|
|
|
|
|
2018-04-06 08:48:40 -04:00
|
|
|
def _setup_state_group_id_seq(self):
|
|
|
|
def r(txn):
|
|
|
|
txn.execute("SELECT MAX(id) FROM state_groups")
|
2019-12-02 13:23:41 -05:00
|
|
|
curr_id = txn.fetchone()[0]
|
|
|
|
if not curr_id:
|
|
|
|
return
|
|
|
|
next_id = curr_id + 1
|
2018-10-19 20:16:55 -04:00
|
|
|
txn.execute("ALTER SEQUENCE state_group_id_seq RESTART WITH %s", (next_id,))
|
|
|
|
|
2018-04-06 08:48:40 -04:00
|
|
|
return self.postgres_store.runInteraction("setup_state_group_id_seq", r)
|
|
|
|
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
##############################################
|
2018-10-19 20:16:55 -04:00
|
|
|
# The following is simply UI stuff
|
2015-04-27 12:53:15 -04:00
|
|
|
##############################################
|
|
|
|
|
|
|
|
|
|
|
|
class Progress(object):
|
|
|
|
"""Used to report progress of the port
|
|
|
|
"""
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
def __init__(self):
|
|
|
|
self.tables = {}
|
|
|
|
|
|
|
|
self.start_time = int(time.time())
|
|
|
|
|
|
|
|
def add_table(self, table, cur, size):
|
|
|
|
self.tables[table] = {
|
|
|
|
"start": cur,
|
|
|
|
"num_done": cur,
|
|
|
|
"total": size,
|
|
|
|
"perc": int(cur * 100 / size),
|
|
|
|
}
|
|
|
|
|
|
|
|
def update(self, table, num_done):
|
|
|
|
data = self.tables[table]
|
|
|
|
data["num_done"] = num_done
|
|
|
|
data["perc"] = int(num_done * 100 / data["total"])
|
|
|
|
|
|
|
|
def done(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class CursesProgress(Progress):
|
|
|
|
"""Reports progress to a curses window
|
|
|
|
"""
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
def __init__(self, stdscr):
|
|
|
|
self.stdscr = stdscr
|
|
|
|
|
|
|
|
curses.use_default_colors()
|
|
|
|
curses.curs_set(0)
|
|
|
|
|
|
|
|
curses.init_pair(1, curses.COLOR_RED, -1)
|
|
|
|
curses.init_pair(2, curses.COLOR_GREEN, -1)
|
|
|
|
|
|
|
|
self.last_update = 0
|
|
|
|
|
|
|
|
self.finished = False
|
|
|
|
|
2015-04-28 07:55:29 -04:00
|
|
|
self.total_processed = 0
|
|
|
|
self.total_remaining = 0
|
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
super(CursesProgress, self).__init__()
|
|
|
|
|
|
|
|
def update(self, table, num_done):
|
|
|
|
super(CursesProgress, self).update(table, num_done)
|
|
|
|
|
2015-04-28 07:55:29 -04:00
|
|
|
self.total_processed = 0
|
|
|
|
self.total_remaining = 0
|
|
|
|
for table, data in self.tables.items():
|
|
|
|
self.total_processed += data["num_done"] - data["start"]
|
|
|
|
self.total_remaining += data["total"] - data["num_done"]
|
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
self.render()
|
|
|
|
|
|
|
|
def render(self, force=False):
|
|
|
|
now = time.time()
|
|
|
|
|
|
|
|
if not force and now - self.last_update < 0.2:
|
|
|
|
# reactor.callLater(1, self.render)
|
|
|
|
return
|
|
|
|
|
|
|
|
self.stdscr.clear()
|
|
|
|
|
|
|
|
rows, cols = self.stdscr.getmaxyx()
|
|
|
|
|
|
|
|
duration = int(now) - int(self.start_time)
|
|
|
|
|
|
|
|
minutes, seconds = divmod(duration, 60)
|
2018-10-19 20:16:55 -04:00
|
|
|
duration_str = '%02dm %02ds' % (minutes, seconds)
|
2015-04-27 12:53:15 -04:00
|
|
|
|
|
|
|
if self.finished:
|
|
|
|
status = "Time spent: %s (Done!)" % (duration_str,)
|
|
|
|
else:
|
2015-04-28 07:55:29 -04:00
|
|
|
|
|
|
|
if self.total_processed > 0:
|
|
|
|
left = float(self.total_remaining) / self.total_processed
|
|
|
|
|
|
|
|
est_remaining = (int(now) - self.start_time) * left
|
2015-04-27 12:53:15 -04:00
|
|
|
est_remaining_str = '%02dm %02ds remaining' % divmod(est_remaining, 60)
|
|
|
|
else:
|
|
|
|
est_remaining_str = "Unknown"
|
2018-10-19 20:16:55 -04:00
|
|
|
status = "Time spent: %s (est. remaining: %s)" % (
|
|
|
|
duration_str,
|
|
|
|
est_remaining_str,
|
2015-04-27 12:53:15 -04:00
|
|
|
)
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
self.stdscr.addstr(0, 0, status, curses.A_BOLD)
|
2015-04-27 12:53:15 -04:00
|
|
|
|
|
|
|
max_len = max([len(t) for t in self.tables.keys()])
|
|
|
|
|
|
|
|
left_margin = 5
|
|
|
|
middle_space = 1
|
|
|
|
|
|
|
|
items = self.tables.items()
|
2019-04-03 17:59:48 -04:00
|
|
|
items = sorted(items, key=lambda i: (i[1]["perc"], i[0]))
|
2015-04-27 12:53:15 -04:00
|
|
|
|
|
|
|
for i, (table, data) in enumerate(items):
|
|
|
|
if i + 2 >= rows:
|
|
|
|
break
|
|
|
|
|
|
|
|
perc = data["perc"]
|
|
|
|
|
|
|
|
color = curses.color_pair(2) if perc == 100 else curses.color_pair(1)
|
|
|
|
|
|
|
|
self.stdscr.addstr(
|
2018-10-19 20:16:55 -04:00
|
|
|
i + 2, left_margin + max_len - len(table), table, curses.A_BOLD | color
|
2015-04-27 12:53:15 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
size = 20
|
|
|
|
|
|
|
|
progress = "[%s%s]" % (
|
2016-08-04 06:28:02 -04:00
|
|
|
"#" * int(perc * size / 100),
|
|
|
|
" " * (size - int(perc * size / 100)),
|
2015-04-27 12:53:15 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
self.stdscr.addstr(
|
2018-10-19 20:16:55 -04:00
|
|
|
i + 2,
|
|
|
|
left_margin + max_len + middle_space,
|
2015-04-27 12:53:15 -04:00
|
|
|
"%s %3d%% (%d/%d)" % (progress, perc, data["num_done"], data["total"]),
|
|
|
|
)
|
|
|
|
|
|
|
|
if self.finished:
|
2018-10-19 20:16:55 -04:00
|
|
|
self.stdscr.addstr(rows - 1, 0, "Press any key to exit...")
|
2015-04-27 12:53:15 -04:00
|
|
|
|
|
|
|
self.stdscr.refresh()
|
|
|
|
self.last_update = time.time()
|
|
|
|
|
|
|
|
def done(self):
|
|
|
|
self.finished = True
|
|
|
|
self.render(True)
|
|
|
|
self.stdscr.getch()
|
|
|
|
|
|
|
|
def set_state(self, state):
|
|
|
|
self.stdscr.clear()
|
2018-10-19 20:16:55 -04:00
|
|
|
self.stdscr.addstr(0, 0, state + "...", curses.A_BOLD)
|
2015-04-27 12:53:15 -04:00
|
|
|
self.stdscr.refresh()
|
|
|
|
|
|
|
|
|
|
|
|
class TerminalProgress(Progress):
|
|
|
|
"""Just prints progress to the terminal
|
|
|
|
"""
|
2018-10-19 20:16:55 -04:00
|
|
|
|
2015-04-27 12:53:15 -04:00
|
|
|
def update(self, table, num_done):
|
|
|
|
super(TerminalProgress, self).update(table, num_done)
|
|
|
|
|
|
|
|
data = self.tables[table]
|
|
|
|
|
2018-10-19 20:16:55 -04:00
|
|
|
print(
|
|
|
|
"%s: %d%% (%d/%d)" % (table, data["perc"], data["num_done"], data["total"])
|
2015-04-27 12:53:15 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
def set_state(self, state):
|
2018-10-19 20:16:55 -04:00
|
|
|
print(state + "...")
|
2015-04-27 12:53:15 -04:00
|
|
|
|
|
|
|
|
|
|
|
##############################################
|
|
|
|
##############################################
|
|
|
|
|
|
|
|
|
2015-04-10 13:47:20 -04:00
|
|
|
if __name__ == "__main__":
|
2015-04-28 12:42:36 -04:00
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description="A script to port an existing synapse SQLite database to"
|
2018-10-19 20:16:55 -04:00
|
|
|
" a new PostgreSQL database."
|
2015-04-28 12:42:36 -04:00
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
parser.add_argument("-v", action='store_true')
|
2015-04-10 13:47:20 -04:00
|
|
|
parser.add_argument(
|
2018-10-19 20:16:55 -04:00
|
|
|
"--sqlite-database",
|
|
|
|
required=True,
|
2015-04-28 12:42:36 -04:00
|
|
|
help="The snapshot of the SQLite database file. This must not be"
|
2018-10-19 20:16:55 -04:00
|
|
|
" currently used by a running synapse server",
|
2015-04-28 12:42:36 -04:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-10-19 20:16:55 -04:00
|
|
|
"--postgres-config",
|
|
|
|
type=argparse.FileType('r'),
|
|
|
|
required=True,
|
|
|
|
help="The database config file for the PostgreSQL database",
|
2015-04-28 12:42:36 -04:00
|
|
|
)
|
|
|
|
parser.add_argument(
|
2018-10-19 20:16:55 -04:00
|
|
|
"--curses", action='store_true', help="display a curses based progress UI"
|
2015-04-10 13:47:20 -04:00
|
|
|
)
|
|
|
|
|
2015-04-28 12:42:36 -04:00
|
|
|
parser.add_argument(
|
2018-10-19 20:16:55 -04:00
|
|
|
"--batch-size",
|
|
|
|
type=int,
|
|
|
|
default=1000,
|
2015-04-28 12:42:36 -04:00
|
|
|
help="The number of rows to select from the SQLite table each"
|
2018-10-19 20:16:55 -04:00
|
|
|
" iteration [default=1000]",
|
2015-04-28 12:42:36 -04:00
|
|
|
)
|
2015-04-17 06:13:05 -04:00
|
|
|
|
2015-04-10 13:47:20 -04:00
|
|
|
args = parser.parse_args()
|
2015-04-17 06:13:05 -04:00
|
|
|
|
|
|
|
logging_config = {
|
|
|
|
"level": logging.DEBUG if args.v else logging.INFO,
|
2018-10-19 20:16:55 -04:00
|
|
|
"format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
|
2015-04-17 06:13:05 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if args.curses:
|
|
|
|
logging_config["filename"] = "port-synapse.log"
|
|
|
|
|
|
|
|
logging.basicConfig(**logging_config)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
|
|
|
sqlite_config = {
|
|
|
|
"name": "sqlite3",
|
|
|
|
"args": {
|
|
|
|
"database": args.sqlite_database,
|
|
|
|
"cp_min": 1,
|
|
|
|
"cp_max": 1,
|
|
|
|
"check_same_thread": False,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
hs_config = yaml.safe_load(args.postgres_config)
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
if "database" not in hs_config:
|
|
|
|
sys.stderr.write("The configuration file must have a 'database' section.\n")
|
|
|
|
sys.exit(4)
|
|
|
|
|
|
|
|
postgres_config = hs_config["database"]
|
2015-05-08 08:45:58 -04:00
|
|
|
|
2015-04-28 12:42:36 -04:00
|
|
|
if "name" not in postgres_config:
|
2019-10-23 10:31:59 -04:00
|
|
|
sys.stderr.write("Malformed database config: no 'name'\n")
|
2015-04-28 12:42:36 -04:00
|
|
|
sys.exit(2)
|
|
|
|
if postgres_config["name"] != "psycopg2":
|
2019-10-23 10:31:59 -04:00
|
|
|
sys.stderr.write("Database must use the 'psycopg2' connector.\n")
|
2015-04-28 12:42:36 -04:00
|
|
|
sys.exit(3)
|
|
|
|
|
2019-10-23 10:31:59 -04:00
|
|
|
config = HomeServerConfig()
|
|
|
|
config.parse_config_dict(hs_config, "", "")
|
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
def start(stdscr=None):
|
|
|
|
if stdscr:
|
|
|
|
progress = CursesProgress(stdscr)
|
|
|
|
else:
|
|
|
|
progress = TerminalProgress()
|
|
|
|
|
|
|
|
porter = Porter(
|
|
|
|
sqlite_config=sqlite_config,
|
|
|
|
progress=progress,
|
|
|
|
batch_size=args.batch_size,
|
2019-10-23 10:31:59 -04:00
|
|
|
hs_config=config,
|
2015-04-17 06:13:05 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
reactor.callWhenRunning(porter.run)
|
|
|
|
|
|
|
|
reactor.run()
|
|
|
|
|
|
|
|
if args.curses:
|
|
|
|
curses.wrapper(start)
|
|
|
|
else:
|
|
|
|
start()
|
2015-04-10 13:47:20 -04:00
|
|
|
|
2015-04-17 06:13:05 -04:00
|
|
|
if end_error_exec_info:
|
|
|
|
exc_type, exc_value, exc_traceback = end_error_exec_info
|
|
|
|
traceback.print_exception(exc_type, exc_value, exc_traceback)
|
2019-12-04 12:48:23 -05:00
|
|
|
sys.exit(5)
|