database.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. import logging
  17. import os
  18. from synapse.config._base import Config, ConfigError
  19. logger = logging.getLogger(__name__)
  20. NON_SQLITE_DATABASE_PATH_WARNING = """\
  21. Ignoring 'database_path' setting: not using a sqlite3 database.
  22. --------------------------------------------------------------------------------
  23. """
  24. DEFAULT_CONFIG = """\
  25. ## Database ##
  26. # The 'database' setting defines the database that synapse uses to store all of
  27. # its data.
  28. #
  29. # 'name' gives the database engine to use: either 'sqlite3' (for SQLite) or
  30. # 'psycopg2' (for PostgreSQL).
  31. #
  32. # 'args' gives options which are passed through to the database engine,
  33. # except for options starting 'cp_', which are used to configure the Twisted
  34. # connection pool. For a reference to valid arguments, see:
  35. # * for sqlite: https://docs.python.org/3/library/sqlite3.html#sqlite3.connect
  36. # * for postgres: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS
  37. # * for the connection pool: https://twistedmatrix.com/documents/current/api/twisted.enterprise.adbapi.ConnectionPool.html#__init__
  38. #
  39. #
  40. # Example SQLite configuration:
  41. #
  42. #database:
  43. # name: sqlite3
  44. # args:
  45. # database: /path/to/homeserver.db
  46. #
  47. #
  48. # Example Postgres configuration:
  49. #
  50. #database:
  51. # name: psycopg2
  52. # args:
  53. # user: synapse_user
  54. # password: secretpassword
  55. # database: synapse
  56. # host: localhost
  57. # cp_min: 5
  58. # cp_max: 10
  59. #
  60. # For more information on using Synapse with Postgres, see `docs/postgres.md`.
  61. #
  62. database:
  63. name: sqlite3
  64. args:
  65. database: %(database_path)s
  66. """
  67. class DatabaseConnectionConfig:
  68. """Contains the connection config for a particular database.
  69. Args:
  70. name: A label for the database, used for logging.
  71. db_config: The config for a particular database, as per `database`
  72. section of main config. Has three fields: `name` for database
  73. module name, `args` for the args to give to the database
  74. connector, and optional `data_stores` that is a list of stores to
  75. provision on this database (defaulting to all).
  76. """
  77. def __init__(self, name: str, db_config: dict):
  78. db_engine = db_config.get("name", "sqlite3")
  79. if db_engine not in ("sqlite3", "psycopg2"):
  80. raise ConfigError("Unsupported database type %r" % (db_engine,))
  81. if db_engine == "sqlite3":
  82. db_config.setdefault("args", {}).update(
  83. {"cp_min": 1, "cp_max": 1, "check_same_thread": False}
  84. )
  85. data_stores = db_config.get("data_stores")
  86. if data_stores is None:
  87. data_stores = ["main", "state"]
  88. self.name = name
  89. self.config = db_config
  90. # The `data_stores` config is actually talking about `databases` (we
  91. # changed the name).
  92. self.databases = data_stores
  93. class DatabaseConfig(Config):
  94. section = "database"
  95. def __init__(self, *args, **kwargs):
  96. super().__init__(*args, **kwargs)
  97. self.databases = []
  98. def read_config(self, config, **kwargs):
  99. # We *experimentally* support specifying multiple databases via the
  100. # `databases` key. This is a map from a label to database config in the
  101. # same format as the `database` config option, plus an extra
  102. # `data_stores` key to specify which data store goes where. For example:
  103. #
  104. # databases:
  105. # master:
  106. # name: psycopg2
  107. # data_stores: ["main"]
  108. # args: {}
  109. # state:
  110. # name: psycopg2
  111. # data_stores: ["state"]
  112. # args: {}
  113. multi_database_config = config.get("databases")
  114. database_config = config.get("database")
  115. database_path = config.get("database_path")
  116. if multi_database_config and database_config:
  117. raise ConfigError("Can't specify both 'database' and 'databases' in config")
  118. if multi_database_config:
  119. if database_path:
  120. raise ConfigError("Can't specify 'database_path' with 'databases'")
  121. self.databases = [
  122. DatabaseConnectionConfig(name, db_conf)
  123. for name, db_conf in multi_database_config.items()
  124. ]
  125. if database_config:
  126. self.databases = [DatabaseConnectionConfig("master", database_config)]
  127. if database_path:
  128. if self.databases and self.databases[0].name != "sqlite3":
  129. logger.warning(NON_SQLITE_DATABASE_PATH_WARNING)
  130. return
  131. database_config = {"name": "sqlite3", "args": {}}
  132. self.databases = [DatabaseConnectionConfig("master", database_config)]
  133. self.set_databasepath(database_path)
  134. def generate_config_section(self, data_dir_path, **kwargs):
  135. return DEFAULT_CONFIG % {
  136. "database_path": os.path.join(data_dir_path, "homeserver.db")
  137. }
  138. def read_arguments(self, args):
  139. """
  140. Cases for the cli input:
  141. - If no databases are configured and no database_path is set, raise.
  142. - No databases and only database_path available ==> sqlite3 db.
  143. - If there are multiple databases and a database_path raise an error.
  144. - If the database set in the config file is sqlite then
  145. overwrite with the command line argument.
  146. """
  147. if args.database_path is None:
  148. if not self.databases:
  149. raise ConfigError("No database config provided")
  150. return
  151. if len(self.databases) == 0:
  152. database_config = {"name": "sqlite3", "args": {}}
  153. self.databases = [DatabaseConnectionConfig("master", database_config)]
  154. self.set_databasepath(args.database_path)
  155. return
  156. if self.get_single_database().name == "sqlite3":
  157. self.set_databasepath(args.database_path)
  158. else:
  159. logger.warning(NON_SQLITE_DATABASE_PATH_WARNING)
  160. def set_databasepath(self, database_path):
  161. if database_path != ":memory:":
  162. database_path = self.abspath(database_path)
  163. self.databases[0].config["args"]["database"] = database_path
  164. @staticmethod
  165. def add_arguments(parser):
  166. db_group = parser.add_argument_group("database")
  167. db_group.add_argument(
  168. "-d",
  169. "--database-path",
  170. metavar="SQLITE_DATABASE_PATH",
  171. help="The path to a sqlite database to use.",
  172. )
  173. def get_single_database(self) -> DatabaseConnectionConfig:
  174. """Returns the database if there is only one, useful for e.g. tests"""
  175. if not self.databases:
  176. raise Exception("More than one database exists")
  177. return self.databases[0]