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.
 
 
 
 
 
 

214 lines
7.2 KiB

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