You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

297 lines
10 KiB

  1. #!/usr/bin/env bash
  2. #
  3. # This script generates SQL files for creating a brand new Synapse DB with the latest
  4. # schema, on both SQLite3 and Postgres.
  5. export PGHOST="localhost"
  6. POSTGRES_MAIN_DB_NAME="synapse_full_schema_main.$$"
  7. POSTGRES_COMMON_DB_NAME="synapse_full_schema_common.$$"
  8. POSTGRES_STATE_DB_NAME="synapse_full_schema_state.$$"
  9. REQUIRED_DEPS=("matrix-synapse" "psycopg2")
  10. usage() {
  11. echo
  12. echo "Usage: $0 -p <postgres_username> -o <path> [-c] [-n <schema number>] [-h]"
  13. echo
  14. echo "-p <postgres_username>"
  15. echo " Username to connect to local postgres instance. The password will be requested"
  16. echo " during script execution."
  17. echo "-c"
  18. echo " CI mode. Prints every command that the script runs."
  19. echo "-o <path>"
  20. echo " Directory to output full schema files to."
  21. echo "-n <schema number>"
  22. echo " Schema number for the new snapshot. Used to set the location of files within "
  23. echo " the output directory, mimicking that of synapse/storage/schemas."
  24. echo " Defaults to 9999."
  25. echo "-h"
  26. echo " Display this help text."
  27. echo ""
  28. echo " NB: make sure to run this against the *oldest* supported version of postgres,"
  29. echo " or else pg_dump might output non-backwards-compatible syntax."
  30. }
  31. SCHEMA_NUMBER="9999"
  32. while getopts "p:co:hn:" opt; do
  33. case $opt in
  34. p)
  35. export PGUSER=$OPTARG
  36. ;;
  37. c)
  38. # Print all commands that are being executed
  39. set -x
  40. ;;
  41. o)
  42. command -v realpath > /dev/null || (echo "The -o flag requires the 'realpath' binary to be installed" && exit 1)
  43. OUTPUT_DIR="$(realpath "$OPTARG")"
  44. ;;
  45. h)
  46. usage
  47. exit
  48. ;;
  49. n)
  50. SCHEMA_NUMBER="$OPTARG"
  51. ;;
  52. \?)
  53. echo "ERROR: Invalid option: -$OPTARG" >&2
  54. usage
  55. exit
  56. ;;
  57. esac
  58. done
  59. # Check that required dependencies are installed
  60. unsatisfied_requirements=()
  61. for dep in "${REQUIRED_DEPS[@]}"; do
  62. pip show "$dep" --quiet || unsatisfied_requirements+=("$dep")
  63. done
  64. if [ ${#unsatisfied_requirements} -ne 0 ]; then
  65. echo "Please install the following python packages: ${unsatisfied_requirements[*]}"
  66. exit 1
  67. fi
  68. if [ -z "$PGUSER" ]; then
  69. echo "No postgres username supplied"
  70. usage
  71. exit 1
  72. fi
  73. if [ -z "$OUTPUT_DIR" ]; then
  74. echo "No output directory supplied"
  75. usage
  76. exit 1
  77. fi
  78. # Create the output directory if it doesn't exist
  79. mkdir -p "$OUTPUT_DIR"
  80. read -rsp "Postgres password for '$PGUSER': " PGPASSWORD
  81. echo ""
  82. export PGPASSWORD
  83. # Exit immediately if a command fails
  84. set -e
  85. # cd to root of the synapse directory
  86. cd "$(dirname "$0")/.."
  87. # Create temporary SQLite and Postgres homeserver db configs and key file
  88. TMPDIR=$(mktemp -d)
  89. KEY_FILE=$TMPDIR/test.signing.key # default Synapse signing key path
  90. SQLITE_CONFIG=$TMPDIR/sqlite.conf
  91. SQLITE_MAIN_DB=$TMPDIR/main.db
  92. SQLITE_STATE_DB=$TMPDIR/state.db
  93. SQLITE_COMMON_DB=$TMPDIR/common.db
  94. POSTGRES_CONFIG=$TMPDIR/postgres.conf
  95. # Ensure these files are delete on script exit
  96. cleanup() {
  97. echo "Cleaning up temporary sqlite database and config files..."
  98. rm -r "$TMPDIR"
  99. echo "Cleaning up temporary Postgres database..."
  100. dropdb --if-exists "$POSTGRES_COMMON_DB_NAME"
  101. dropdb --if-exists "$POSTGRES_MAIN_DB_NAME"
  102. dropdb --if-exists "$POSTGRES_STATE_DB_NAME"
  103. }
  104. trap 'cleanup' EXIT
  105. cat > "$SQLITE_CONFIG" <<EOF
  106. server_name: "test"
  107. signing_key_path: "$KEY_FILE"
  108. macaroon_secret_key: "abcde"
  109. report_stats: false
  110. databases:
  111. common:
  112. name: "sqlite3"
  113. data_stores: []
  114. args:
  115. database: "$SQLITE_COMMON_DB"
  116. main:
  117. name: "sqlite3"
  118. data_stores: ["main"]
  119. args:
  120. database: "$SQLITE_MAIN_DB"
  121. state:
  122. name: "sqlite3"
  123. data_stores: ["state"]
  124. args:
  125. database: "$SQLITE_STATE_DB"
  126. # Suppress the key server warning.
  127. trusted_key_servers: []
  128. EOF
  129. cat > "$POSTGRES_CONFIG" <<EOF
  130. server_name: "test"
  131. signing_key_path: "$KEY_FILE"
  132. macaroon_secret_key: "abcde"
  133. report_stats: false
  134. databases:
  135. common:
  136. name: "psycopg2"
  137. data_stores: []
  138. args:
  139. user: "$PGUSER"
  140. host: "$PGHOST"
  141. password: "$PGPASSWORD"
  142. database: "$POSTGRES_COMMON_DB_NAME"
  143. main:
  144. name: "psycopg2"
  145. data_stores: ["main"]
  146. args:
  147. user: "$PGUSER"
  148. host: "$PGHOST"
  149. password: "$PGPASSWORD"
  150. database: "$POSTGRES_MAIN_DB_NAME"
  151. state:
  152. name: "psycopg2"
  153. data_stores: ["state"]
  154. args:
  155. user: "$PGUSER"
  156. host: "$PGHOST"
  157. password: "$PGPASSWORD"
  158. database: "$POSTGRES_STATE_DB_NAME"
  159. # Suppress the key server warning.
  160. trusted_key_servers: []
  161. EOF
  162. # Generate the server's signing key.
  163. echo "Generating SQLite3 db schema..."
  164. python -m synapse.app.homeserver --generate-keys -c "$SQLITE_CONFIG"
  165. # Make sure the SQLite3 database is using the latest schema and has no pending background update.
  166. echo "Running db background jobs..."
  167. synapse/_scripts/update_synapse_database.py --database-config "$SQLITE_CONFIG" --run-background-updates
  168. # Create the PostgreSQL database.
  169. echo "Creating postgres databases..."
  170. createdb --lc-collate=C --lc-ctype=C --template=template0 "$POSTGRES_COMMON_DB_NAME"
  171. createdb --lc-collate=C --lc-ctype=C --template=template0 "$POSTGRES_MAIN_DB_NAME"
  172. createdb --lc-collate=C --lc-ctype=C --template=template0 "$POSTGRES_STATE_DB_NAME"
  173. echo "Running db background jobs..."
  174. synapse/_scripts/update_synapse_database.py --database-config "$POSTGRES_CONFIG" --run-background-updates
  175. echo "Dropping unwanted db tables..."
  176. # Some common tables are created and updated by Synapse itself and do not belong in the
  177. # schema.
  178. DROP_APP_MANAGED_TABLES="
  179. DROP TABLE schema_version;
  180. DROP TABLE schema_compat_version;
  181. DROP TABLE applied_schema_deltas;
  182. DROP TABLE applied_module_schemas;
  183. "
  184. # Other common tables are not created by Synapse and do belong in the schema.
  185. # TODO: we could derive DROP_COMMON_TABLES from the dump of the common-only DB. But
  186. # since there's only one table there, I haven't bothered to do so.
  187. DROP_COMMON_TABLES="$DROP_APP_MANAGED_TABLES
  188. DROP TABLE background_updates;
  189. "
  190. sqlite3 "$SQLITE_COMMON_DB" <<< "$DROP_APP_MANAGED_TABLES"
  191. sqlite3 "$SQLITE_MAIN_DB" <<< "$DROP_COMMON_TABLES"
  192. sqlite3 "$SQLITE_STATE_DB" <<< "$DROP_COMMON_TABLES"
  193. psql "$POSTGRES_COMMON_DB_NAME" -w <<< "$DROP_APP_MANAGED_TABLES"
  194. psql "$POSTGRES_MAIN_DB_NAME" -w <<< "$DROP_COMMON_TABLES"
  195. psql "$POSTGRES_STATE_DB_NAME" -w <<< "$DROP_COMMON_TABLES"
  196. # For Reasons(TM), SQLite's `.schema` also dumps out "shadow tables", the implementation
  197. # details behind full text search tables. Omit these from the dumps.
  198. sqlite3 "$SQLITE_MAIN_DB" <<< "
  199. DROP TABLE event_search_content;
  200. DROP TABLE event_search_segments;
  201. DROP TABLE event_search_segdir;
  202. DROP TABLE event_search_docsize;
  203. DROP TABLE event_search_stat;
  204. DROP TABLE user_directory_search_content;
  205. DROP TABLE user_directory_search_segments;
  206. DROP TABLE user_directory_search_segdir;
  207. DROP TABLE user_directory_search_docsize;
  208. DROP TABLE user_directory_search_stat;
  209. "
  210. echo "Dumping SQLite3 schema..."
  211. mkdir -p "$OUTPUT_DIR/"{common,main,state}"/full_schemas/$SCHEMA_NUMBER"
  212. sqlite3 "$SQLITE_COMMON_DB" ".schema" > "$OUTPUT_DIR/common/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  213. sqlite3 "$SQLITE_COMMON_DB" ".dump --data-only --nosys" >> "$OUTPUT_DIR/common/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  214. sqlite3 "$SQLITE_MAIN_DB" ".schema" > "$OUTPUT_DIR/main/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  215. sqlite3 "$SQLITE_MAIN_DB" ".dump --data-only --nosys" >> "$OUTPUT_DIR/main/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  216. sqlite3 "$SQLITE_STATE_DB" ".schema" > "$OUTPUT_DIR/state/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  217. sqlite3 "$SQLITE_STATE_DB" ".dump --data-only --nosys" >> "$OUTPUT_DIR/state/full_schemas/$SCHEMA_NUMBER/full.sql.sqlite"
  218. cleanup_pg_schema() {
  219. # Cleanup as follows:
  220. # - Remove empty lines. pg_dump likes to output a lot of these.
  221. # - Remove comment-only lines. pg_dump also likes to output a lot of these to visually
  222. # separate tables etc.
  223. # - Remove "public." prefix --- the schema name.
  224. # - Remove "SET" commands. Last time I ran this, the output commands were
  225. # SET statement_timeout = 0;
  226. # SET lock_timeout = 0;
  227. # SET idle_in_transaction_session_timeout = 0;
  228. # SET client_encoding = 'UTF8';
  229. # SET standard_conforming_strings = on;
  230. # SET check_function_bodies = false;
  231. # SET xmloption = content;
  232. # SET client_min_messages = warning;
  233. # SET row_security = off;
  234. # SET default_table_access_method = heap;
  235. # - Very carefully remove specific SELECT statements. We CANNOT blanket remove all
  236. # SELECT statements because some of those have side-effects which we do want in the
  237. # schema. Last time I ran this, the only SELECTS were
  238. # SELECT pg_catalog.set_config('search_path', '', false);
  239. # and
  240. # SELECT pg_catalog.setval(text, bigint, bool);
  241. # We do want to remove the former, but the latter is important. If the last argument
  242. # is `true` or omitted, this marks the given integer as having been consumed and
  243. # will NOT appear as the nextval.
  244. sed -e '/^$/d' \
  245. -e '/^--/d' \
  246. -e 's/public\.//g' \
  247. -e '/^SET /d' \
  248. -e '/^SELECT pg_catalog.set_config/d'
  249. }
  250. echo "Dumping Postgres schema..."
  251. pg_dump --format=plain --schema-only --no-tablespaces --no-acl --no-owner "$POSTGRES_COMMON_DB_NAME" | cleanup_pg_schema > "$OUTPUT_DIR/common/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  252. pg_dump --format=plain --data-only --inserts --no-tablespaces --no-acl --no-owner "$POSTGRES_COMMON_DB_NAME" | cleanup_pg_schema >> "$OUTPUT_DIR/common/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  253. pg_dump --format=plain --schema-only --no-tablespaces --no-acl --no-owner "$POSTGRES_MAIN_DB_NAME" | cleanup_pg_schema > "$OUTPUT_DIR/main/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  254. pg_dump --format=plain --data-only --inserts --no-tablespaces --no-acl --no-owner "$POSTGRES_MAIN_DB_NAME" | cleanup_pg_schema >> "$OUTPUT_DIR/main/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  255. pg_dump --format=plain --schema-only --no-tablespaces --no-acl --no-owner "$POSTGRES_STATE_DB_NAME" | cleanup_pg_schema > "$OUTPUT_DIR/state/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  256. pg_dump --format=plain --data-only --inserts --no-tablespaces --no-acl --no-owner "$POSTGRES_STATE_DB_NAME" | cleanup_pg_schema >> "$OUTPUT_DIR/state/full_schemas/$SCHEMA_NUMBER/full.sql.postgres"
  257. echo "Done! Files dumped to: $OUTPUT_DIR"